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