Remove an unnecessary list_remove_all() call in chat().
[privoxy.git] / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 1.322 2010/07/21 14:30:40 fabiankeil 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-2010 the
10  *                Privoxy team. http://www.privoxy.org/
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  *********************************************************************/
35
36
37 #include "config.h"
38
39 #include <stdio.h>
40 #include <sys/types.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <signal.h>
44 #include <fcntl.h>
45 #include <errno.h>
46 #include <assert.h>
47
48 #ifdef _WIN32
49 # ifndef FEATURE_PTHREAD
50 #  ifndef STRICT
51 #   define STRICT
52 #  endif
53 #  include <windows.h>
54 #  include <process.h>
55 # endif /* ndef FEATURE_PTHREAD */
56
57 # include "win32.h"
58 # ifndef _WIN_CONSOLE
59 #  include "w32log.h"
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
62
63 #else /* ifndef _WIN32 */
64
65 # if !defined (__OS2__)
66 # include <unistd.h>
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
72
73 #ifdef sun
74 #include <sys/termios.h>
75 #endif /* sun */
76
77 #ifdef unix
78 #include <pwd.h>
79 #include <grp.h>
80 #endif
81
82 # include <signal.h>
83
84 # ifdef __BEOS__
85 #  include <socket.h>  /* BeOS has select() for sockets only. */
86 #  include <OS.h>      /* declarations for threads and stuff. */
87 # endif
88
89 # if defined(__EMX__) || defined(__OS2__)
90 #  include <sys/select.h>  /* OS/2/EMX needs a little help with select */
91 # endif
92 # ifdef __OS2__
93 #define INCL_DOS
94 # include <os2.h>
95 #define bzero(B,N) memset(B,0x00,n)
96 # endif
97
98 # ifndef FD_ZERO
99 #  include <select.h>
100 # endif
101
102 #endif
103
104 #include "project.h"
105 #include "list.h"
106 #include "jcc.h"
107 #include "filters.h"
108 #include "loaders.h"
109 #include "parsers.h"
110 #include "miscutil.h"
111 #include "errlog.h"
112 #include "jbsockets.h"
113 #include "gateway.h"
114 #include "actions.h"
115 #include "cgi.h"
116 #include "loadcfg.h"
117 #include "urlmatch.h"
118
119 const char jcc_h_rcs[] = JCC_H_VERSION;
120 const char project_h_rcs[] = PROJECT_H_VERSION;
121
122 int daemon_mode = 1;
123 struct client_state  clients[1];
124 struct file_list     files[1];
125
126 #ifdef FEATURE_STATISTICS
127 int urls_read     = 0;     /* total nr of urls read inc rejected */
128 int urls_rejected = 0;     /* total nr of urls rejected */
129 #endif /* def FEATURE_STATISTICS */
130
131 #ifdef FEATURE_GRACEFUL_TERMINATION
132 int g_terminate = 0;
133 #endif
134
135 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
136 static void sig_handler(int the_signal);
137 #endif
138 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
139 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
140 static jb_err get_server_headers(struct client_state *csp);
141 static const char *crunch_reason(const struct http_response *rsp);
142 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
143 static char *get_request_line(struct client_state *csp);
144 static jb_err receive_client_request(struct client_state *csp);
145 static jb_err parse_client_request(struct client_state *csp);
146 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
147 static jb_err change_request_destination(struct client_state *csp);
148 static void chat(struct client_state *csp);
149 static void serve(struct client_state *csp);
150 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
151 static void usage(const char *myname);
152 #endif
153 static void initialize_mutexes(void);
154 static jb_socket bind_port_helper(struct configuration_spec *config);
155 static void listen_loop(void);
156
157 #ifdef AMIGA
158 void serve(struct client_state *csp);
159 #else /* ifndef AMIGA */
160 static void serve(struct client_state *csp);
161 #endif /* def AMIGA */
162
163 #ifdef __BEOS__
164 static int32 server_thread(void *data);
165 #endif /* def __BEOS__ */
166
167 #ifdef _WIN32
168 #define sleep(N)  Sleep(((N) * 1000))
169 #endif
170
171 #ifdef __OS2__
172 #define sleep(N)  DosSleep(((N) * 100))
173 #endif
174
175 #ifdef MUTEX_LOCKS_AVAILABLE
176 /*
177  * XXX: Does the locking stuff really belong in this file?
178  */
179 privoxy_mutex_t log_mutex;
180 privoxy_mutex_t log_init_mutex;
181 privoxy_mutex_t connection_reuse_mutex;
182
183 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
184 privoxy_mutex_t resolver_mutex;
185 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
186
187 #ifndef HAVE_GMTIME_R
188 privoxy_mutex_t gmtime_mutex;
189 #endif /* ndef HAVE_GMTIME_R */
190
191 #ifndef HAVE_LOCALTIME_R
192 privoxy_mutex_t localtime_mutex;
193 #endif /* ndef HAVE_GMTIME_R */
194
195 #ifndef HAVE_RANDOM
196 privoxy_mutex_t rand_mutex;
197 #endif /* ndef HAVE_RANDOM */
198
199 #endif /* def MUTEX_LOCKS_AVAILABLE */
200
201 #if defined(unix)
202 const char *basedir = NULL;
203 const char *pidfile = NULL;
204 static int received_hup_signal = 0;
205 #endif /* defined unix */
206
207 /* HTTP snipplets. */
208 static const char CSUCCEED[] =
209    "HTTP/1.0 200 Connection established\r\n"
210    "Proxy-Agent: Privoxy/" VERSION "\r\n\r\n";
211
212 static const char CHEADER[] =
213    "HTTP/1.0 400 Invalid header received from client\r\n"
214    "Proxy-Agent: Privoxy " VERSION "\r\n"
215    "Content-Type: text/plain\r\n"
216    "Connection: close\r\n\r\n"
217    "Invalid header received from client.\r\n";
218
219 static const char FTP_RESPONSE[] =
220    "HTTP/1.0 400 Invalid request received from client\r\n"
221    "Content-Type: text/plain\r\n"
222    "Connection: close\r\n\r\n"
223    "Invalid request. Privoxy doesn't support FTP.\r\n";
224
225 static const char GOPHER_RESPONSE[] =
226    "HTTP/1.0 400 Invalid request received from client\r\n"
227    "Content-Type: text/plain\r\n"
228    "Connection: close\r\n\r\n"
229    "Invalid request. Privoxy doesn't support gopher.\r\n";
230
231 /* XXX: should be a template */
232 static const char MISSING_DESTINATION_RESPONSE[] =
233    "HTTP/1.0 400 Bad request received from client\r\n"
234    "Proxy-Agent: Privoxy " VERSION "\r\n"
235    "Content-Type: text/plain\r\n"
236    "Connection: close\r\n\r\n"
237    "Bad request. Privoxy was unable to extract the destination.\r\n";
238
239 /* XXX: should be a template */
240 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
241    "HTTP/1.0 502 Server or forwarder response invalid\r\n"
242    "Proxy-Agent: Privoxy " VERSION "\r\n"
243    "Content-Type: text/plain\r\n"
244    "Connection: close\r\n\r\n"
245    "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
246
247 /* XXX: should be a template */
248 static const char MESSED_UP_REQUEST_RESPONSE[] =
249    "HTTP/1.0 400 Malformed request after rewriting\r\n"
250    "Proxy-Agent: Privoxy " VERSION "\r\n"
251    "Content-Type: text/plain\r\n"
252    "Connection: close\r\n\r\n"
253    "Bad request. Messed up with header filters.\r\n";
254
255 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
256    "HTTP/1.0 503 Too many open connections\r\n"
257    "Proxy-Agent: Privoxy " VERSION "\r\n"
258    "Content-Type: text/plain\r\n"
259    "Connection: close\r\n\r\n"
260    "Maximum number of open connections reached.\r\n";
261
262 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
263    "HTTP/1.0 504 Connection timeout\r\n"
264    "Proxy-Agent: Privoxy " VERSION "\r\n"
265    "Content-Type: text/plain\r\n"
266    "Connection: close\r\n\r\n"
267    "The connection timed out because the client request didn't arrive in time.\r\n";
268
269 /* A function to crunch a response */
270 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
271
272 /* Crunch function flags */
273 #define CF_NO_FLAGS        0
274 /* Cruncher applies to forced requests as well */
275 #define CF_IGNORE_FORCE    1
276 /* Crunched requests are counted for the block statistics */
277 #define CF_COUNT_AS_REJECT 2
278
279 /* A crunch function and its flags */
280 struct cruncher
281 {
282    const crunch_func_ptr cruncher;
283    const int flags;
284 };
285
286 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
287
288 /* Complete list of cruncher functions */
289 static const struct cruncher crunchers_all[] = {
290    { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
291    { block_url,       CF_COUNT_AS_REJECT },
292 #ifdef FEATURE_TRUST
293    { trust_url,       CF_COUNT_AS_REJECT },
294 #endif /* def FEATURE_TRUST */
295    { redirect_url,    CF_NO_FLAGS  },
296    { dispatch_cgi,    CF_IGNORE_FORCE},
297    { NULL,            0 }
298 };
299
300 /* Light version, used after tags are applied */
301 static const struct cruncher crunchers_light[] = {
302    { block_url,       CF_COUNT_AS_REJECT },
303    { redirect_url,    CF_NO_FLAGS },
304    { NULL,            0 }
305 };
306
307
308 /*
309  * XXX: Don't we really mean
310  *
311  * #if defined(unix)
312  *
313  * here?
314  */
315 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
316 /*********************************************************************
317  *
318  * Function    :  sig_handler 
319  *
320  * Description :  Signal handler for different signals.
321  *                Exit gracefully on TERM and INT
322  *                or set a flag that will cause the errlog
323  *                to be reopened by the main thread on HUP.
324  *
325  * Parameters  :
326  *          1  :  the_signal = the signal cause this function to call
327  *
328  * Returns     :  - 
329  *
330  *********************************************************************/
331 static void sig_handler(int the_signal)
332 {
333    switch(the_signal)
334    {
335       case SIGTERM:
336       case SIGINT:
337          log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
338 #if defined(unix)
339          if(pidfile)
340          {
341             unlink(pidfile);
342          }
343 #endif /* unix */
344          exit(the_signal);
345          break;
346
347       case SIGHUP:
348 #if defined(unix)
349          received_hup_signal = 1;
350 #endif
351          break;         
352
353       default:
354          /* 
355           * We shouldn't be here, unless we catch signals
356           * in main() that we can't handle here!
357           */
358          log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
359    }
360    return;
361
362 }
363 #endif
364
365
366 /*********************************************************************
367  *
368  * Function    :  client_protocol_is_unsupported
369  *
370  * Description :  Checks if the client used a known unsupported
371  *                protocol and deals with it by sending an error
372  *                response.
373  *
374  * Parameters  :
375  *          1  :  csp = Current client state (buffers, headers, etc...)
376  *          2  :  req = the first request line send by the client
377  *
378  * Returns     :  TRUE if an error response has been generated, or
379  *                FALSE if the request doesn't look invalid.
380  *
381  *********************************************************************/
382 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
383 {
384    /*
385     * If it's a FTP or gopher request, we don't support it.
386     *
387     * These checks are better than nothing, but they might
388     * not work in all configurations and some clients might
389     * have problems digesting the answer.
390     *
391     * They should, however, never cause more problems than
392     * Privoxy's old behaviour (returning the misleading HTML
393     * error message:
394     *
395     * "Could not resolve http://(ftp|gopher)://example.org").
396     */
397    if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
398    {
399       const char *response = NULL;
400       const char *protocol = NULL;
401
402       if (!strncmpic(req, "GET ftp://", 10))
403       {
404          response = FTP_RESPONSE;
405          protocol = "FTP";
406       }
407       else
408       {
409          response = GOPHER_RESPONSE;
410          protocol = "GOPHER";
411       }
412       log_error(LOG_LEVEL_ERROR,
413          "%s tried to use Privoxy as %s proxy: %s",
414          csp->ip_addr_str, protocol, req);
415       log_error(LOG_LEVEL_CLF,
416          "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
417       freez(req);
418       write_socket(csp->cfd, response, strlen(response));
419
420       return TRUE;
421    }
422
423    return FALSE;
424 }
425
426
427 /*********************************************************************
428  *
429  * Function    :  get_request_destination_elsewhere
430  *
431  * Description :  If the client's request was redirected into
432  *                Privoxy without the client's knowledge,
433  *                the request line lacks the destination host.
434  *
435  *                This function tries to get it elsewhere,
436  *                provided accept-intercepted-requests is enabled.
437  *
438  *                "Elsewhere" currently only means "Host: header",
439  *                but in the future we may ask the redirecting
440  *                packet filter to look the destination up.
441  *
442  *                If the destination stays unknown, an error
443  *                response is send to the client and headers
444  *                are freed so that chat() can return directly.
445  *
446  * Parameters  :
447  *          1  :  csp = Current client state (buffers, headers, etc...)
448  *          2  :  headers = a header list
449  *
450  * Returns     :  JB_ERR_OK if the destination is now known, or
451  *                JB_ERR_PARSE if it isn't.
452  *
453  *********************************************************************/
454 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
455 {
456    char *req;
457
458    if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
459    {
460       log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
461          " Privoxy isn't configured to accept intercepted requests.",
462          csp->ip_addr_str, csp->http->cmd);
463       /* XXX: Use correct size */
464       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
465          csp->ip_addr_str, csp->http->cmd);
466
467       write_socket(csp->cfd, CHEADER, strlen(CHEADER));
468       destroy_list(headers);
469
470       return JB_ERR_PARSE;
471    }
472    else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
473    {
474 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
475       /* Split the domain we just got for pattern matching */
476       init_domain_components(csp->http);
477 #endif
478
479       return JB_ERR_OK;
480    }
481    else
482    {
483       /* We can't work without destination. Go spread the news.*/
484
485       req = list_to_text(headers);
486       chomp(req);
487       /* XXX: Use correct size */
488       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
489          csp->ip_addr_str, csp->http->cmd);
490       log_error(LOG_LEVEL_ERROR,
491          "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
492          csp->ip_addr_str, csp->http->cmd, req);
493       freez(req);
494
495       write_socket(csp->cfd, MISSING_DESTINATION_RESPONSE, strlen(MISSING_DESTINATION_RESPONSE));
496       destroy_list(headers);
497
498       return JB_ERR_PARSE;
499    }
500    /*
501     * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
502     * to get the destination IP address, use it as host directly
503     * or do a reverse DNS lookup first.
504     */
505 }
506
507
508 /*********************************************************************
509  *
510  * Function    :  get_server_headers
511  *
512  * Description :  Parses server headers in iob and fills them
513  *                into csp->headers so that they can later be
514  *                handled by sed().
515  *
516  * Parameters  :
517  *          1  :  csp = Current client state (buffers, headers, etc...)
518  *
519  * Returns     :  JB_ERR_OK if everything went fine, or
520  *                JB_ERR_PARSE if the headers were incomplete.
521  *
522  *********************************************************************/
523 static jb_err get_server_headers(struct client_state *csp)
524 {
525    int continue_hack_in_da_house = 0;
526    char * header;
527
528    while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
529    {
530       if (header == NULL)
531       {
532          /*
533           * continue hack in da house. Ignore the ending of
534           * this head and continue enlisting header lines.
535           * The reason is described below.
536           */
537          enlist(csp->headers, "");
538          continue_hack_in_da_house = 0;
539          continue;
540       }
541       else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
542       {
543          /*
544           * It's a bodyless continue response, don't
545           * stop header parsing after reaching its end.
546           *
547           * As a result Privoxy will concatenate the
548           * next response's head and parse and deliver
549           * the headers as if they belonged to one request.
550           *
551           * The client will separate them because of the
552           * empty line between them.
553           *
554           * XXX: What we're doing here is clearly against
555           * the intended purpose of the continue header,
556           * and under some conditions (HTTP/1.0 client request)
557           * it's a standard violation.
558           *
559           * Anyway, "sort of against the spec" is preferable
560           * to "always getting confused by Continue responses"
561           * (Privoxy's behaviour before this hack was added)
562           */
563          log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
564          continue_hack_in_da_house = 1;
565       }
566       else if (*header == '\0') 
567       {
568          /*
569           * If the header is empty, but the Continue hack
570           * isn't active, we can assume that we reached the
571           * end of the buffer before we hit the end of the
572           * head.
573           *
574           * Inform the caller an let it decide how to handle it.
575           */
576          return JB_ERR_PARSE;
577       }
578
579       if (JB_ERR_MEMORY == enlist(csp->headers, header))
580       {
581          /*
582           * XXX: Should we quit the request and return a
583           * out of memory error page instead?
584           */
585          log_error(LOG_LEVEL_ERROR,
586             "Out of memory while enlisting server headers. %s lost.",
587             header);
588       }
589       freez(header);
590    }
591
592    return JB_ERR_OK;
593 }
594
595
596 /*********************************************************************
597  *
598  * Function    :  crunch_reason
599  *
600  * Description :  Translates the crunch reason code into a string.
601  *
602  * Parameters  :
603  *          1  :  rsp = a http_response
604  *
605  * Returns     :  A string with the crunch reason or an error description.
606  *
607  *********************************************************************/
608 static const char *crunch_reason(const struct http_response *rsp)
609 {
610    char * reason = NULL;
611
612    assert(rsp != NULL);
613    if (rsp == NULL)
614    {
615       return "Internal error while searching for crunch reason";
616    }
617
618    switch (rsp->crunch_reason)
619    {
620       case UNSUPPORTED:
621          reason = "Unsupported HTTP feature";
622          break;
623       case BLOCKED:
624          reason = "Blocked";
625          break;
626       case UNTRUSTED:
627          reason = "Untrusted";
628          break;
629       case REDIRECTED:
630          reason = "Redirected";
631          break;
632       case CGI_CALL:
633          reason = "CGI Call";
634          break;
635       case NO_SUCH_DOMAIN:
636          reason = "DNS failure";
637          break;
638       case FORWARDING_FAILED:
639          reason = "Forwarding failed";
640          break;
641       case CONNECT_FAILED:
642          reason = "Connection failure";
643          break;
644       case OUT_OF_MEMORY:
645          reason = "Out of memory (may mask other reasons)";
646          break;
647       case CONNECTION_TIMEOUT:
648          reason = "Connection timeout";
649          break;
650       case NO_SERVER_DATA:
651          reason = "No server data received";
652          break;
653       default:
654          reason = "No reason recorded";
655          break;
656    }
657
658    return reason;
659 }
660
661
662 /*********************************************************************
663  *
664  * Function    :  send_crunch_response
665  *
666  * Description :  Delivers already prepared response for
667  *                intercepted requests, logs the interception
668  *                and frees the response.
669  *
670  * Parameters  :
671  *          1  :  csp = Current client state (buffers, headers, etc...)
672  *          1  :  rsp = Fully prepared response. Will be freed on exit.
673  *
674  * Returns     :  Nothing.
675  *
676  *********************************************************************/
677 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
678 {
679       const struct http_request *http = csp->http;
680       char status_code[4];
681
682       assert(rsp != NULL);
683       assert(rsp->head != NULL);
684
685       if (rsp == NULL)
686       {
687          log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
688       }
689
690       /*
691        * Extract the status code from the actual head
692        * that will be send to the client. It is the only
693        * way to get it right for all requests, including
694        * the fixed ones for out-of-memory problems.
695        *
696        * A head starts like this: 'HTTP/1.1 200...'
697        *                           0123456789|11
698        *                                     10
699        */
700       status_code[0] = rsp->head[9];
701       status_code[1] = rsp->head[10];
702       status_code[2] = rsp->head[11];
703       status_code[3] = '\0';
704
705       /* Log that the request was crunched and why. */
706       log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
707       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
708          csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
709
710       /* Write the answer to the client */
711       if (write_socket(csp->cfd, rsp->head, rsp->head_length)
712        || write_socket(csp->cfd, rsp->body, rsp->content_length))
713       {
714          /* There is nothing we can do about it. */
715          log_error(LOG_LEVEL_ERROR,
716             "Couldn't deliver the error message through client socket %d: %E",
717             csp->cfd);
718       }
719
720       /* Clean up and return */
721       if (cgi_error_memory() != rsp)
722       {
723          free_http_response(rsp);
724       } 
725       return;
726 }
727
728
729 /*********************************************************************
730  *
731  * Function    :  crunch_response_triggered
732  *
733  * Description :  Checks if the request has to be crunched,
734  *                and delivers the crunch response if necessary.
735  *
736  * Parameters  :
737  *          1  :  csp = Current client state (buffers, headers, etc...)
738  *          2  :  crunchers = list of cruncher functions to run
739  *
740  * Returns     :  TRUE if the request was answered with a crunch response
741  *                FALSE otherwise.
742  *
743  *********************************************************************/
744 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
745 {
746    struct http_response *rsp = NULL;
747    const struct cruncher *c;
748
749    /*
750     * If CGI request crunching is disabled,
751     * check the CGI dispatcher out of order to
752     * prevent unintentional blocks or redirects. 
753     */
754    if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
755        && (NULL != (rsp = dispatch_cgi(csp))))
756    {
757       /* Deliver, log and free the interception response. */
758       send_crunch_response(csp, rsp);
759       csp->flags |= CSP_FLAG_CRUNCHED;
760       return TRUE;
761    }
762
763    for (c = crunchers; c->cruncher != NULL; c++)
764    {
765       /*
766        * Check the cruncher if either Privoxy is toggled
767        * on and the request isn't forced, or if the cruncher
768        * applies to forced requests as well.
769        */
770       if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
771           !(csp->flags & CSP_FLAG_FORCED)) ||
772           (c->flags & CF_IGNORE_FORCE))
773       {
774          rsp = c->cruncher(csp);
775          if (NULL != rsp)
776          {
777             /* Deliver, log and free the interception response. */
778             send_crunch_response(csp, rsp);
779             csp->flags |= CSP_FLAG_CRUNCHED;
780 #ifdef FEATURE_STATISTICS
781             if (c->flags & CF_COUNT_AS_REJECT)
782             {
783                csp->flags |= CSP_FLAG_REJECTED;
784             }
785 #endif /* def FEATURE_STATISTICS */
786
787             return TRUE;
788          }
789       }
790    }
791
792    return FALSE;
793 }
794
795
796 /*********************************************************************
797  *
798  * Function    :  build_request_line
799  *
800  * Description :  Builds the HTTP request line.
801  *
802  *                If a HTTP forwarder is used it expects the whole URL,
803  *                web servers only get the path.
804  *
805  * Parameters  :
806  *          1  :  csp = Current client state (buffers, headers, etc...)
807  *          2  :  fwd = The forwarding spec used for the request
808  *                XXX: Should use http->fwd instead.
809  *          3  :  request_line = The old request line which will be replaced.
810  *
811  * Returns     :  Nothing. Terminates in case of memory problems.
812  *
813  *********************************************************************/
814 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
815 {
816    struct http_request *http = csp->http;
817
818    assert(http->ssl == 0);
819
820    /*
821     * Downgrade http version from 1.1 to 1.0
822     * if +downgrade action applies.
823     */
824    if ( (csp->action->flags & ACTION_DOWNGRADE)
825      && (!strcmpic(http->ver, "HTTP/1.1")))
826    {
827       freez(http->ver);
828       http->ver = strdup("HTTP/1.0");
829
830       if (http->ver == NULL)
831       {
832          log_error(LOG_LEVEL_FATAL, "Out of memory downgrading HTTP version");
833       }
834    }
835
836    /*
837     * Rebuild the request line.
838     */
839    freez(*request_line);
840    *request_line = strdup(http->gpc);
841    string_append(request_line, " ");
842
843    if (fwd->forward_host)
844    {
845       string_append(request_line, http->url);
846    }
847    else
848    {
849       string_append(request_line, http->path);
850    }
851    string_append(request_line, " ");
852    string_append(request_line, http->ver);
853
854    if (*request_line == NULL)
855    {
856       log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
857    }
858    log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
859 }
860
861
862 /*********************************************************************
863  *
864  * Function    :  change_request_destination
865  *
866  * Description :  Parse a (rewritten) request line and regenerate
867  *                the http request data.
868  *
869  * Parameters  :
870  *          1  :  csp = Current client state (buffers, headers, etc...)
871  *
872  * Returns     :  Forwards the parse_http_request() return code.
873  *                Terminates in case of memory problems.
874  *
875  *********************************************************************/
876 static jb_err change_request_destination(struct client_state *csp)
877 {
878    struct http_request *http = csp->http;
879    jb_err err;
880
881    log_error(LOG_LEVEL_INFO, "Rewrite detected: %s", csp->headers->first->str);
882    free_http_request(http);
883    err = parse_http_request(csp->headers->first->str, http);
884    if (JB_ERR_OK != err)
885    {
886       log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
887          jb_err_to_string(err));
888    }
889    else
890    {
891       /* XXX: ocmd is a misleading name */
892       http->ocmd = strdup(http->cmd);
893       if (http->ocmd == NULL)
894       {
895          log_error(LOG_LEVEL_FATAL,
896             "Out of memory copying rewritten HTTP request line");
897       }
898    }
899
900    return err;
901 }
902
903
904 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
905 /*********************************************************************
906  *
907  * Function    :  server_response_is_complete
908  *
909  * Description :  Determines whether we should stop reading
910  *                from the server socket.
911  *
912  * Parameters  :
913  *          1  :  csp = Current client state (buffers, headers, etc...)
914  *          2  :  content_length = Length of content received so far.
915  *
916  * Returns     :  TRUE if the response is complete,
917  *                FALSE otherwise.
918  *
919  *********************************************************************/
920 static int server_response_is_complete(struct client_state *csp,
921    unsigned long long content_length)
922 {
923    int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
924
925    if (!strcmpic(csp->http->gpc, "HEAD"))
926    {
927       /*
928        * "HEAD" implies no body, we are thus expecting
929        * no content. XXX: incomplete "list" of methods?
930        */
931       csp->expected_content_length = 0;
932       content_length_known = TRUE;
933    }
934
935    if (csp->http->status == 204 || csp->http->status == 304)
936    {
937       /*
938        * Expect no body. XXX: incomplete "list" of status codes?
939        */
940       csp->expected_content_length = 0;
941       content_length_known = TRUE;
942    }
943
944    return (content_length_known && ((0 == csp->expected_content_length)
945             || (csp->expected_content_length <= content_length)));
946 }
947
948
949 #ifdef FEATURE_CONNECTION_SHARING
950 /*********************************************************************
951  *
952  * Function    :  wait_for_alive_connections
953  *
954  * Description :  Waits for alive connections to timeout.
955  *
956  * Parameters  :  N/A
957  *
958  * Returns     :  N/A
959  *
960  *********************************************************************/
961 static void wait_for_alive_connections(void)
962 {
963    int connections_alive = close_unusable_connections();
964
965    while (0 < connections_alive)
966    {
967       log_error(LOG_LEVEL_CONNECT,
968          "Waiting for %d connections to timeout.",
969          connections_alive);
970       sleep(60);
971       connections_alive = close_unusable_connections();
972    }
973
974    log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
975
976 }
977 #endif /* def FEATURE_CONNECTION_SHARING */
978
979
980 /*********************************************************************
981  *
982  * Function    :  save_connection_destination
983  *
984  * Description :  Remembers a connection for reuse later on.
985  *
986  * Parameters  :
987  *          1  :  sfd  = Open socket to remember.
988  *          2  :  http = The destination for the connection.
989  *          3  :  fwd  = The forwarder settings used.
990  *          3  :  server_connection  = storage.
991  *
992  * Returns     : void
993  *
994  *********************************************************************/
995 void save_connection_destination(jb_socket sfd,
996                                  const struct http_request *http,
997                                  const struct forward_spec *fwd,
998                                  struct reusable_connection *server_connection)
999 {
1000    assert(sfd != JB_INVALID_SOCKET);
1001    assert(NULL != http->host);
1002
1003    server_connection->sfd = sfd;
1004    server_connection->host = strdup(http->host);
1005    if (NULL == server_connection->host)
1006    {
1007       log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
1008    }
1009    server_connection->port = http->port;
1010
1011    assert(NULL != fwd);
1012    assert(server_connection->gateway_host == NULL);
1013    assert(server_connection->gateway_port == 0);
1014    assert(server_connection->forwarder_type == 0);
1015    assert(server_connection->forward_host == NULL);
1016    assert(server_connection->forward_port == 0);
1017
1018    server_connection->forwarder_type = fwd->type;
1019    if (NULL != fwd->gateway_host)
1020    {
1021       server_connection->gateway_host = strdup(fwd->gateway_host);
1022       if (NULL == server_connection->gateway_host)
1023       {
1024          log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
1025       }
1026    }
1027    else
1028    {
1029       server_connection->gateway_host = NULL;
1030    }
1031    server_connection->gateway_port = fwd->gateway_port;
1032
1033    if (NULL != fwd->forward_host)
1034    {
1035       server_connection->forward_host = strdup(fwd->forward_host);
1036       if (NULL == server_connection->forward_host)
1037       {
1038          log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
1039       }
1040    }
1041    else
1042    {
1043       server_connection->forward_host = NULL;
1044    }
1045    server_connection->forward_port = fwd->forward_port;
1046 }
1047
1048
1049 /*********************************************************************
1050  *
1051  * Function    : verify_request_length
1052  *
1053  * Description : Checks if we already got the whole client requests
1054  *               and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1055  *               we do.
1056  *
1057  *               Data that doesn't belong to the current request is
1058  *               thrown away to let the client retry on a clean socket.
1059  *
1060  *               XXX: This is a hack until we can deal with multiple
1061  *                    pipelined requests at the same time.
1062  *
1063  *
1064  * Parameters  :
1065  *          1  :  csp = Current client state (buffers, headers, etc...)
1066  *
1067  * Returns     :  void
1068  *
1069  *********************************************************************/
1070 static void verify_request_length(struct client_state *csp)
1071 {
1072    unsigned long long buffered_request_bytes =
1073       (unsigned long long)(csp->iob->eod - csp->iob->cur);
1074
1075    if ((csp->expected_client_content_length != 0)
1076       && (buffered_request_bytes != 0))
1077    {
1078       if (csp->expected_client_content_length >= buffered_request_bytes)
1079       {
1080          csp->expected_client_content_length -= buffered_request_bytes;
1081          log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1082             "to account for the %llu ones we already got.",
1083             csp->expected_client_content_length, buffered_request_bytes);
1084       }
1085       else
1086       {
1087          assert(csp->iob->eod > csp->iob->cur + csp->expected_client_content_length);
1088          csp->iob->eod = csp->iob->cur + csp->expected_client_content_length;
1089          log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1090             "Marking the server socket tainted after throwing %llu bytes away.",
1091             buffered_request_bytes - csp->expected_client_content_length);
1092          csp->expected_client_content_length = 0;
1093          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1094       }
1095
1096       if (csp->expected_client_content_length == 0)
1097       {
1098          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1099       }
1100    }
1101
1102    if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1103     && ((csp->iob->cur[0] != '\0') || (csp->expected_client_content_length != 0)))
1104    {
1105       csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1106       if (strcmpic(csp->http->gpc, "GET")
1107          && strcmpic(csp->http->gpc, "HEAD")
1108          && strcmpic(csp->http->gpc, "TRACE")
1109          && strcmpic(csp->http->gpc, "OPTIONS")
1110          && strcmpic(csp->http->gpc, "DELETE"))
1111       {
1112          /* XXX: this is an incomplete hack */
1113          csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1114          log_error(LOG_LEVEL_CONNECT,
1115             "There might be a request body. The connection will not be kept alive.");
1116       }
1117       else
1118       {
1119          /* XXX: and so is this */
1120          csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1121          log_error(LOG_LEVEL_CONNECT,
1122             "Possible pipeline attempt detected. The connection will not "
1123             "be kept alive and we will only serve the first request.");
1124          /* Nuke the pipelined requests from orbit, just to be sure. */
1125          csp->iob->buf[0] = '\0';
1126          csp->iob->eod = csp->iob->cur = csp->iob->buf;
1127       }
1128    }
1129    else
1130    {
1131       csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1132       log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1133    }
1134 }
1135 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1136
1137
1138 /*********************************************************************
1139  *
1140  * Function    :  mark_server_socket_tainted
1141  *
1142  * Description :  Makes sure we don't reuse a server socket
1143  *                (if we didn't read everything the server sent
1144  *                us reusing the socket would lead to garbage).
1145  *
1146  * Parameters  :
1147  *          1  :  csp = Current client state (buffers, headers, etc...)
1148  *
1149  * Returns     :  void.
1150  *
1151  *********************************************************************/
1152 static void mark_server_socket_tainted(struct client_state *csp)
1153 {
1154    if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1155       && !(csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED))
1156    {
1157       log_error(LOG_LEVEL_CONNECT,
1158          "Marking the server socket %d tainted.",
1159          csp->server_connection.sfd);
1160       csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1161    }
1162 }
1163
1164 /*********************************************************************
1165  *
1166  * Function    :  get_request_line
1167  *
1168  * Description : Read the client request line.
1169  *
1170  * Parameters  :
1171  *          1  :  csp = Current client state (buffers, headers, etc...)
1172  *
1173  * Returns     :  Pointer to request line or NULL in case of errors.
1174  *
1175  *********************************************************************/
1176 static char *get_request_line(struct client_state *csp)
1177 {
1178    char buf[BUFFER_SIZE];
1179    char *request_line = NULL;
1180    int len;
1181
1182    memset(buf, 0, sizeof(buf));
1183
1184    do
1185    {
1186       if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1187       {
1188          log_error(LOG_LEVEL_CONNECT,
1189             "Stopped waiting for the request line. Timeout: %d.",
1190             csp->config->socket_timeout);
1191          write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1192             strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1193          return NULL;
1194       }
1195
1196       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1197
1198       if (len <= 0) return NULL;
1199
1200       /*
1201        * If there is no memory left for buffering the
1202        * request, there is nothing we can do but hang up
1203        */
1204       if (add_to_iob(csp, buf, len))
1205       {
1206          return NULL;
1207       }
1208
1209       request_line = get_header(csp->iob);
1210
1211    } while ((NULL != request_line) && ('\0' == *request_line));
1212
1213    return request_line;
1214
1215 }
1216
1217
1218 /*********************************************************************
1219  *
1220  * Function    :  receive_client_request
1221  *
1222  * Description : Read the client's request (more precisely the
1223  *               client headers) and answer it if necessary.
1224  *
1225  *               Note that since we're not using select() we could get
1226  *               blocked here if a client connected, then didn't say
1227  *               anything!
1228  *
1229  * Parameters  :
1230  *          1  :  csp = Current client state (buffers, headers, etc...)
1231  *
1232  * Returns     :  JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1233  *
1234  *********************************************************************/
1235 static jb_err receive_client_request(struct client_state *csp)
1236 {
1237    char buf[BUFFER_SIZE];
1238    char *p;
1239    char *req = NULL;
1240    struct http_request *http;
1241    int len;
1242    jb_err err;
1243
1244    /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1245    struct list header_list;
1246    struct list *headers = &header_list;
1247
1248    http = csp->http;
1249
1250    memset(buf, 0, sizeof(buf));
1251
1252    req = get_request_line(csp);
1253    if (req == NULL)
1254    {
1255       mark_server_socket_tainted(csp);
1256       return JB_ERR_PARSE;
1257    }
1258    assert(*req != '\0');
1259
1260    if (client_protocol_is_unsupported(csp, req))
1261    {
1262       return JB_ERR_PARSE;
1263    }
1264
1265 #ifdef FEATURE_FORCE_LOAD
1266    /*
1267     * If this request contains the FORCE_PREFIX and blocks
1268     * aren't enforced, get rid of it and set the force flag.
1269     */
1270    if (strstr(req, FORCE_PREFIX))
1271    {
1272       if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1273       {
1274          log_error(LOG_LEVEL_FORCE,
1275             "Ignored force prefix in request: \"%s\".", req);
1276       }
1277       else
1278       {
1279          strclean(req, FORCE_PREFIX);
1280          log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1281          csp->flags |= CSP_FLAG_FORCED;
1282       }
1283    }
1284 #endif /* def FEATURE_FORCE_LOAD */
1285
1286    err = parse_http_request(req, http);
1287    freez(req);
1288    if (JB_ERR_OK != err)
1289    {
1290       write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1291       /* XXX: Use correct size */
1292       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1293       log_error(LOG_LEVEL_ERROR,
1294          "Couldn't parse request line received from %s: %s",
1295          csp->ip_addr_str, jb_err_to_string(err));
1296
1297       free_http_request(http);
1298       return JB_ERR_PARSE;
1299    }
1300
1301    /* grab the rest of the client's headers */
1302    init_list(headers);
1303    for (;;)
1304    {
1305       p = get_header(csp->iob);
1306
1307       if (p == NULL)
1308       {
1309          /* There are no additional headers to read. */
1310          break;
1311       }
1312
1313       if (*p == '\0')
1314       {
1315          /*
1316           * We didn't receive a complete header
1317           * line yet, get the rest of it.
1318           */
1319          if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1320          {
1321             log_error(LOG_LEVEL_ERROR,
1322                "Stopped grabbing the client headers.");
1323             destroy_list(headers);
1324             return JB_ERR_PARSE;
1325          }
1326
1327          len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1328          if (len <= 0)
1329          {
1330             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1331             destroy_list(headers);
1332             return JB_ERR_PARSE;
1333          }
1334          
1335          if (add_to_iob(csp, buf, len))
1336          {
1337             /*
1338              * If there is no memory left for buffering the
1339              * request, there is nothing we can do but hang up
1340              */
1341             destroy_list(headers);
1342             return JB_ERR_MEMORY;
1343          }
1344       }
1345       else
1346       {
1347          /*
1348           * We were able to read a complete
1349           * header and can finaly enlist it.
1350           */
1351          enlist(headers, p);
1352          freez(p);
1353       }
1354    }
1355
1356    if (http->host == NULL)
1357    {
1358       /*
1359        * If we still don't know the request destination,
1360        * the request is invalid or the client uses
1361        * Privoxy without its knowledge.
1362        */
1363       if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1364       {
1365          /*
1366           * Our attempts to get the request destination
1367           * elsewhere failed or Privoxy is configured
1368           * to only accept proxy requests.
1369           *
1370           * An error response has already been send
1371           * and we're done here.
1372           */
1373          return JB_ERR_PARSE;
1374       }
1375    }
1376
1377    /*
1378     * Determine the actions for this URL
1379     */
1380 #ifdef FEATURE_TOGGLE
1381    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1382    {
1383       /* Most compatible set of actions (i.e. none) */
1384       init_current_action(csp->action);
1385    }
1386    else
1387 #endif /* ndef FEATURE_TOGGLE */
1388    {
1389       get_url_actions(csp, http);
1390    }
1391
1392    /* 
1393     * Save a copy of the original request for logging
1394     */
1395    http->ocmd = strdup(http->cmd);
1396    if (http->ocmd == NULL)
1397    {
1398       log_error(LOG_LEVEL_FATAL,
1399          "Out of memory copying HTTP request line");
1400    }
1401    enlist(csp->headers, http->cmd);
1402
1403    /* Append the previously read headers */
1404    list_append_list_unique(csp->headers, headers);
1405    destroy_list(headers);
1406
1407    return JB_ERR_OK;
1408
1409 }
1410
1411
1412 /*********************************************************************
1413  *
1414  * Function    : parse_client_request
1415  *
1416  * Description : Parses the client's request and decides what to do
1417  *               with it.
1418  *
1419  *               Note that since we're not using select() we could get
1420  *               blocked here if a client connected, then didn't say
1421  *               anything!
1422  *
1423  * Parameters  :
1424  *          1  :  csp = Current client state (buffers, headers, etc...)
1425  *
1426  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1427  *
1428  *********************************************************************/
1429 static jb_err parse_client_request(struct client_state *csp)
1430 {
1431    struct http_request *http = csp->http;
1432    jb_err err;
1433
1434 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1435    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1436     && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1437     && (csp->http->ssl == 0))
1438    {
1439       /* Assume persistence until further notice */
1440       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1441    }
1442 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1443
1444    err = sed(csp, FILTER_CLIENT_HEADERS);
1445    if (JB_ERR_OK != err)
1446    {
1447       /* XXX: Should be handled in sed(). */
1448       assert(err == JB_ERR_PARSE);
1449       log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1450    }
1451    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1452
1453    /* Check request line for rewrites. */
1454    if ((NULL == csp->headers->first->str)
1455       || (strcmp(http->cmd, csp->headers->first->str) &&
1456          (JB_ERR_OK != change_request_destination(csp))))
1457    {
1458       /*
1459        * A header filter broke the request line - bail out.
1460        */
1461       write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1462       /* XXX: Use correct size */
1463       log_error(LOG_LEVEL_CLF,
1464          "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1465       log_error(LOG_LEVEL_ERROR,
1466          "Invalid request line after applying header filters.");
1467       free_http_request(http);
1468
1469       return JB_ERR_PARSE;
1470    }
1471
1472 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1473    if (csp->http->ssl == 0)
1474    {
1475       verify_request_length(csp);
1476    }
1477 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1478
1479    return JB_ERR_OK;
1480
1481 }
1482
1483
1484 /*********************************************************************
1485  *
1486  * Function    :  chat
1487  *
1488  * Description :  Once a connection from the client has been accepted,
1489  *                this function is called (via serve()) to handle the
1490  *                main business of the communication.  This function
1491  *                returns after dealing with a single request. It can
1492  *                be called multiple times witht the same client socket
1493  *                if the client is keeping the connection alive.
1494  *
1495  *                The decision whether or not a client connection will
1496  *                be kept alive is up to the caller which also must
1497  *                close the client socket when done.
1498  *
1499  *                FIXME: chat is nearly thousand lines long.
1500  *                Ridiculous.
1501  *
1502  * Parameters  :
1503  *          1  :  csp = Current client state (buffers, headers, etc...)
1504  *
1505  * Returns     :  Nothing.
1506  *
1507  *********************************************************************/
1508 static void chat(struct client_state *csp)
1509 {
1510    char buf[BUFFER_SIZE];
1511    char *hdr;
1512    char *p;
1513    fd_set rfds;
1514    int n;
1515    jb_socket maxfd;
1516    int server_body;
1517    int ms_iis5_hack = 0;
1518    unsigned long long byte_count = 0;
1519    int forwarded_connect_retries = 0;
1520    int max_forwarded_connect_retries = csp->config->forwarded_connect_retries;
1521    const struct forward_spec *fwd;
1522    struct http_request *http;
1523    long len = 0; /* for buffer sizes (and negative error codes) */
1524
1525    /* Function that does the content filtering for the current request */
1526    filter_function_ptr content_filter = NULL;
1527
1528    /* Skeleton for HTTP response, if we should intercept the request */
1529    struct http_response *rsp;
1530    struct timeval timeout;
1531 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1532    int watch_client_socket = 1;
1533 #endif
1534
1535    memset(buf, 0, sizeof(buf));
1536
1537    http = csp->http;
1538
1539    if (receive_client_request(csp) != JB_ERR_OK)
1540    {
1541       return;
1542    }
1543    if (parse_client_request(csp) != JB_ERR_OK)
1544    {
1545       return;
1546    }
1547
1548    /* decide how to route the HTTP request */
1549    fwd = forward_url(csp, http);
1550    if (NULL == fwd)
1551    {
1552       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
1553       /* Never get here - LOG_LEVEL_FATAL causes program exit */
1554       return;
1555    }
1556
1557    /*
1558     * build the http request to send to the server
1559     * we have to do one of the following:
1560     *
1561     * create = use the original HTTP request to create a new
1562     *          HTTP request that has either the path component
1563     *          without the http://domainspec (w/path) or the
1564     *          full orininal URL (w/url)
1565     *          Note that the path and/or the HTTP version may
1566     *          have been altered by now.
1567     *
1568     * connect = Open a socket to the host:port of the server
1569     *           and short-circuit server and client socket.
1570     *
1571     * pass =  Pass the request unchanged if forwarding a CONNECT
1572     *         request to a parent proxy. Note that we'll be sending
1573     *         the CFAIL message ourselves if connecting to the parent
1574     *         fails, but we won't send a CSUCCEED message if it works,
1575     *         since that would result in a double message (ours and the
1576     *         parent's). After sending the request to the parent, we simply
1577     *         tunnel.
1578     *
1579     * here's the matrix:
1580     *                        SSL
1581     *                    0        1
1582     *                +--------+--------+
1583     *                |        |        |
1584     *             0  | create | connect|
1585     *                | w/path |        |
1586     *  Forwarding    +--------+--------+
1587     *                |        |        |
1588     *             1  | create | pass   |
1589     *                | w/url  |        |
1590     *                +--------+--------+
1591     *
1592     */
1593
1594    if (http->ssl && connect_port_is_forbidden(csp))
1595    {
1596       const char *acceptable_connect_ports =
1597          csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1598       assert(NULL != acceptable_connect_ports);
1599       log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1600          "limit-connect{%s} doesn't allow CONNECT requests to port %d.",
1601          csp->ip_addr_str, acceptable_connect_ports, csp->http->port);
1602       csp->action->flags |= ACTION_BLOCK;
1603       http->ssl = 0;
1604    }
1605
1606    if (http->ssl == 0)
1607    {
1608       freez(csp->headers->first->str);
1609       build_request_line(csp, fwd, &csp->headers->first->str);
1610    }
1611
1612    /*
1613     * We have a request. Check if one of the crunchers wants it.
1614     */
1615    if (crunch_response_triggered(csp, crunchers_all))
1616    {
1617       /*
1618        * Yes. The client got the crunch response and we're done here.
1619        */
1620       return;
1621    }
1622
1623    log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1624
1625    if (fwd->forward_host)
1626    {
1627       log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1628          fwd->forward_host, fwd->forward_port, http->hostport);
1629    }
1630    else
1631    {
1632       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1633    }
1634
1635    /* here we connect to the server, gateway, or the forwarder */
1636
1637 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1638    if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1639       && socket_is_still_alive(csp->server_connection.sfd)
1640       && connection_destination_matches(&csp->server_connection, http, fwd))
1641    {
1642       log_error(LOG_LEVEL_CONNECT,
1643          "Reusing server socket %u. Opened for %s.",
1644          csp->server_connection.sfd, csp->server_connection.host);
1645    }
1646    else
1647    {
1648       if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1649       {
1650          log_error(LOG_LEVEL_CONNECT,
1651             "Closing server socket %u. Opened for %s.",
1652             csp->server_connection.sfd, csp->server_connection.host);
1653          close_socket(csp->server_connection.sfd);
1654          mark_connection_closed(&csp->server_connection);
1655       }
1656 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1657
1658       while ((csp->server_connection.sfd = forwarded_connect(fwd, http, csp))
1659          && (errno == EINVAL)
1660          && (forwarded_connect_retries++ < max_forwarded_connect_retries))
1661       {
1662          log_error(LOG_LEVEL_ERROR,
1663             "failed request #%u to connect to %s. Trying again.",
1664             forwarded_connect_retries, http->hostport);
1665       }
1666
1667       if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1668       {
1669          if (fwd->type != SOCKS_NONE)
1670          {
1671             /* Socks error. */
1672             rsp = error_response(csp, "forwarding-failed");
1673          }
1674          else if (errno == EINVAL)
1675          {
1676             rsp = error_response(csp, "no-such-domain");
1677          }
1678          else
1679          {
1680             rsp = error_response(csp, "connect-failed");
1681             log_error(LOG_LEVEL_CONNECT, "connect to: %s failed: %E",
1682                http->hostport);
1683          }
1684
1685          /* Write the answer to the client */
1686          if (rsp != NULL)
1687          {
1688             send_crunch_response(csp, rsp);
1689          }
1690
1691          return;
1692       }
1693 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1694       save_connection_destination(csp->server_connection.sfd,
1695          http, fwd, &csp->server_connection);
1696       csp->server_connection.keep_alive_timeout =
1697          (unsigned)csp->config->keep_alive_timeout;
1698    }
1699 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1700
1701    hdr = list_to_text(csp->headers);
1702    if (hdr == NULL)
1703    {
1704       /* FIXME Should handle error properly */
1705       log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1706    }
1707    list_remove_all(csp->headers);
1708
1709    if (fwd->forward_host || (http->ssl == 0))
1710    {
1711       /*
1712        * Write the client's (modified) header to the server
1713        * (along with anything else that may be in the buffer)
1714        */
1715       if (write_socket(csp->server_connection.sfd, hdr, strlen(hdr))
1716        || (flush_socket(csp->server_connection.sfd, csp->iob) <  0))
1717       {
1718          log_error(LOG_LEVEL_CONNECT,
1719             "write header to: %s failed: %E", http->hostport);
1720
1721          rsp = error_response(csp, "connect-failed");
1722          if (rsp)
1723          {
1724             send_crunch_response(csp, rsp);
1725          }
1726
1727          freez(hdr);
1728          return;
1729       }
1730    }
1731    else
1732    {
1733       /*
1734        * We're running an SSL tunnel and we're not forwarding,
1735        * so just send the "connect succeeded" message to the
1736        * client, flush the rest, and get out of the way.
1737        */
1738       if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1739       {
1740          freez(hdr);
1741          return;
1742       }
1743       IOB_RESET(csp);
1744    }
1745
1746    log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1747
1748    csp->server_connection.request_sent = time(NULL);
1749
1750    /* we're finished with the client's header */
1751    freez(hdr);
1752
1753    maxfd = (csp->cfd > csp->server_connection.sfd) ?
1754       csp->cfd : csp->server_connection.sfd;
1755
1756    /* pass data between the client and server
1757     * until one or the other shuts down the connection.
1758     */
1759
1760    server_body = 0;
1761
1762    for (;;)
1763    {
1764 #ifdef __OS2__
1765       /*
1766        * FD_ZERO here seems to point to an errant macro which crashes.
1767        * So do this by hand for now...
1768        */
1769       memset(&rfds,0x00,sizeof(fd_set));
1770 #else
1771       FD_ZERO(&rfds);
1772 #endif
1773 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1774       if (!watch_client_socket)
1775       {
1776          maxfd = csp->server_connection.sfd;
1777       }
1778       else
1779 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1780       {
1781          FD_SET(csp->cfd, &rfds);
1782       }
1783
1784       FD_SET(csp->server_connection.sfd, &rfds);
1785
1786 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1787       if ((csp->flags & CSP_FLAG_CHUNKED)
1788          && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
1789          && ((csp->iob->eod - csp->iob->cur) >= 5)
1790          && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
1791       {
1792          log_error(LOG_LEVEL_CONNECT,
1793             "Looks like we read the last chunk together with "
1794             "the server headers. We better stop reading.");
1795          byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
1796          csp->expected_content_length = byte_count;
1797          csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1798       }
1799       if (server_body && server_response_is_complete(csp, byte_count))
1800       {
1801          if (csp->expected_content_length == byte_count)
1802          {
1803             log_error(LOG_LEVEL_CONNECT,
1804                "Done reading from server. Content length: %llu as expected. "
1805                "Bytes most recently read: %d.",
1806                byte_count, len);
1807          }
1808          else
1809          {
1810             log_error(LOG_LEVEL_CONNECT,
1811                "Done reading from server. Expected content length: %llu. "
1812                "Actual content length: %llu. Bytes most recently read: %d.",
1813                csp->expected_content_length, byte_count, len);
1814          }
1815          len = 0;
1816          /*
1817           * XXX: should not jump around,
1818           * chat() is complicated enough already.
1819           */
1820          goto reading_done;
1821       }
1822 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
1823
1824       timeout.tv_sec = csp->config->socket_timeout;
1825       timeout.tv_usec = 0;
1826       n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
1827
1828       if (n == 0)
1829       {
1830          log_error(LOG_LEVEL_ERROR,
1831             "Didn't receive data in time: %s", http->url);
1832          if ((byte_count == 0) && (http->ssl == 0))
1833          {
1834             send_crunch_response(csp, error_response(csp, "connection-timeout"));
1835          }
1836          mark_server_socket_tainted(csp);
1837          return;
1838       }
1839       else if (n < 0)
1840       {
1841          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1842          mark_server_socket_tainted(csp);
1843          return;
1844       }
1845
1846       /*
1847        * This is the body of the browser's request,
1848        * just read and write it.
1849        *
1850        * XXX: Make sure the client doesn't use pipelining
1851        * behind Privoxy's back.
1852        */
1853       if (FD_ISSET(csp->cfd, &rfds))
1854       {
1855          int max_bytes_to_read = sizeof(buf) - 1;
1856
1857 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1858          if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1859          {
1860             if (data_is_available(csp->cfd, 0))
1861             {
1862                /*
1863                 * If the next request is already waiting, we have
1864                 * to stop select()ing the client socket. Otherwise
1865                 * we would always return right away and get nothing
1866                 * else done.
1867                 */
1868                watch_client_socket = 0;
1869                log_error(LOG_LEVEL_CONNECT,
1870                   "Stopping to watch the client socket. "
1871                   "There's already another request waiting.");
1872                continue;
1873             }
1874             /*
1875              * If the client socket is set, but there's no data
1876              * available on the socket, the client went fishing
1877              * and continuing talking to the server makes no sense.
1878              */
1879             log_error(LOG_LEVEL_CONNECT,
1880                "The client closed socket %d while "
1881                "the server socket %d is still open.",
1882                csp->cfd, csp->server_connection.sfd);
1883             mark_server_socket_tainted(csp);
1884             break;
1885          }
1886          if (csp->expected_client_content_length != 0)
1887          {
1888             if (csp->expected_client_content_length < (sizeof(buf) - 1))
1889             {
1890                max_bytes_to_read = (int)csp->expected_client_content_length;
1891             }
1892             log_error(LOG_LEVEL_CONNECT,
1893                "Waiting for up to %d bytes from the client.",
1894                max_bytes_to_read);
1895          }
1896          assert(max_bytes_to_read < sizeof(buf));
1897 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1898
1899          len = read_socket(csp->cfd, buf, max_bytes_to_read);
1900
1901          if (len <= 0)
1902          {
1903             /* XXX: not sure if this is necessary. */
1904             mark_server_socket_tainted(csp);
1905             break; /* "game over, man" */
1906          }
1907
1908 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1909          if (csp->expected_client_content_length != 0)
1910          {
1911             assert(len <= max_bytes_to_read);
1912             csp->expected_client_content_length -= (unsigned)len;
1913             log_error(LOG_LEVEL_CONNECT,
1914                "Expected client content length set to %llu "
1915                "after reading %d bytes.",
1916                csp->expected_client_content_length, len);
1917             if (csp->expected_client_content_length == 0)
1918             {
1919                log_error(LOG_LEVEL_CONNECT,
1920                   "Done reading from the client.");
1921                csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1922             }
1923          }
1924 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1925
1926          if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
1927          {
1928             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1929             mark_server_socket_tainted(csp);
1930             return;
1931          }
1932          continue;
1933       }
1934
1935       /*
1936        * The server wants to talk. It could be the header or the body.
1937        * If `hdr' is null, then it's the header otherwise it's the body.
1938        * FIXME: Does `hdr' really mean `host'? No.
1939        */
1940       if (FD_ISSET(csp->server_connection.sfd, &rfds))
1941       {
1942 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1943          if (!socket_is_still_alive(csp->cfd))
1944          {
1945 #ifdef _WIN32
1946             log_error(LOG_LEVEL_CONNECT,
1947                "The server still wants to talk, but the client may already have hung up on us.");
1948 #else
1949             log_error(LOG_LEVEL_CONNECT,
1950                "The server still wants to talk, but the client hung up on us.");
1951             mark_server_socket_tainted(csp);
1952             return;
1953 #endif /* def _WIN32 */
1954          }
1955 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1956
1957          fflush(NULL);
1958          len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
1959
1960          if (len < 0)
1961          {
1962             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1963
1964             if (http->ssl && (fwd->forward_host == NULL))
1965             {
1966                /*
1967                 * Just hang up. We already confirmed the client's CONNECT
1968                 * request with status code 200 and unencrypted content is
1969                 * no longer welcome.
1970                 */
1971                log_error(LOG_LEVEL_ERROR,
1972                   "CONNECT already confirmed. Unable to tell the client about the problem.");
1973                return;
1974             }
1975             else if (byte_count)
1976             {
1977                /*
1978                 * Just hang up. We already transmitted the original headers
1979                 * and parts of the original content and therefore missed the
1980                 * chance to send an error message (without risking data corruption).
1981                 *
1982                 * XXX: we could retry with a fancy range request here.
1983                 */
1984                log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
1985                   "Unable to tell the client about the problem.");
1986                mark_server_socket_tainted(csp);
1987                return;
1988             }
1989             /*
1990              * XXX: Consider handling the cases above the same.
1991              */
1992             mark_server_socket_tainted(csp);
1993             len = 0;
1994          }
1995
1996 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1997          if (csp->flags & CSP_FLAG_CHUNKED)
1998          {
1999             if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2000             {
2001                /* XXX: this is a temporary hack */
2002                log_error(LOG_LEVEL_CONNECT,
2003                   "Looks like we reached the end of the last chunk. "
2004                   "We better stop reading.");
2005                csp->expected_content_length = byte_count + (unsigned long long)len;
2006                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2007             }
2008          }
2009          reading_done:
2010 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
2011
2012          /*
2013           * Add a trailing zero to let be able to use string operations.
2014           * XXX: do we still need this with filter_popups gone?
2015           */
2016          buf[len] = '\0';
2017
2018          /*
2019           * Normally, this would indicate that we've read
2020           * as much as the server has sent us and we can
2021           * close the client connection.  However, Microsoft
2022           * in its wisdom has released IIS/5 with a bug that
2023           * prevents it from sending the trailing \r\n in
2024           * a 302 redirect header (and possibly other headers).
2025           * To work around this if we've haven't parsed
2026           * a full header we'll append a trailing \r\n
2027           * and see if this now generates a valid one.
2028           *
2029           * This hack shouldn't have any impacts.  If we've
2030           * already transmitted the header or if this is a
2031           * SSL connection, then we won't bother with this
2032           * hack.  So we only work on partially received
2033           * headers.  If we append a \r\n and this still
2034           * doesn't generate a valid header, then we won't
2035           * transmit anything to the client.
2036           */
2037          if (len == 0)
2038          {
2039
2040             if (server_body || http->ssl)
2041             {
2042                /*
2043                 * If we have been buffering up the document,
2044                 * now is the time to apply content modification
2045                 * and send the result to the client.
2046                 */
2047                if (content_filter)
2048                {
2049                   p = execute_content_filter(csp, content_filter);
2050                   /*
2051                    * If the content filter fails, use the original
2052                    * buffer and length.
2053                    * (see p != NULL ? p : csp->iob->cur below)
2054                    */
2055                   if (NULL == p)
2056                   {
2057                      csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2058                   }
2059
2060                   if (JB_ERR_OK != update_server_headers(csp))
2061                   {
2062                      log_error(LOG_LEVEL_FATAL,
2063                         "Failed to update server headers. after filtering.");
2064                   }
2065
2066                   hdr = list_to_text(csp->headers);
2067                   if (hdr == NULL)
2068                   {
2069                      /* FIXME Should handle error properly */
2070                      log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2071                   }
2072
2073                   if (write_socket(csp->cfd, hdr, strlen(hdr))
2074                    || write_socket(csp->cfd,
2075                          ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2076                   {
2077                      log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2078                      freez(hdr);
2079                      freez(p);
2080                      mark_server_socket_tainted(csp);
2081                      return;
2082                   }
2083
2084                   freez(hdr);
2085                   freez(p);
2086                }
2087
2088                break; /* "game over, man" */
2089             }
2090
2091             /*
2092              * This is NOT the body, so
2093              * Let's pretend the server just sent us a blank line.
2094              */
2095             snprintf(buf, sizeof(buf), "\r\n");
2096             len = (int)strlen(buf);
2097
2098             /*
2099              * Now, let the normal header parsing algorithm below do its
2100              * job.  If it fails, we'll exit instead of continuing.
2101              */
2102
2103             ms_iis5_hack = 1;
2104          }
2105
2106          /*
2107           * If this is an SSL connection or we're in the body
2108           * of the server document, just write it to the client,
2109           * unless we need to buffer the body for later content-filtering
2110           */
2111          if (server_body || http->ssl)
2112          {
2113             if (content_filter)
2114             {
2115                /*
2116                 * If there is no memory left for buffering the content, or the buffer limit
2117                 * has been reached, switch to non-filtering mode, i.e. make & write the
2118                 * header, flush the iob and buf, and get out of the way.
2119                 */
2120                if (add_to_iob(csp, buf, len))
2121                {
2122                   size_t hdrlen;
2123                   long flushed;
2124
2125                   log_error(LOG_LEVEL_INFO,
2126                      "Flushing header and buffers. Stepping back from filtering.");
2127
2128                   hdr = list_to_text(csp->headers);
2129                   if (hdr == NULL)
2130                   {
2131                      /* 
2132                       * Memory is too tight to even generate the header.
2133                       * Send our static "Out-of-memory" page.
2134                       */
2135                      log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2136                      rsp = cgi_error_memory();
2137                      send_crunch_response(csp, rsp);
2138                      mark_server_socket_tainted(csp);
2139                      return;
2140                   }
2141                   hdrlen = strlen(hdr);
2142
2143                   if (write_socket(csp->cfd, hdr, hdrlen)
2144                    || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2145                    || (write_socket(csp->cfd, buf, (size_t)len)))
2146                   {
2147                      log_error(LOG_LEVEL_CONNECT,
2148                         "Flush header and buffers to client failed: %E");
2149                      freez(hdr);
2150                      mark_server_socket_tainted(csp);
2151                      return;
2152                   }
2153
2154                   /*
2155                    * Reset the byte_count to the amount of bytes
2156                    * we just flushed. len will be added a few lines below,
2157                    * hdrlen doesn't matter for LOG_LEVEL_CLF.
2158                    */
2159                   byte_count = (unsigned long long)flushed;
2160                   freez(hdr);
2161                   content_filter = NULL;
2162                   server_body = 1;
2163                }
2164             }
2165             else
2166             {
2167                if (write_socket(csp->cfd, buf, (size_t)len))
2168                {
2169                   log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2170                   mark_server_socket_tainted(csp);
2171                   return;
2172                }
2173             }
2174             byte_count += (unsigned long long)len;
2175             continue;
2176          }
2177          else
2178          {
2179             /*
2180              * We're still looking for the end of the server's header.
2181              * Buffer up the data we just read.  If that fails, there's
2182              * little we can do but send our static out-of-memory page.
2183              */
2184             if (add_to_iob(csp, buf, len))
2185             {
2186                log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2187                rsp = cgi_error_memory();
2188                send_crunch_response(csp, rsp);               
2189                mark_server_socket_tainted(csp);
2190                return;
2191             }
2192
2193             /* Convert iob into something sed() can digest */
2194             if (JB_ERR_PARSE == get_server_headers(csp))
2195             {
2196                if (ms_iis5_hack)
2197                {
2198                   /*
2199                    * Well, we tried our MS IIS/5 hack and it didn't work.
2200                    * The header is incomplete and there isn't anything
2201                    * we can do about it.
2202                    */
2203                   log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2204                      "Applying the MS IIS5 hack didn't help.");
2205                   log_error(LOG_LEVEL_CLF,
2206                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2207                   write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2208                      strlen(INVALID_SERVER_HEADERS_RESPONSE));
2209                   mark_server_socket_tainted(csp);
2210                   return;
2211                }
2212                else
2213                {
2214                   /*
2215                    * Since we have to wait for more from the server before
2216                    * we can parse the headers we just continue here.
2217                    */
2218                   log_error(LOG_LEVEL_CONNECT,
2219                      "Continuing buffering headers. Bytes most recently read: %d.",
2220                      len);
2221                   continue;
2222                }
2223             }
2224             else
2225             {
2226                /*
2227                 * Account for the content bytes we
2228                 * might have gotten with the headers.
2229                 */
2230                assert(csp->iob->eod >= csp->iob->cur);
2231                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2232             }
2233
2234             /* Did we actually get anything? */
2235             if (NULL == csp->headers->first)
2236             {
2237                if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2238                {
2239                   log_error(LOG_LEVEL_ERROR,
2240                      "Empty server or forwarder response received on socket %d. "
2241                      "Closing client socket %d without sending data.",
2242                      csp->server_connection.sfd, csp->cfd);
2243                }
2244                else
2245                {
2246                   log_error(LOG_LEVEL_ERROR,
2247                      "Empty server or forwarder response received on socket %d.",
2248                      csp->server_connection.sfd);
2249                   send_crunch_response(csp, error_response(csp, "no-server-data"));
2250                }
2251                log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2252                free_http_request(http);
2253                mark_server_socket_tainted(csp);
2254                return;
2255             }
2256
2257             assert(csp->headers->first->str);
2258             assert(!http->ssl);
2259             if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2260                 strncmpic(csp->headers->first->str, "ICY", 3))
2261             {
2262                /*
2263                 * It doesn't look like a HTTP (or Shoutcast) response:
2264                 * tell the client and log the problem.
2265                 */
2266                if (strlen(csp->headers->first->str) > 30)
2267                {
2268                   csp->headers->first->str[30] = '\0';
2269                }
2270                log_error(LOG_LEVEL_ERROR,
2271                   "Invalid server or forwarder response. Starts with: %s",
2272                   csp->headers->first->str);
2273                log_error(LOG_LEVEL_CLF,
2274                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2275                write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2276                   strlen(INVALID_SERVER_HEADERS_RESPONSE));
2277                free_http_request(http);
2278                mark_server_socket_tainted(csp);
2279                return;
2280             }
2281
2282             /*
2283              * We have now received the entire server header,
2284              * filter it and send the result to the client
2285              */
2286             if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2287             {
2288                log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2289             }
2290             hdr = list_to_text(csp->headers);
2291             if (hdr == NULL)
2292             {
2293                /* FIXME Should handle error properly */
2294                log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2295             }
2296
2297             csp->server_connection.response_received = time(NULL);
2298
2299             if (crunch_response_triggered(csp, crunchers_light))
2300             {
2301                /*
2302                 * One of the tags created by a server-header
2303                 * tagger triggered a crunch. We already
2304                 * delivered the crunch response to the client
2305                 * and are done here after cleaning up.
2306                 */
2307                 freez(hdr);
2308                 mark_server_socket_tainted(csp);
2309                 return;
2310             }
2311             /* Buffer and pcrs filter this if appropriate. */
2312
2313             if (!http->ssl) /* We talk plaintext */
2314             {
2315                content_filter = get_filter_function(csp);
2316             }
2317             /*
2318              * Only write if we're not buffering for content modification
2319              */
2320             if (!content_filter)
2321             {
2322                /*
2323                 * Write the server's (modified) header to
2324                 * the client (along with anything else that
2325                 * may be in the buffer)
2326                 */
2327
2328                if (write_socket(csp->cfd, hdr, strlen(hdr))
2329                 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2330                {
2331                   log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2332
2333                   /*
2334                    * The write failed, so don't bother mentioning it
2335                    * to the client... it probably can't hear us anyway.
2336                    */
2337                   freez(hdr);
2338                   mark_server_socket_tainted(csp);
2339                   return;
2340                }
2341             }
2342
2343             /* we're finished with the server's header */
2344
2345             freez(hdr);
2346             server_body = 1;
2347
2348             /*
2349              * If this was a MS IIS/5 hack then it means the server
2350              * has already closed the connection. Nothing more to read.
2351              * Time to bail.
2352              */
2353             if (ms_iis5_hack)
2354             {
2355                log_error(LOG_LEVEL_ERROR,
2356                   "Closed server connection detected. "
2357                   "Applying the MS IIS5 hack didn't help.");
2358                log_error(LOG_LEVEL_CLF,
2359                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2360                write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2361                   strlen(INVALID_SERVER_HEADERS_RESPONSE));
2362                mark_server_socket_tainted(csp);
2363                return;
2364             }
2365          }
2366          continue;
2367       }
2368       mark_server_socket_tainted(csp);
2369       return; /* huh? we should never get here */
2370    }
2371
2372    if (csp->content_length == 0)
2373    {
2374       /*
2375        * If Privoxy didn't recalculate the Content-Lenght,
2376        * byte_count is still correct.
2377        */
2378       csp->content_length = byte_count;
2379    }
2380
2381 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2382    if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2383       && (csp->expected_content_length != byte_count))
2384    {
2385       log_error(LOG_LEVEL_CONNECT,
2386          "Received %llu bytes while expecting %llu.",
2387          byte_count, csp->expected_content_length);
2388       mark_server_socket_tainted(csp);
2389    }
2390 #endif
2391
2392    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2393       csp->ip_addr_str, http->ocmd, csp->content_length);
2394
2395    csp->server_connection.timestamp = time(NULL);
2396 }
2397
2398
2399 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2400 /*********************************************************************
2401  *
2402  * Function    :  prepare_csp_for_next_request
2403  *
2404  * Description :  Put the csp in a mostly vergin state.
2405  *
2406  * Parameters  :
2407  *          1  :  csp = Current client state (buffers, headers, etc...)
2408  *
2409  * Returns     :  N/A
2410  *
2411  *********************************************************************/
2412 static void prepare_csp_for_next_request(struct client_state *csp)
2413 {
2414    csp->content_type = 0;
2415    csp->content_length = 0;
2416    csp->expected_content_length = 0;
2417    csp->expected_client_content_length = 0;
2418    list_remove_all(csp->headers);
2419    freez(csp->iob->buf);
2420    memset(csp->iob, 0, sizeof(csp->iob));
2421    freez(csp->error_message);
2422    free_http_request(csp->http);
2423    destroy_list(csp->headers);
2424    destroy_list(csp->tags);
2425    free_current_action(csp->action);
2426    if (NULL != csp->fwd)
2427    {
2428       unload_forward_spec(csp->fwd);
2429       csp->fwd = NULL;
2430    }
2431    /* XXX: Store per-connection flags someplace else. */
2432    csp->flags &= CSP_FLAG_TOGGLED_ON;
2433    csp->flags |= CSP_FLAG_ACTIVE;
2434    csp->flags |= CSP_FLAG_REUSED_CLIENT_CONNECTION;
2435 }
2436 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2437
2438
2439 /*********************************************************************
2440  *
2441  * Function    :  serve
2442  *
2443  * Description :  This is little more than chat.  We only "serve" to
2444  *                to close (or remember) any socket that chat may have
2445  *                opened.
2446  *
2447  * Parameters  :
2448  *          1  :  csp = Current client state (buffers, headers, etc...)
2449  *
2450  * Returns     :  N/A
2451  *
2452  *********************************************************************/
2453 #ifdef AMIGA
2454 void serve(struct client_state *csp)
2455 #else /* ifndef AMIGA */
2456 static void serve(struct client_state *csp)
2457 #endif /* def AMIGA */
2458 {
2459 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2460 #ifdef FEATURE_CONNECTION_SHARING
2461    static int monitor_thread_running = 0;
2462 #endif /* def FEATURE_CONNECTION_SHARING */
2463    int continue_chatting = 0;
2464
2465    do
2466    {
2467       unsigned int latency;
2468
2469       chat(csp);
2470
2471       /*
2472        * If the request has been crunched,
2473        * the calculated latency is zero.
2474        */
2475       latency = (unsigned)(csp->server_connection.response_received -
2476          csp->server_connection.request_sent) / 2;
2477
2478       continue_chatting = (csp->config->feature_flags
2479          & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2480          && (((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2481                && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
2482             || (csp->flags & CSP_FLAG_CRUNCHED))
2483          && (csp->cfd != JB_INVALID_SOCKET);
2484
2485       if (continue_chatting && !(csp->flags & CSP_FLAG_CRUNCHED))
2486       {
2487          continue_chatting = (csp->server_connection.sfd != JB_INVALID_SOCKET)
2488             && socket_is_still_alive(csp->server_connection.sfd);
2489          if (continue_chatting)
2490          {
2491             if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2492             {
2493                csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2494                log_error(LOG_LEVEL_CONNECT,
2495                   "The server didn't specify how long the connection will stay open. "
2496                   "Assumed timeout is: %u.", csp->server_connection.keep_alive_timeout);
2497             }
2498             continue_chatting = (latency < csp->server_connection.keep_alive_timeout);
2499          }
2500       }
2501
2502       if (continue_chatting)
2503       {
2504          unsigned int client_timeout;
2505
2506          if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2507          {
2508             client_timeout = (unsigned)csp->server_connection.keep_alive_timeout - latency;
2509             log_error(LOG_LEVEL_CONNECT,
2510                "Waiting for the next client request on socket %d. "
2511                "Keeping the server socket %d to %s open.",
2512                csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2513          }
2514          else
2515          {
2516             client_timeout = 1; /* XXX: Use something else here? */
2517             log_error(LOG_LEVEL_CONNECT,
2518                "Waiting for the next client request on socket %d. "
2519                "No server socket to keep open.", csp->cfd);
2520          }
2521          if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2522             && data_is_available(csp->cfd, (int)client_timeout)
2523             && socket_is_still_alive(csp->cfd))
2524          {
2525             log_error(LOG_LEVEL_CONNECT, "Client request arrived in "
2526                "time or the client closed the connection on socket %d.",
2527                 csp->cfd);
2528             prepare_csp_for_next_request(csp);
2529          }
2530          else
2531          {
2532             log_error(LOG_LEVEL_CONNECT,
2533                "No additional client request received in time on socket %d.",
2534                 csp->cfd);
2535 #ifdef FEATURE_CONNECTION_SHARING
2536             if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2537                && (socket_is_still_alive(csp->server_connection.sfd)))
2538             {
2539                time_t time_open = time(NULL) - csp->server_connection.timestamp;
2540
2541                if (csp->server_connection.keep_alive_timeout < time_open + latency)
2542                {
2543                   break;
2544                }
2545
2546                remember_connection(&csp->server_connection);
2547                csp->server_connection.sfd = JB_INVALID_SOCKET;
2548                close_socket(csp->cfd);
2549                csp->cfd = JB_INVALID_SOCKET;
2550                privoxy_mutex_lock(&connection_reuse_mutex);
2551                if (!monitor_thread_running)
2552                {
2553                   monitor_thread_running = 1;
2554                   privoxy_mutex_unlock(&connection_reuse_mutex);
2555                   wait_for_alive_connections();
2556                   privoxy_mutex_lock(&connection_reuse_mutex);
2557                   monitor_thread_running = 0;
2558                }
2559                privoxy_mutex_unlock(&connection_reuse_mutex);
2560             }
2561 #endif /* def FEATURE_CONNECTION_SHARING */
2562             break;
2563          }
2564       }
2565       else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2566       {
2567          log_error(LOG_LEVEL_CONNECT,
2568             "The connection on server socket %d to %s isn't reusable. "
2569             "Closing.", csp->server_connection.sfd, csp->server_connection.host);
2570       }
2571    } while (continue_chatting);
2572
2573 #else
2574    chat(csp);
2575 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2576
2577    if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2578    {
2579 #ifdef FEATURE_CONNECTION_SHARING
2580       if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2581       {
2582          forget_connection(csp->server_connection.sfd);
2583       }
2584 #endif /* def FEATURE_CONNECTION_SHARING */
2585       close_socket(csp->server_connection.sfd);
2586    }
2587
2588 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2589    mark_connection_closed(&csp->server_connection);
2590 #endif
2591
2592    if (csp->cfd != JB_INVALID_SOCKET)
2593    {
2594       close_socket(csp->cfd);
2595    }
2596
2597    csp->flags &= ~CSP_FLAG_ACTIVE;
2598
2599 }
2600
2601
2602 #ifdef __BEOS__
2603 /*********************************************************************
2604  *
2605  * Function    :  server_thread
2606  *
2607  * Description :  We only exist to call `serve' in a threaded environment.
2608  *
2609  * Parameters  :
2610  *          1  :  data = Current client state (buffers, headers, etc...)
2611  *
2612  * Returns     :  Always 0.
2613  *
2614  *********************************************************************/
2615 static int32 server_thread(void *data)
2616 {
2617    serve((struct client_state *) data);
2618    return 0;
2619
2620 }
2621 #endif
2622
2623
2624 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2625 /*********************************************************************
2626  *
2627  * Function    :  usage
2628  *
2629  * Description :  Print usage info & exit.
2630  *
2631  * Parameters  :  Pointer to argv[0] for identifying ourselves
2632  *
2633  * Returns     :  No. ,-)
2634  *
2635  *********************************************************************/
2636 static void usage(const char *myname)
2637 {
2638    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2639           "Usage: %s "
2640 #if defined(unix)
2641           "[--chroot] "
2642 #endif /* defined(unix) */
2643           "[--help] "
2644 #if defined(unix)
2645           "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
2646 #endif /* defined(unix) */
2647           "[--version] [configfile]\n"
2648           "Aborting\n", myname);
2649
2650    exit(2);
2651
2652 }
2653 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
2654
2655
2656 #ifdef MUTEX_LOCKS_AVAILABLE
2657 /*********************************************************************
2658  *
2659  * Function    :  privoxy_mutex_lock
2660  *
2661  * Description :  Locks a mutex.
2662  *
2663  * Parameters  :
2664  *          1  :  mutex = The mutex to lock.
2665  *
2666  * Returns     :  Void. May exit in case of errors.
2667  *
2668  *********************************************************************/
2669 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
2670 {
2671 #ifdef FEATURE_PTHREAD
2672    int err = pthread_mutex_lock(mutex);
2673    if (err)
2674    {
2675       if (mutex != &log_mutex)
2676       {
2677          log_error(LOG_LEVEL_FATAL,
2678             "Mutex locking failed: %s.\n", strerror(err));
2679       }
2680       exit(1);
2681    }
2682 #else
2683    EnterCriticalSection(mutex);
2684 #endif /* def FEATURE_PTHREAD */
2685 }
2686
2687
2688 /*********************************************************************
2689  *
2690  * Function    :  privoxy_mutex_unlock
2691  *
2692  * Description :  Unlocks a mutex.
2693  *
2694  * Parameters  :
2695  *          1  :  mutex = The mutex to unlock.
2696  *
2697  * Returns     :  Void. May exit in case of errors.
2698  *
2699  *********************************************************************/
2700 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
2701 {
2702 #ifdef FEATURE_PTHREAD
2703    int err = pthread_mutex_unlock(mutex);
2704    if (err)
2705    {
2706       if (mutex != &log_mutex)
2707       {
2708          log_error(LOG_LEVEL_FATAL,
2709             "Mutex unlocking failed: %s.\n", strerror(err));
2710       }
2711       exit(1);
2712    }
2713 #else
2714    LeaveCriticalSection(mutex);
2715 #endif /* def FEATURE_PTHREAD */
2716 }
2717
2718
2719 /*********************************************************************
2720  *
2721  * Function    :  privoxy_mutex_init
2722  *
2723  * Description :  Prepares a mutex.
2724  *
2725  * Parameters  :
2726  *          1  :  mutex = The mutex to initialize.
2727  *
2728  * Returns     :  Void. May exit in case of errors.
2729  *
2730  *********************************************************************/
2731 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
2732 {
2733 #ifdef FEATURE_PTHREAD
2734    int err = pthread_mutex_init(mutex, 0);
2735    if (err)
2736    {
2737       printf("Fatal error. Mutex initialization failed: %s.\n",
2738          strerror(err));
2739       exit(1);
2740    }
2741 #else
2742    InitializeCriticalSection(mutex);
2743 #endif /* def FEATURE_PTHREAD */
2744 }
2745 #endif /* def MUTEX_LOCKS_AVAILABLE */
2746
2747 /*********************************************************************
2748  *
2749  * Function    :  initialize_mutexes
2750  *
2751  * Description :  Prepares mutexes if mutex support is available.
2752  *
2753  * Parameters  :  None
2754  *
2755  * Returns     :  Void, exits in case of errors.
2756  *
2757  *********************************************************************/
2758 static void initialize_mutexes(void)
2759 {
2760 #ifdef MUTEX_LOCKS_AVAILABLE
2761    /*
2762     * Prepare global mutex semaphores
2763     */
2764    privoxy_mutex_init(&log_mutex);
2765    privoxy_mutex_init(&log_init_mutex);
2766    privoxy_mutex_init(&connection_reuse_mutex);
2767
2768    /*
2769     * XXX: The assumptions below are a bit naive
2770     * and can cause locks that aren't necessary.
2771     *
2772     * For example older FreeBSD versions (< 6.x?)
2773     * have no gethostbyname_r, but gethostbyname is
2774     * thread safe.
2775     */
2776 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
2777    privoxy_mutex_init(&resolver_mutex);
2778 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
2779    /*
2780     * XXX: should we use a single mutex for
2781     * localtime() and gmtime() as well?
2782     */
2783 #ifndef HAVE_GMTIME_R
2784    privoxy_mutex_init(&gmtime_mutex);
2785 #endif /* ndef HAVE_GMTIME_R */
2786
2787 #ifndef HAVE_LOCALTIME_R
2788    privoxy_mutex_init(&localtime_mutex);
2789 #endif /* ndef HAVE_GMTIME_R */
2790
2791 #ifndef HAVE_RANDOM
2792    privoxy_mutex_init(&rand_mutex);
2793 #endif /* ndef HAVE_RANDOM */
2794 #endif /* def MUTEX_LOCKS_AVAILABLE */
2795 }
2796
2797
2798 /*********************************************************************
2799  *
2800  * Function    :  main
2801  *
2802  * Description :  Load the config file and start the listen loop.
2803  *                This function is a lot more *sane* with the `load_config'
2804  *                and `listen_loop' functions; although it stills does
2805  *                a *little* too much for my taste.
2806  *
2807  * Parameters  :
2808  *          1  :  argc = Number of parameters (including $0).
2809  *          2  :  argv = Array of (char *)'s to the parameters.
2810  *
2811  * Returns     :  1 if : can't open config file, unrecognized directive,
2812  *                stats requested in multi-thread mode, can't open the
2813  *                log file, can't open the jar file, listen port is invalid,
2814  *                any load fails, and can't bind port.
2815  *
2816  *                Else main never returns, the process must be signaled
2817  *                to terminate execution.  Or, on Windows, use the
2818  *                "File", "Exit" menu option.
2819  *
2820  *********************************************************************/
2821 #ifdef __MINGW32__
2822 int real_main(int argc, char **argv)
2823 #else
2824 int main(int argc, char **argv)
2825 #endif
2826 {
2827    int argc_pos = 0;
2828    unsigned int random_seed;
2829 #ifdef unix
2830    struct passwd *pw = NULL;
2831    struct group *grp = NULL;
2832    char *p;
2833    int do_chroot = 0;
2834    char *pre_chroot_nslookup_to_load_resolver = NULL;
2835 #endif
2836
2837    Argc = argc;
2838    Argv = argv;
2839
2840    configfile =
2841 #if !defined(_WIN32)
2842    "config"
2843 #else
2844    "config.txt"
2845 #endif
2846       ;
2847
2848    /* Prepare mutexes if supported and necessary. */
2849    initialize_mutexes();
2850
2851    /* Enable logging until further notice. */
2852    init_log_module();
2853
2854    /*
2855     * Parse the command line arguments
2856     *
2857     * XXX: simply printing usage information in case of
2858     * invalid arguments isn't particularly user friendly.
2859     */
2860    while (++argc_pos < argc)
2861    {
2862 #ifdef _WIN32
2863       /* Check to see if the service must be installed or uninstalled */
2864       if (strncmp(argv[argc_pos], "--install", 9) == 0)
2865       {
2866          const char *pName = argv[argc_pos] + 9;
2867          if (*pName == ':')
2868             pName++;
2869          exit( (install_service(pName)) ? 0 : 1 );
2870       }
2871       else if (strncmp(argv[argc_pos], "--uninstall", + 11) == 0)
2872       {
2873          const char *pName = argv[argc_pos] + 11;
2874          if (*pName == ':')
2875             pName++;
2876          exit((uninstall_service(pName)) ? 0 : 1);
2877       }
2878       else if (strcmp(argv[argc_pos], "--service" ) == 0)
2879       {
2880          bRunAsService = TRUE;
2881          w32_set_service_cwd();
2882          atexit(w32_service_exit_notify);
2883       }
2884       else
2885 #endif /* defined(_WIN32) */
2886
2887
2888 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2889
2890       if (strcmp(argv[argc_pos], "--help") == 0)
2891       {
2892          usage(argv[0]);
2893       }
2894
2895       else if(strcmp(argv[argc_pos], "--version") == 0)
2896       {
2897          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2898          exit(0);
2899       }
2900
2901 #if defined(unix)
2902
2903       else if (strcmp(argv[argc_pos], "--no-daemon" ) == 0)
2904       {
2905          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
2906          daemon_mode = 0;
2907       }
2908
2909       else if (strcmp(argv[argc_pos], "--pidfile" ) == 0)
2910       {
2911          if (++argc_pos == argc) usage(argv[0]);
2912          pidfile = strdup(argv[argc_pos]);
2913       }
2914
2915       else if (strcmp(argv[argc_pos], "--user" ) == 0)
2916       {
2917          if (++argc_pos == argc) usage(argv[argc_pos]);
2918
2919          if ((NULL != (p = strchr(argv[argc_pos], '.'))) && *(p + 1) != '0')
2920          {
2921             *p++ = '\0';
2922             if (NULL == (grp = getgrnam(p)))
2923             {
2924                log_error(LOG_LEVEL_FATAL, "Group %s not found.", p);
2925             }
2926          }
2927
2928          if (NULL == (pw = getpwnam(argv[argc_pos])))
2929          {
2930             log_error(LOG_LEVEL_FATAL, "User %s not found.", argv[argc_pos]);
2931          }
2932
2933          if (p != NULL) *--p = '\0';
2934       }
2935
2936       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup" ) == 0)
2937       {
2938          if (++argc_pos == argc) usage(argv[0]);
2939          pre_chroot_nslookup_to_load_resolver = strdup(argv[argc_pos]);
2940       }
2941
2942       else if (strcmp(argv[argc_pos], "--chroot" ) == 0)
2943       {
2944          do_chroot = 1;
2945       }
2946 #endif /* defined(unix) */
2947
2948       else if (argc_pos + 1 != argc)
2949       {
2950          /*
2951           * This is neither the last command line
2952           * option, nor was it recognized before,
2953           * therefore it must be invalid.
2954           */
2955          usage(argv[0]);
2956       }
2957       else
2958
2959 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
2960       {
2961          configfile = argv[argc_pos];
2962       }
2963
2964    } /* -END- while (more arguments) */
2965
2966    show_version(Argv[0]);
2967
2968 #if defined(unix)
2969    if ( *configfile != '/' )
2970    {
2971       char cwd[BUFFER_SIZE];
2972       char *abs_file;
2973       size_t abs_file_size; 
2974
2975       /* make config-filename absolute here */
2976       if (NULL == getcwd(cwd, sizeof(cwd)))
2977       {
2978          perror("failed to get current working directory");
2979          exit( 1 );
2980       }
2981
2982       /* XXX: why + 5? */
2983       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
2984       basedir = strdup(cwd);
2985
2986       if (NULL == basedir ||
2987           NULL == (abs_file = malloc(abs_file_size)))
2988       {
2989          perror("malloc failed");
2990          exit( 1 );
2991       }
2992       strlcpy(abs_file, basedir, abs_file_size);
2993       strlcat(abs_file, "/", abs_file_size );
2994       strlcat(abs_file, configfile, abs_file_size);
2995       configfile = abs_file;
2996    }
2997 #endif /* defined unix */
2998
2999
3000    files->next = NULL;
3001    clients->next = NULL;
3002
3003    /* XXX: factor out initialising after the next stable release. */
3004 #ifdef AMIGA
3005    InitAmiga();
3006 #elif defined(_WIN32)
3007    InitWin32();
3008 #endif
3009
3010    random_seed = (unsigned int)time(NULL);
3011 #ifdef HAVE_RANDOM
3012    srandom(random_seed);
3013 #else
3014    srand(random_seed);
3015 #endif /* ifdef HAVE_RANDOM */
3016
3017    /*
3018     * Unix signal handling
3019     *
3020     * Catch the abort, interrupt and terminate signals for a graceful exit
3021     * Catch the hangup signal so the errlog can be reopened.
3022     * Ignore the broken pipe signals (FIXME: Why?)
3023     */
3024 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3025 {
3026    int idx;
3027    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP, 0 };
3028    const int ignored_signals[] = { SIGPIPE, 0 };
3029
3030    for (idx = 0; catched_signals[idx] != 0; idx++)
3031    {
3032 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */ 
3033       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3034 #else
3035       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3036 #endif /* ifdef sun */
3037       {
3038          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3039       }
3040    }
3041
3042    for (idx = 0; ignored_signals[idx] != 0; idx++)
3043    {
3044       if (signal(ignored_signals[idx], SIG_IGN) == SIG_ERR)
3045       {
3046          log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for signal %d: %E", ignored_signals[idx]);
3047       }
3048    }
3049
3050 }
3051 #else /* ifdef _WIN32 */
3052 # ifdef _WIN_CONSOLE
3053    /*
3054     * We *are* in a windows console app.
3055     * Print a verbose messages about FAQ's and such
3056     */
3057    printf("%s", win32_blurb);
3058 # endif /* def _WIN_CONSOLE */
3059 #endif /* def _WIN32 */
3060
3061
3062    /* Initialize the CGI subsystem */
3063    cgi_init_error_messages();
3064
3065    /*
3066     * If runnig on unix and without the --nodaemon
3067     * option, become a daemon. I.e. fork, detach
3068     * from tty and get process group leadership
3069     */
3070 #if defined(unix)
3071 {
3072    if (daemon_mode)
3073    {
3074       int fd;
3075       pid_t pid = fork();
3076
3077       if ( pid < 0 ) /* error */
3078       {
3079          perror("fork");
3080          exit( 3 );
3081       }
3082       else if ( pid != 0 ) /* parent */
3083       {
3084          int status;
3085          pid_t wpid;
3086          /*
3087           * must check for errors
3088           * child died due to missing files aso
3089           */
3090          sleep( 1 );
3091          wpid = waitpid( pid, &status, WNOHANG );
3092          if ( wpid != 0 )
3093          {
3094             exit( 1 );
3095          }
3096          exit( 0 );
3097       }
3098       /* child */
3099
3100       setsid();
3101
3102       /*
3103        * stderr (fd 2) will be closed later on,
3104        * when the config file has been parsed.
3105        */
3106       close(0);
3107       close(1);
3108
3109       /*
3110        * Reserve fd 0 and 1 to prevent abort() and friends
3111        * from sending stuff to the clients or servers.
3112        */
3113       fd = open("/dev/null", O_RDONLY);
3114       if (fd == -1)
3115       {
3116          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3117       }
3118       else if (fd != 0)
3119       {
3120          if (dup2(fd, 0) == -1)
3121          {
3122             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3123          }
3124          close(fd);
3125       }
3126       fd = open("/dev/null", O_WRONLY);
3127       if (fd == -1)
3128       {
3129          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3130       }
3131       else if (fd != 1)
3132       {
3133          if (dup2(fd, 1) == -1)
3134          {
3135             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3136          }
3137          close(fd);
3138       }
3139
3140       chdir("/");
3141
3142    } /* -END- if (daemon_mode) */
3143
3144    /*
3145     * As soon as we have written the PID file, we can switch
3146     * to the user and group ID indicated by the --user option
3147     */
3148    write_pid_file();
3149
3150    if (NULL != pw)
3151    {
3152       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3153       {
3154          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3155       }
3156       if (NULL != grp)
3157       {
3158          if (setgroups(1, &grp->gr_gid))
3159          {
3160             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3161          }
3162       }
3163       else if (initgroups(pw->pw_name, pw->pw_gid))
3164       {
3165          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3166       }
3167       if (do_chroot)
3168       {
3169          if (!pw->pw_dir)
3170          {
3171             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3172          }
3173          /* Read the time zone file from /etc before doing chroot. */
3174          tzset();
3175          if (NULL != pre_chroot_nslookup_to_load_resolver
3176              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3177          {
3178             /* Initialize resolver library. */
3179             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3180          }
3181          if (chroot(pw->pw_dir) < 0)
3182          {
3183             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3184          }
3185          if (chdir ("/"))
3186          {
3187             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3188          }
3189       }
3190       if (setuid(pw->pw_uid))
3191       {
3192          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3193       }
3194       if (do_chroot)
3195       {
3196          char putenv_dummy[64];
3197
3198          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3199          if (putenv(putenv_dummy) != 0)
3200          {
3201             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3202          }                
3203
3204          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3205          if (putenv(putenv_dummy) != 0)
3206          {
3207             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3208          }
3209       }
3210    }
3211    else if (do_chroot)
3212    {
3213       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3214    }
3215 }
3216 #endif /* defined unix */
3217
3218 #ifdef _WIN32
3219    /* This will be FALSE unless the command line specified --service
3220     */
3221    if (bRunAsService)
3222    {
3223       /* Yup, so now we must attempt to establish a connection 
3224        * with the service dispatcher. This will only work if this
3225        * process was launched by the service control manager to
3226        * actually run as a service. If this isn't the case, i've
3227        * known it take around 30 seconds or so for the call to return.
3228        */
3229
3230       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3231       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3232       {
3233          /* Service has run, and at this point is now being stopped, so just return */
3234          return 0;
3235       }
3236
3237 #ifdef _WIN_CONSOLE
3238       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3239 #endif
3240       /* An error occurred. Usually it's because --service was wrongly specified
3241        * and we were unable to connect to the Service Control Dispatcher because
3242        * it wasn't expecting us and is therefore not listening.
3243        *
3244        * For now, just continue below to call the listen_loop function.
3245        */
3246    }
3247 #endif /* def _WIN32 */
3248
3249    listen_loop();
3250
3251    /* NOTREACHED */
3252    return(-1);
3253
3254 }
3255
3256
3257 /*********************************************************************
3258  *
3259  * Function    :  bind_port_helper
3260  *
3261  * Description :  Bind the listen port.  Handles logging, and aborts
3262  *                on failure.
3263  *
3264  * Parameters  :
3265  *          1  :  config = Privoxy configuration.  Specifies port
3266  *                         to bind to.
3267  *
3268  * Returns     :  Port that was opened.
3269  *
3270  *********************************************************************/
3271 static jb_socket bind_port_helper(struct configuration_spec * config)
3272 {
3273    int result;
3274    jb_socket bfd;
3275
3276    if (config->haddr == NULL)
3277    {
3278       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3279                 config->hport);
3280    }
3281    else
3282    {
3283       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3284                 config->hport, config->haddr);
3285    }
3286
3287    result = bind_port(config->haddr, config->hport, &bfd);
3288
3289    if (result < 0)
3290    {
3291       switch(result)
3292       {
3293          case -3 :
3294             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: "
3295                "There may be another Privoxy or some other "
3296                "proxy running on port %d",
3297                (NULL != config->haddr) ? config->haddr : "INADDR_ANY",
3298                       config->hport, config->hport);
3299
3300          case -2 :
3301             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: " 
3302                "The hostname is not resolvable",
3303                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3304
3305          default :
3306             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3307                (NULL != config->haddr) ? config->haddr : "INADDR_ANY", config->hport);
3308       }
3309
3310       /* shouldn't get here */
3311       return JB_INVALID_SOCKET;
3312    }
3313
3314    config->need_bind = 0;
3315
3316    return bfd;
3317 }
3318
3319
3320 #ifdef _WIN32
3321 /* Without this simple workaround we get this compiler warning from _beginthread
3322  *     warning C4028: formal parameter 1 different from declaration
3323  */
3324 void w32_service_listen_loop(void *p)
3325 {
3326    listen_loop();
3327 }
3328 #endif /* def _WIN32 */
3329
3330
3331 /*********************************************************************
3332  *
3333  * Function    :  listen_loop
3334  *
3335  * Description :  bind the listen port and enter a "FOREVER" listening loop.
3336  *
3337  * Parameters  :  N/A
3338  *
3339  * Returns     :  Never.
3340  *
3341  *********************************************************************/
3342 static void listen_loop(void)
3343 {
3344    struct client_state *csp = NULL;
3345    jb_socket bfd;
3346    struct configuration_spec *config;
3347    unsigned int active_threads = 0;
3348
3349    config = load_config();
3350
3351 #ifdef FEATURE_CONNECTION_SHARING
3352    /*
3353     * XXX: Should be relocated once it no
3354     * longer needs to emit log messages.
3355     */
3356    initialize_reusable_connections();
3357 #endif /* def FEATURE_CONNECTION_SHARING */
3358
3359    bfd = bind_port_helper(config);
3360
3361 #ifdef FEATURE_GRACEFUL_TERMINATION
3362    while (!g_terminate)
3363 #else
3364    for (;;)
3365 #endif
3366    {
3367 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3368       while (waitpid(-1, NULL, WNOHANG) > 0)
3369       {
3370          /* zombie children */
3371       }
3372 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3373
3374       /*
3375        * Free data that was used by died threads
3376        */
3377       active_threads = sweep();
3378
3379 #if defined(unix)
3380       /*
3381        * Re-open the errlog after HUP signal
3382        */
3383       if (received_hup_signal)
3384       {
3385          if (NULL != config->logfile)
3386          {
3387             init_error_log(Argv[0], config->logfile);
3388          }
3389          received_hup_signal = 0;
3390       }
3391 #endif
3392
3393       if ( NULL == (csp = (struct client_state *) zalloc(sizeof(*csp))) )
3394       {
3395          log_error(LOG_LEVEL_FATAL, "malloc(%d) for csp failed: %E", sizeof(*csp));
3396          continue;
3397       }
3398
3399       csp->flags |= CSP_FLAG_ACTIVE;
3400       csp->server_connection.sfd = JB_INVALID_SOCKET;
3401
3402       csp->config = config = load_config();
3403
3404       if ( config->need_bind )
3405       {
3406          /*
3407           * Since we were listening to the "old port", we will not see
3408           * a "listen" param change until the next request.  So, at
3409           * least 1 more request must be made for us to find the new
3410           * setting.  I am simply closing the old socket and binding the
3411           * new one.
3412           *
3413           * Which-ever is correct, we will serve 1 more page via the
3414           * old settings.  This should probably be a "show-proxy-args"
3415           * request.  This should not be a so common of an operation
3416           * that this will hurt people's feelings.
3417           */
3418
3419          close_socket(bfd);
3420
3421          bfd = bind_port_helper(config);
3422       }
3423
3424       log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3425
3426       if (!accept_connection(csp, bfd))
3427       {
3428          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3429
3430 #ifdef AMIGA
3431          if(!childs)
3432          {
3433             exit(1);
3434          }
3435 #endif
3436          freez(csp);
3437          continue;
3438       }
3439       else
3440       {
3441          log_error(LOG_LEVEL_CONNECT, "accepted connection from %s", csp->ip_addr_str);
3442       }
3443
3444 #ifdef FEATURE_TOGGLE
3445       if (global_toggle_state)
3446 #endif /* def FEATURE_TOGGLE */
3447       {
3448          csp->flags |= CSP_FLAG_TOGGLED_ON;
3449       }
3450
3451       if (run_loader(csp))
3452       {
3453          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3454          /* Never get here - LOG_LEVEL_FATAL causes program exit */
3455       }
3456
3457 #ifdef FEATURE_ACL
3458       if (block_acl(NULL,csp))
3459       {
3460          log_error(LOG_LEVEL_CONNECT, "Connection from %s dropped due to ACL", csp->ip_addr_str);
3461          close_socket(csp->cfd);
3462          freez(csp->ip_addr_str);
3463          freez(csp);
3464          continue;
3465       }
3466 #endif /* def FEATURE_ACL */
3467
3468       if ((0 != config->max_client_connections)
3469          && (active_threads >= config->max_client_connections))
3470       {
3471          log_error(LOG_LEVEL_CONNECT,
3472             "Rejecting connection from %s. Maximum number of connections reached.",
3473             csp->ip_addr_str);
3474          write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3475             strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3476          close_socket(csp->cfd);
3477          freez(csp->ip_addr_str);
3478          freez(csp);
3479          continue;
3480       }
3481
3482       /* add it to the list of clients */
3483       csp->next = clients->next;
3484       clients->next = csp;
3485
3486       if (config->multi_threaded)
3487       {
3488          int child_id;
3489
3490 /* this is a switch () statment in the C preprocessor - ugh */
3491 #undef SELECTED_ONE_OPTION
3492
3493 /* Use Pthreads in preference to native code */
3494 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3495 #define SELECTED_ONE_OPTION
3496          {
3497             pthread_t the_thread;
3498             pthread_attr_t attrs;
3499
3500             pthread_attr_init(&attrs);
3501             pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3502             errno = pthread_create(&the_thread, &attrs,
3503                (void * (*)(void *))serve, csp);
3504             child_id = errno ? -1 : 0;
3505             pthread_attr_destroy(&attrs);
3506          }
3507 #endif
3508
3509 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3510 #define SELECTED_ONE_OPTION
3511          child_id = _beginthread(
3512             (void (*)(void *))serve,
3513             64 * 1024,
3514             csp);
3515 #endif
3516
3517 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3518 #define SELECTED_ONE_OPTION
3519          child_id = _beginthread(
3520             (void(* _Optlink)(void*))serve,
3521             NULL,
3522             64 * 1024,
3523             csp);
3524 #endif
3525
3526 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3527 #define SELECTED_ONE_OPTION
3528          {
3529             thread_id tid = spawn_thread
3530                (server_thread, "server", B_NORMAL_PRIORITY, csp);
3531
3532             if ((tid >= 0) && (resume_thread(tid) == B_OK))
3533             {
3534                child_id = (int) tid;
3535             }
3536             else
3537             {
3538                child_id = -1;
3539             }
3540          }
3541 #endif
3542
3543 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3544 #define SELECTED_ONE_OPTION
3545          csp->cfd = ReleaseSocket(csp->cfd, -1);
3546          
3547 #ifdef __amigaos4__
3548          child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3549                                            NP_Output, Output(),
3550                                            NP_CloseOutput, FALSE,
3551                                            NP_Name, (ULONG)"privoxy child",
3552                                            NP_Child, TRUE,
3553                                            TAG_DONE);
3554 #else
3555          child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3556                                            NP_Output, Output(),
3557                                            NP_CloseOutput, FALSE,
3558                                            NP_Name, (ULONG)"privoxy child",
3559                                            NP_StackSize, 200*1024,
3560                                            TAG_DONE);
3561 #endif
3562          if(0 != child_id)
3563          {
3564             childs++;
3565             ((struct Task *)child_id)->tc_UserData = csp;
3566             Signal((struct Task *)child_id, SIGF_SINGLE);
3567             Wait(SIGF_SINGLE);
3568          }
3569 #endif
3570
3571 #if !defined(SELECTED_ONE_OPTION)
3572          child_id = fork();
3573
3574          /* This block is only needed when using fork().
3575           * When using threads, the server thread was
3576           * created and run by the call to _beginthread().
3577           */
3578          if (child_id == 0)   /* child */
3579          {
3580             int rc = 0;
3581 #ifdef FEATURE_TOGGLE
3582             int inherited_toggle_state = global_toggle_state;
3583 #endif /* def FEATURE_TOGGLE */
3584
3585             serve(csp);
3586
3587             /* 
3588              * If we've been toggled or we've blocked the request, tell Mom
3589              */
3590
3591 #ifdef FEATURE_TOGGLE
3592             if (inherited_toggle_state != global_toggle_state)
3593             {
3594                rc |= RC_FLAG_TOGGLED;
3595             }
3596 #endif /* def FEATURE_TOGGLE */
3597
3598 #ifdef FEATURE_STATISTICS  
3599             if (csp->flags & CSP_FLAG_REJECTED)
3600             {
3601                rc |= RC_FLAG_BLOCKED;
3602             }
3603 #endif /* ndef FEATURE_STATISTICS */
3604
3605             _exit(rc);
3606          }
3607          else if (child_id > 0) /* parent */
3608          {
3609             /* in a fork()'d environment, the parent's
3610              * copy of the client socket and the CSP
3611              * are not used.
3612              */
3613             int child_status;
3614 #if !defined(_WIN32) && !defined(__CYGWIN__)
3615
3616             wait( &child_status );
3617
3618             /* 
3619              * Evaluate child's return code: If the child has
3620              *  - been toggled, toggle ourselves
3621              *  - blocked its request, bump up the stats counter
3622              */
3623
3624 #ifdef FEATURE_TOGGLE
3625             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3626             {
3627                global_toggle_state = !global_toggle_state;
3628             }
3629 #endif /* def FEATURE_TOGGLE */
3630
3631 #ifdef FEATURE_STATISTICS
3632             urls_read++;
3633             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3634             {
3635                urls_rejected++;
3636             }
3637 #endif /* def FEATURE_STATISTICS */ 
3638
3639 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3640             close_socket(csp->cfd);
3641             csp->flags &= ~CSP_FLAG_ACTIVE;
3642          }
3643 #endif
3644
3645 #undef SELECTED_ONE_OPTION
3646 /* end of cpp switch () */
3647
3648          if (child_id < 0)
3649          {
3650             /*
3651              * Spawning the child failed, assume it's because
3652              * there are too many children running already.
3653              * XXX: If you assume ...
3654              */
3655             log_error(LOG_LEVEL_ERROR,
3656                "Unable to take any additional connections: %E");
3657             write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3658                strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3659             close_socket(csp->cfd);
3660             csp->flags &= ~CSP_FLAG_ACTIVE;
3661          }
3662       }
3663       else
3664       {
3665          serve(csp);
3666       }
3667    }
3668
3669    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3670
3671    /* Clean up.  Aim: free all memory (no leaks) */
3672 #ifdef FEATURE_GRACEFUL_TERMINATION
3673
3674    log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3675
3676    unload_current_config_file();
3677    unload_current_actions_file();
3678    unload_current_re_filterfile();
3679 #ifdef FEATURE_TRUST
3680    unload_current_trust_file();
3681 #endif
3682
3683    if (config->multi_threaded)
3684    {
3685       int i = 60;
3686       do
3687       {
3688          sleep(1);
3689          sweep();
3690       } while ((clients->next != NULL) && (--i > 0));
3691
3692       if (i <= 0)
3693       {
3694          log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3695       }
3696    }
3697    sweep();
3698    sweep();
3699
3700 #if defined(unix)
3701    freez(basedir);
3702 #endif
3703    freez(configfile);
3704
3705 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3706    /* Cleanup - remove taskbar icon etc. */
3707    TermLogWindow();
3708 #endif
3709
3710    exit(0);
3711 #endif /* FEATURE_GRACEFUL_TERMINATION */
3712
3713 }
3714
3715
3716 /*
3717   Local Variables:
3718   tab-width: 3
3719   end:
3720 */