When stopping to watch a client socket due to pipelining, additionally log the socket...
[privoxy.git] / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 1.377 2012/03/09 16:24:36 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          log_error(LOG_LEVEL_CONNECT,
1197             "Stopped waiting for the request line. Timeout: %d.",
1198             csp->config->socket_timeout);
1199          write_socket(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1200             strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE));
1201          return NULL;
1202       }
1203
1204       len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1205
1206       if (len <= 0) return NULL;
1207
1208       /*
1209        * If there is no memory left for buffering the
1210        * request, there is nothing we can do but hang up
1211        */
1212       if (add_to_iob(csp, buf, len))
1213       {
1214          return NULL;
1215       }
1216
1217       request_line = get_header(csp->iob);
1218
1219    } while ((NULL != request_line) && ('\0' == *request_line));
1220
1221    return request_line;
1222
1223 }
1224
1225
1226 /*********************************************************************
1227  *
1228  * Function    :  receive_client_request
1229  *
1230  * Description : Read the client's request (more precisely the
1231  *               client headers) and answer it if necessary.
1232  *
1233  * Parameters  :
1234  *          1  :  csp = Current client state (buffers, headers, etc...)
1235  *
1236  * Returns     :  JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1237  *
1238  *********************************************************************/
1239 static jb_err receive_client_request(struct client_state *csp)
1240 {
1241    char buf[BUFFER_SIZE];
1242    char *p;
1243    char *req = NULL;
1244    struct http_request *http;
1245    int len;
1246    jb_err err;
1247
1248    /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1249    struct list header_list;
1250    struct list *headers = &header_list;
1251
1252    http = csp->http;
1253
1254    memset(buf, 0, sizeof(buf));
1255
1256    req = get_request_line(csp);
1257    if (req == NULL)
1258    {
1259       mark_server_socket_tainted(csp);
1260       return JB_ERR_PARSE;
1261    }
1262    assert(*req != '\0');
1263
1264    if (client_protocol_is_unsupported(csp, req))
1265    {
1266       return JB_ERR_PARSE;
1267    }
1268
1269 #ifdef FEATURE_FORCE_LOAD
1270    /*
1271     * If this request contains the FORCE_PREFIX and blocks
1272     * aren't enforced, get rid of it and set the force flag.
1273     */
1274    if (strstr(req, FORCE_PREFIX))
1275    {
1276       if (csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS)
1277       {
1278          log_error(LOG_LEVEL_FORCE,
1279             "Ignored force prefix in request: \"%s\".", req);
1280       }
1281       else
1282       {
1283          strclean(req, FORCE_PREFIX);
1284          log_error(LOG_LEVEL_FORCE, "Enforcing request: \"%s\".", req);
1285          csp->flags |= CSP_FLAG_FORCED;
1286       }
1287    }
1288 #endif /* def FEATURE_FORCE_LOAD */
1289
1290    err = parse_http_request(req, http);
1291    freez(req);
1292    if (JB_ERR_OK != err)
1293    {
1294       write_socket(csp->cfd, CHEADER, strlen(CHEADER));
1295       /* XXX: Use correct size */
1296       log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1297       log_error(LOG_LEVEL_ERROR,
1298          "Couldn't parse request line received from %s: %s",
1299          csp->ip_addr_str, jb_err_to_string(err));
1300
1301       free_http_request(http);
1302       return JB_ERR_PARSE;
1303    }
1304
1305    /* grab the rest of the client's headers */
1306    init_list(headers);
1307    for (;;)
1308    {
1309       p = get_header(csp->iob);
1310
1311       if (p == NULL)
1312       {
1313          /* There are no additional headers to read. */
1314          break;
1315       }
1316
1317       if (*p == '\0')
1318       {
1319          /*
1320           * We didn't receive a complete header
1321           * line yet, get the rest of it.
1322           */
1323          if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1324          {
1325             log_error(LOG_LEVEL_ERROR,
1326                "Stopped grabbing the client headers.");
1327             destroy_list(headers);
1328             return JB_ERR_PARSE;
1329          }
1330
1331          len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1332          if (len <= 0)
1333          {
1334             log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1335             destroy_list(headers);
1336             return JB_ERR_PARSE;
1337          }
1338
1339          if (add_to_iob(csp, buf, len))
1340          {
1341             /*
1342              * If there is no memory left for buffering the
1343              * request, there is nothing we can do but hang up
1344              */
1345             destroy_list(headers);
1346             return JB_ERR_MEMORY;
1347          }
1348       }
1349       else
1350       {
1351          /*
1352           * We were able to read a complete
1353           * header and can finally enlist it.
1354           */
1355          enlist(headers, p);
1356          freez(p);
1357       }
1358    }
1359
1360    if (http->host == NULL)
1361    {
1362       /*
1363        * If we still don't know the request destination,
1364        * the request is invalid or the client uses
1365        * Privoxy without its knowledge.
1366        */
1367       if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1368       {
1369          /*
1370           * Our attempts to get the request destination
1371           * elsewhere failed or Privoxy is configured
1372           * to only accept proxy requests.
1373           *
1374           * An error response has already been send
1375           * and we're done here.
1376           */
1377          return JB_ERR_PARSE;
1378       }
1379    }
1380
1381    /*
1382     * Determine the actions for this URL
1383     */
1384 #ifdef FEATURE_TOGGLE
1385    if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1386    {
1387       /* Most compatible set of actions (i.e. none) */
1388       init_current_action(csp->action);
1389    }
1390    else
1391 #endif /* ndef FEATURE_TOGGLE */
1392    {
1393       get_url_actions(csp, http);
1394    }
1395
1396    /*
1397     * Save a copy of the original request for logging
1398     */
1399    http->ocmd = strdup(http->cmd);
1400    if (http->ocmd == NULL)
1401    {
1402       log_error(LOG_LEVEL_FATAL,
1403          "Out of memory copying HTTP request line");
1404    }
1405    enlist(csp->headers, http->cmd);
1406
1407    /* Append the previously read headers */
1408    list_append_list_unique(csp->headers, headers);
1409    destroy_list(headers);
1410
1411    return JB_ERR_OK;
1412
1413 }
1414
1415
1416 /*********************************************************************
1417  *
1418  * Function    : parse_client_request
1419  *
1420  * Description : Parses the client's request and decides what to do
1421  *               with it.
1422  *
1423  *               Note that since we're not using select() we could get
1424  *               blocked here if a client connected, then didn't say
1425  *               anything!
1426  *
1427  * Parameters  :
1428  *          1  :  csp = Current client state (buffers, headers, etc...)
1429  *
1430  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
1431  *
1432  *********************************************************************/
1433 static jb_err parse_client_request(struct client_state *csp)
1434 {
1435    struct http_request *http = csp->http;
1436    jb_err err;
1437
1438 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1439    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1440     && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1441     && (csp->http->ssl == 0))
1442    {
1443       /* Assume persistence until further notice */
1444       csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1445    }
1446 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1447
1448    err = sed(csp, FILTER_CLIENT_HEADERS);
1449    if (JB_ERR_OK != err)
1450    {
1451       /* XXX: Should be handled in sed(). */
1452       assert(err == JB_ERR_PARSE);
1453       log_error(LOG_LEVEL_FATAL, "Failed to parse client headers.");
1454    }
1455    csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1456
1457    /* Check request line for rewrites. */
1458    if ((NULL == csp->headers->first->str)
1459       || (strcmp(http->cmd, csp->headers->first->str) &&
1460          (JB_ERR_OK != change_request_destination(csp))))
1461    {
1462       /*
1463        * A header filter broke the request line - bail out.
1464        */
1465       write_socket(csp->cfd, MESSED_UP_REQUEST_RESPONSE, strlen(MESSED_UP_REQUEST_RESPONSE));
1466       /* XXX: Use correct size */
1467       log_error(LOG_LEVEL_CLF,
1468          "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1469       log_error(LOG_LEVEL_ERROR,
1470          "Invalid request line after applying header filters.");
1471       free_http_request(http);
1472
1473       return JB_ERR_PARSE;
1474    }
1475
1476 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1477    if (csp->http->ssl == 0)
1478    {
1479       verify_request_length(csp);
1480    }
1481 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1482
1483    return JB_ERR_OK;
1484
1485 }
1486
1487
1488 /*********************************************************************
1489  *
1490  * Function    :  chat
1491  *
1492  * Description :  Once a connection from the client has been accepted,
1493  *                this function is called (via serve()) to handle the
1494  *                main business of the communication.  This function
1495  *                returns after dealing with a single request. It can
1496  *                be called multiple times with the same client socket
1497  *                if the client is keeping the connection alive.
1498  *
1499  *                The decision whether or not a client connection will
1500  *                be kept alive is up to the caller which also must
1501  *                close the client socket when done.
1502  *
1503  *                FIXME: chat is nearly thousand lines long.
1504  *                Ridiculous.
1505  *
1506  * Parameters  :
1507  *          1  :  csp = Current client state (buffers, headers, etc...)
1508  *
1509  * Returns     :  Nothing.
1510  *
1511  *********************************************************************/
1512 static void chat(struct client_state *csp)
1513 {
1514    char buf[BUFFER_SIZE];
1515    char *hdr;
1516    char *p;
1517    fd_set rfds;
1518    int n;
1519    jb_socket maxfd;
1520    int server_body;
1521    int ms_iis5_hack = 0;
1522    unsigned long long byte_count = 0;
1523    const struct forward_spec *fwd;
1524    struct http_request *http;
1525    long len = 0; /* for buffer sizes (and negative error codes) */
1526    int buffer_and_filter_content = 0;
1527
1528    /* Skeleton for HTTP response, if we should intercept the request */
1529    struct http_response *rsp;
1530    struct timeval timeout;
1531 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1532    int watch_client_socket = 1;
1533 #endif
1534
1535    memset(buf, 0, sizeof(buf));
1536
1537    http = csp->http;
1538
1539    if (receive_client_request(csp) != JB_ERR_OK)
1540    {
1541       return;
1542    }
1543    if (parse_client_request(csp) != JB_ERR_OK)
1544    {
1545       return;
1546    }
1547
1548    /* decide how to route the HTTP request */
1549    fwd = forward_url(csp, http);
1550    if (NULL == fwd)
1551    {
1552       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
1553       /* Never get here - LOG_LEVEL_FATAL causes program exit */
1554       return;
1555    }
1556
1557    /*
1558     * build the http request to send to the server
1559     * we have to do one of the following:
1560     *
1561     * create = use the original HTTP request to create a new
1562     *          HTTP request that has either the path component
1563     *          without the http://domainspec (w/path) or the
1564     *          full orininal URL (w/url)
1565     *          Note that the path and/or the HTTP version may
1566     *          have been altered by now.
1567     *
1568     * connect = Open a socket to the host:port of the server
1569     *           and short-circuit server and client socket.
1570     *
1571     * pass =  Pass the request unchanged if forwarding a CONNECT
1572     *         request to a parent proxy. Note that we'll be sending
1573     *         the CFAIL message ourselves if connecting to the parent
1574     *         fails, but we won't send a CSUCCEED message if it works,
1575     *         since that would result in a double message (ours and the
1576     *         parent's). After sending the request to the parent, we simply
1577     *         tunnel.
1578     *
1579     * here's the matrix:
1580     *                        SSL
1581     *                    0        1
1582     *                +--------+--------+
1583     *                |        |        |
1584     *             0  | create | connect|
1585     *                | w/path |        |
1586     *  Forwarding    +--------+--------+
1587     *                |        |        |
1588     *             1  | create | pass   |
1589     *                | w/url  |        |
1590     *                +--------+--------+
1591     *
1592     */
1593
1594    if (http->ssl && connect_port_is_forbidden(csp))
1595    {
1596       const char *acceptable_connect_ports =
1597          csp->action->string[ACTION_STRING_LIMIT_CONNECT];
1598       assert(NULL != acceptable_connect_ports);
1599       log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
1600          "limit-connect{%s} doesn't allow CONNECT requests to %s",
1601          csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
1602       csp->action->flags |= ACTION_BLOCK;
1603       http->ssl = 0;
1604    }
1605
1606    if (http->ssl == 0)
1607    {
1608       freez(csp->headers->first->str);
1609       build_request_line(csp, fwd, &csp->headers->first->str);
1610    }
1611
1612    /*
1613     * We have a request. Check if one of the crunchers wants it.
1614     */
1615    if (crunch_response_triggered(csp, crunchers_all))
1616    {
1617       /*
1618        * Yes. The client got the crunch response and we're done here.
1619        */
1620       return;
1621    }
1622
1623    log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
1624
1625    if (fwd->forward_host)
1626    {
1627       log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
1628          fwd->forward_host, fwd->forward_port, http->hostport);
1629    }
1630    else
1631    {
1632       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
1633    }
1634
1635    /* here we connect to the server, gateway, or the forwarder */
1636
1637 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1638    if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
1639       && socket_is_still_alive(csp->server_connection.sfd)
1640       && connection_destination_matches(&csp->server_connection, http, fwd))
1641    {
1642       log_error(LOG_LEVEL_CONNECT,
1643          "Reusing server socket %u. Opened for %s.",
1644          csp->server_connection.sfd, csp->server_connection.host);
1645    }
1646    else
1647    {
1648       if (csp->server_connection.sfd != JB_INVALID_SOCKET)
1649       {
1650          log_error(LOG_LEVEL_CONNECT,
1651             "Closing server socket %u. Opened for %s.",
1652             csp->server_connection.sfd, csp->server_connection.host);
1653          close_socket(csp->server_connection.sfd);
1654          mark_connection_closed(&csp->server_connection);
1655       }
1656 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1657
1658       csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
1659
1660       if (csp->server_connection.sfd == JB_INVALID_SOCKET)
1661       {
1662          if (fwd->type != SOCKS_NONE)
1663          {
1664             /* Socks error. */
1665             rsp = error_response(csp, "forwarding-failed");
1666          }
1667          else if (errno == EINVAL)
1668          {
1669             rsp = error_response(csp, "no-such-domain");
1670          }
1671          else
1672          {
1673             rsp = error_response(csp, "connect-failed");
1674          }
1675
1676          /* Write the answer to the client */
1677          if (rsp != NULL)
1678          {
1679             send_crunch_response(csp, rsp);
1680          }
1681
1682          return;
1683       }
1684 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1685       save_connection_destination(csp->server_connection.sfd,
1686          http, fwd, &csp->server_connection);
1687       csp->server_connection.keep_alive_timeout =
1688          (unsigned)csp->config->keep_alive_timeout;
1689    }
1690 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1691
1692    if (fwd->forward_host || (http->ssl == 0))
1693    {
1694       hdr = list_to_text(csp->headers);
1695       if (hdr == NULL)
1696       {
1697          /* FIXME Should handle error properly */
1698          log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1699       }
1700       list_remove_all(csp->headers);
1701
1702       /*
1703        * Write the client's (modified) header to the server
1704        * (along with anything else that may be in the buffer)
1705        */
1706       if (write_socket(csp->server_connection.sfd, hdr, strlen(hdr))
1707        || (flush_socket(csp->server_connection.sfd, csp->iob) <  0))
1708       {
1709          log_error(LOG_LEVEL_CONNECT,
1710             "write header to: %s failed: %E", http->hostport);
1711
1712          rsp = error_response(csp, "connect-failed");
1713          if (rsp)
1714          {
1715             send_crunch_response(csp, rsp);
1716          }
1717
1718          freez(hdr);
1719          return;
1720       }
1721       freez(hdr);
1722    }
1723    else
1724    {
1725       /*
1726        * We're running an SSL tunnel and we're not forwarding,
1727        * so just ditch the client headers, send the "connect succeeded"
1728        * message to the client, flush the rest, and get out of the way.
1729        */
1730       list_remove_all(csp->headers);
1731       if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
1732       {
1733          return;
1734       }
1735       IOB_RESET(csp);
1736    }
1737
1738    log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
1739
1740    csp->server_connection.request_sent = time(NULL);
1741
1742    maxfd = (csp->cfd > csp->server_connection.sfd) ?
1743       csp->cfd : csp->server_connection.sfd;
1744
1745    /* pass data between the client and server
1746     * until one or the other shuts down the connection.
1747     */
1748
1749    server_body = 0;
1750
1751    for (;;)
1752    {
1753 #ifdef __OS2__
1754       /*
1755        * FD_ZERO here seems to point to an errant macro which crashes.
1756        * So do this by hand for now...
1757        */
1758       memset(&rfds,0x00,sizeof(fd_set));
1759 #else
1760       FD_ZERO(&rfds);
1761 #endif
1762 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1763       if (!watch_client_socket)
1764       {
1765          maxfd = csp->server_connection.sfd;
1766       }
1767       else
1768 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1769       {
1770          FD_SET(csp->cfd, &rfds);
1771       }
1772
1773       FD_SET(csp->server_connection.sfd, &rfds);
1774
1775 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1776       if ((csp->flags & CSP_FLAG_CHUNKED)
1777          && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
1778          && ((csp->iob->eod - csp->iob->cur) >= 5)
1779          && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
1780       {
1781          /*
1782           * XXX: This check should be obsolete now,
1783           *      but let's wait a while to be sure.
1784           */
1785          log_error(LOG_LEVEL_CONNECT,
1786             "Looks like we got the last chunk together with "
1787             "the server headers but didn't detect it earlier. "
1788             "We better stop reading.");
1789          byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
1790          csp->expected_content_length = byte_count;
1791          csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
1792       }
1793       if (server_body && server_response_is_complete(csp, byte_count))
1794       {
1795          if (csp->expected_content_length == byte_count)
1796          {
1797             log_error(LOG_LEVEL_CONNECT,
1798                "Done reading from server. Content length: %llu as expected. "
1799                "Bytes most recently read: %d.",
1800                byte_count, len);
1801          }
1802          else
1803          {
1804             log_error(LOG_LEVEL_CONNECT,
1805                "Done reading from server. Expected content length: %llu. "
1806                "Actual content length: %llu. Bytes most recently read: %d.",
1807                csp->expected_content_length, byte_count, len);
1808          }
1809          len = 0;
1810          /*
1811           * XXX: should not jump around,
1812           * chat() is complicated enough already.
1813           */
1814          goto reading_done;
1815       }
1816 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
1817
1818       timeout.tv_sec = csp->config->socket_timeout;
1819       timeout.tv_usec = 0;
1820       n = select((int)maxfd+1, &rfds, NULL, NULL, &timeout);
1821
1822       if (n == 0)
1823       {
1824          log_error(LOG_LEVEL_ERROR,
1825             "Didn't receive data in time: %s", http->url);
1826          if ((byte_count == 0) && (http->ssl == 0))
1827          {
1828             send_crunch_response(csp, error_response(csp, "connection-timeout"));
1829          }
1830          mark_server_socket_tainted(csp);
1831          return;
1832       }
1833       else if (n < 0)
1834       {
1835          log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
1836          mark_server_socket_tainted(csp);
1837          return;
1838       }
1839
1840       /*
1841        * This is the body of the browser's request,
1842        * just read and write it.
1843        *
1844        * XXX: Make sure the client doesn't use pipelining
1845        * behind Privoxy's back.
1846        */
1847       if (FD_ISSET(csp->cfd, &rfds))
1848       {
1849          int max_bytes_to_read = sizeof(buf) - 1;
1850
1851 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1852          if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1853          {
1854             if (data_is_available(csp->cfd, 0))
1855             {
1856                /*
1857                 * If the next request is already waiting, we have
1858                 * to stop select()ing the client socket. Otherwise
1859                 * we would always return right away and get nothing
1860                 * else done.
1861                 */
1862                watch_client_socket = 0;
1863                log_error(LOG_LEVEL_CONNECT,
1864                   "Stopping to watch the client socket %d. "
1865                   "There's already another request waiting.",
1866                   csp->cfd);
1867                continue;
1868             }
1869             /*
1870              * If the client socket is set, but there's no data
1871              * available on the socket, the client went fishing
1872              * and continuing talking to the server makes no sense.
1873              */
1874             log_error(LOG_LEVEL_CONNECT,
1875                "The client closed socket %d while "
1876                "the server socket %d is still open.",
1877                csp->cfd, csp->server_connection.sfd);
1878             mark_server_socket_tainted(csp);
1879             break;
1880          }
1881          if (csp->expected_client_content_length != 0)
1882          {
1883             if (csp->expected_client_content_length < (sizeof(buf) - 1))
1884             {
1885                max_bytes_to_read = (int)csp->expected_client_content_length;
1886             }
1887             log_error(LOG_LEVEL_CONNECT,
1888                "Waiting for up to %d bytes from the client.",
1889                max_bytes_to_read);
1890          }
1891          assert(max_bytes_to_read < sizeof(buf));
1892 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1893
1894          len = read_socket(csp->cfd, buf, max_bytes_to_read);
1895
1896          if (len <= 0)
1897          {
1898             /* XXX: not sure if this is necessary. */
1899             mark_server_socket_tainted(csp);
1900             break; /* "game over, man" */
1901          }
1902
1903 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1904          if (csp->expected_client_content_length != 0)
1905          {
1906             assert(len <= max_bytes_to_read);
1907             csp->expected_client_content_length -= (unsigned)len;
1908             log_error(LOG_LEVEL_CONNECT,
1909                "Expected client content length set to %llu "
1910                "after reading %d bytes.",
1911                csp->expected_client_content_length, len);
1912             if (csp->expected_client_content_length == 0)
1913             {
1914                log_error(LOG_LEVEL_CONNECT,
1915                   "Done reading from the client.");
1916                csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1917             }
1918          }
1919 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1920
1921          if (write_socket(csp->server_connection.sfd, buf, (size_t)len))
1922          {
1923             log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
1924             mark_server_socket_tainted(csp);
1925             return;
1926          }
1927          continue;
1928       }
1929
1930       /*
1931        * The server wants to talk. It could be the header or the body.
1932        * If `hdr' is null, then it's the header otherwise it's the body.
1933        * FIXME: Does `hdr' really mean `host'? No.
1934        */
1935       if (FD_ISSET(csp->server_connection.sfd, &rfds))
1936       {
1937 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1938          /*
1939           * If we are buffering content, we don't want to eat up to
1940           * buffer-limit bytes if the client no longer cares about them.
1941           * If we aren't buffering, however, a dead client socket will be
1942           * noticed pretty much right away anyway, so we can reduce the
1943           * overhead by skipping the check.
1944           */
1945          if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
1946          {
1947 #ifdef _WIN32
1948             log_error(LOG_LEVEL_CONNECT,
1949                "The server still wants to talk, but the client may already have hung up on us.");
1950 #else
1951             log_error(LOG_LEVEL_CONNECT,
1952                "The server still wants to talk, but the client hung up on us.");
1953             mark_server_socket_tainted(csp);
1954             return;
1955 #endif /* def _WIN32 */
1956          }
1957 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1958
1959          fflush(NULL);
1960          len = read_socket(csp->server_connection.sfd, buf, sizeof(buf) - 1);
1961
1962          if (len < 0)
1963          {
1964             log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
1965
1966             if (http->ssl && (fwd->forward_host == NULL))
1967             {
1968                /*
1969                 * Just hang up. We already confirmed the client's CONNECT
1970                 * request with status code 200 and unencrypted content is
1971                 * no longer welcome.
1972                 */
1973                log_error(LOG_LEVEL_ERROR,
1974                   "CONNECT already confirmed. Unable to tell the client about the problem.");
1975                return;
1976             }
1977             else if (byte_count)
1978             {
1979                /*
1980                 * Just hang up. We already transmitted the original headers
1981                 * and parts of the original content and therefore missed the
1982                 * chance to send an error message (without risking data corruption).
1983                 *
1984                 * XXX: we could retry with a fancy range request here.
1985                 */
1986                log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
1987                   "Unable to tell the client about the problem.");
1988                mark_server_socket_tainted(csp);
1989                return;
1990             }
1991             /*
1992              * XXX: Consider handling the cases above the same.
1993              */
1994             mark_server_socket_tainted(csp);
1995             len = 0;
1996          }
1997
1998 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1999          if (csp->flags & CSP_FLAG_CHUNKED)
2000          {
2001             if ((len >= 5) && !memcmp(buf+len-5, "0\r\n\r\n", 5))
2002             {
2003                /* XXX: this is a temporary hack */
2004                log_error(LOG_LEVEL_CONNECT,
2005                   "Looks like we reached the end of the last chunk. "
2006                   "We better stop reading.");
2007                csp->expected_content_length = byte_count + (unsigned long long)len;
2008                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2009             }
2010          }
2011          reading_done:
2012 #endif  /* FEATURE_CONNECTION_KEEP_ALIVE */
2013
2014          /*
2015           * Add a trailing zero to let be able to use string operations.
2016           * XXX: do we still need this with filter_popups gone?
2017           */
2018          buf[len] = '\0';
2019
2020          /*
2021           * Normally, this would indicate that we've read
2022           * as much as the server has sent us and we can
2023           * close the client connection.  However, Microsoft
2024           * in its wisdom has released IIS/5 with a bug that
2025           * prevents it from sending the trailing \r\n in
2026           * a 302 redirect header (and possibly other headers).
2027           * To work around this if we've haven't parsed
2028           * a full header we'll append a trailing \r\n
2029           * and see if this now generates a valid one.
2030           *
2031           * This hack shouldn't have any impacts.  If we've
2032           * already transmitted the header or if this is a
2033           * SSL connection, then we won't bother with this
2034           * hack.  So we only work on partially received
2035           * headers.  If we append a \r\n and this still
2036           * doesn't generate a valid header, then we won't
2037           * transmit anything to the client.
2038           */
2039          if (len == 0)
2040          {
2041
2042             if (server_body || http->ssl)
2043             {
2044                /*
2045                 * If we have been buffering up the document,
2046                 * now is the time to apply content modification
2047                 * and send the result to the client.
2048                 */
2049                if (buffer_and_filter_content)
2050                {
2051                   p = execute_content_filters(csp);
2052                   /*
2053                    * If content filtering fails, use the original
2054                    * buffer and length.
2055                    * (see p != NULL ? p : csp->iob->cur below)
2056                    */
2057                   if (NULL == p)
2058                   {
2059                      csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2060                   }
2061 #ifdef FEATURE_COMPRESSION
2062                   else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2063                      && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2064                   {
2065                      char *compressed_content = compress_buffer(p,
2066                         (size_t *)&csp->content_length, csp->config->compression_level);
2067                      if (compressed_content != NULL)
2068                      {
2069                         freez(p);
2070                         p = compressed_content;
2071                         csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2072                      }
2073                   }
2074 #endif
2075
2076                   if (JB_ERR_OK != update_server_headers(csp))
2077                   {
2078                      log_error(LOG_LEVEL_FATAL,
2079                         "Failed to update server headers. after filtering.");
2080                   }
2081
2082                   hdr = list_to_text(csp->headers);
2083                   if (hdr == NULL)
2084                   {
2085                      /* FIXME Should handle error properly */
2086                      log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2087                   }
2088
2089                   if (write_socket(csp->cfd, hdr, strlen(hdr))
2090                    || write_socket(csp->cfd,
2091                          ((p != NULL) ? p : csp->iob->cur), (size_t)csp->content_length))
2092                   {
2093                      log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2094                      freez(hdr);
2095                      freez(p);
2096                      mark_server_socket_tainted(csp);
2097                      return;
2098                   }
2099
2100                   freez(hdr);
2101                   freez(p);
2102                }
2103
2104                break; /* "game over, man" */
2105             }
2106
2107             /*
2108              * This is NOT the body, so
2109              * Let's pretend the server just sent us a blank line.
2110              */
2111             snprintf(buf, sizeof(buf), "\r\n");
2112             len = (int)strlen(buf);
2113
2114             /*
2115              * Now, let the normal header parsing algorithm below do its
2116              * job.  If it fails, we'll exit instead of continuing.
2117              */
2118
2119             ms_iis5_hack = 1;
2120          }
2121
2122          /*
2123           * If this is an SSL connection or we're in the body
2124           * of the server document, just write it to the client,
2125           * unless we need to buffer the body for later content-filtering
2126           */
2127          if (server_body || http->ssl)
2128          {
2129             if (buffer_and_filter_content)
2130             {
2131                /*
2132                 * If there is no memory left for buffering the content, or the buffer limit
2133                 * has been reached, switch to non-filtering mode, i.e. make & write the
2134                 * header, flush the iob and buf, and get out of the way.
2135                 */
2136                if (add_to_iob(csp, buf, len))
2137                {
2138                   size_t hdrlen;
2139                   long flushed;
2140
2141                   log_error(LOG_LEVEL_INFO,
2142                      "Flushing header and buffers. Stepping back from filtering.");
2143
2144                   hdr = list_to_text(csp->headers);
2145                   if (hdr == NULL)
2146                   {
2147                      /*
2148                       * Memory is too tight to even generate the header.
2149                       * Send our static "Out-of-memory" page.
2150                       */
2151                      log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2152                      rsp = cgi_error_memory();
2153                      send_crunch_response(csp, rsp);
2154                      mark_server_socket_tainted(csp);
2155                      return;
2156                   }
2157                   hdrlen = strlen(hdr);
2158
2159                   if (write_socket(csp->cfd, hdr, hdrlen)
2160                    || ((flushed = flush_socket(csp->cfd, csp->iob)) < 0)
2161                    || (write_socket(csp->cfd, buf, (size_t)len)))
2162                   {
2163                      log_error(LOG_LEVEL_CONNECT,
2164                         "Flush header and buffers to client failed: %E");
2165                      freez(hdr);
2166                      mark_server_socket_tainted(csp);
2167                      return;
2168                   }
2169
2170                   /*
2171                    * Reset the byte_count to the amount of bytes
2172                    * we just flushed. len will be added a few lines below,
2173                    * hdrlen doesn't matter for LOG_LEVEL_CLF.
2174                    */
2175                   byte_count = (unsigned long long)flushed;
2176                   freez(hdr);
2177                   buffer_and_filter_content = 0;
2178                   server_body = 1;
2179                }
2180             }
2181             else
2182             {
2183                if (write_socket(csp->cfd, buf, (size_t)len))
2184                {
2185                   log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2186                   mark_server_socket_tainted(csp);
2187                   return;
2188                }
2189             }
2190             byte_count += (unsigned long long)len;
2191             continue;
2192          }
2193          else
2194          {
2195             /*
2196              * We're still looking for the end of the server's header.
2197              * Buffer up the data we just read.  If that fails, there's
2198              * little we can do but send our static out-of-memory page.
2199              */
2200             if (add_to_iob(csp, buf, len))
2201             {
2202                log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2203                rsp = cgi_error_memory();
2204                send_crunch_response(csp, rsp);
2205                mark_server_socket_tainted(csp);
2206                return;
2207             }
2208
2209             /* Convert iob into something sed() can digest */
2210             if (JB_ERR_PARSE == get_server_headers(csp))
2211             {
2212                if (ms_iis5_hack)
2213                {
2214                   /*
2215                    * Well, we tried our MS IIS/5 hack and it didn't work.
2216                    * The header is incomplete and there isn't anything
2217                    * we can do about it.
2218                    */
2219                   log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2220                      "Applying the MS IIS5 hack didn't help.");
2221                   log_error(LOG_LEVEL_CLF,
2222                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2223                   write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2224                      strlen(INVALID_SERVER_HEADERS_RESPONSE));
2225                   mark_server_socket_tainted(csp);
2226                   return;
2227                }
2228                else
2229                {
2230                   /*
2231                    * Since we have to wait for more from the server before
2232                    * we can parse the headers we just continue here.
2233                    */
2234                   log_error(LOG_LEVEL_CONNECT,
2235                      "Continuing buffering headers. Bytes most recently read: %d.",
2236                      len);
2237                   continue;
2238                }
2239             }
2240             else
2241             {
2242                /*
2243                 * Account for the content bytes we
2244                 * might have gotten with the headers.
2245                 */
2246                assert(csp->iob->eod >= csp->iob->cur);
2247                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2248             }
2249
2250             /* Did we actually get anything? */
2251             if (NULL == csp->headers->first)
2252             {
2253                if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2254                {
2255                   log_error(LOG_LEVEL_ERROR,
2256                      "No server or forwarder response received on socket %d. "
2257                      "Closing client socket %d without sending data.",
2258                      csp->server_connection.sfd, csp->cfd);
2259                   log_error(LOG_LEVEL_CLF,
2260                      "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2261                }
2262                else
2263                {
2264                   log_error(LOG_LEVEL_ERROR,
2265                      "No server or forwarder response received on socket %d.",
2266                      csp->server_connection.sfd);
2267                   send_crunch_response(csp, error_response(csp, "no-server-data"));
2268                }
2269                free_http_request(http);
2270                mark_server_socket_tainted(csp);
2271                return;
2272             }
2273
2274             assert(csp->headers->first->str);
2275             assert(!http->ssl);
2276             if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2277                 strncmpic(csp->headers->first->str, "ICY", 3))
2278             {
2279                /*
2280                 * It doesn't look like a HTTP (or Shoutcast) response:
2281                 * tell the client and log the problem.
2282                 */
2283                if (strlen(csp->headers->first->str) > 30)
2284                {
2285                   csp->headers->first->str[30] = '\0';
2286                }
2287                log_error(LOG_LEVEL_ERROR,
2288                   "Invalid server or forwarder response. Starts with: %s",
2289                   csp->headers->first->str);
2290                log_error(LOG_LEVEL_CLF,
2291                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2292                write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2293                   strlen(INVALID_SERVER_HEADERS_RESPONSE));
2294                free_http_request(http);
2295                mark_server_socket_tainted(csp);
2296                return;
2297             }
2298
2299             /*
2300              * We have now received the entire server header,
2301              * filter it and send the result to the client
2302              */
2303             if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2304             {
2305                log_error(LOG_LEVEL_FATAL, "Failed to parse server headers.");
2306             }
2307             hdr = list_to_text(csp->headers);
2308             if (hdr == NULL)
2309             {
2310                /* FIXME Should handle error properly */
2311                log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2312             }
2313
2314             if ((csp->flags & CSP_FLAG_CHUNKED)
2315                && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2316                && ((csp->iob->eod - csp->iob->cur) >= 5)
2317                && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2318             {
2319                log_error(LOG_LEVEL_CONNECT,
2320                   "Looks like we got the last chunk together with "
2321                   "the server headers. We better stop reading.");
2322                byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2323                csp->expected_content_length = byte_count;
2324                csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2325             }
2326
2327             csp->server_connection.response_received = time(NULL);
2328
2329             if (crunch_response_triggered(csp, crunchers_light))
2330             {
2331                /*
2332                 * One of the tags created by a server-header
2333                 * tagger triggered a crunch. We already
2334                 * delivered the crunch response to the client
2335                 * and are done here after cleaning up.
2336                 */
2337                 freez(hdr);
2338                 mark_server_socket_tainted(csp);
2339                 return;
2340             }
2341             /* Buffer and pcrs filter this if appropriate. */
2342
2343             if (!http->ssl) /* We talk plaintext */
2344             {
2345                buffer_and_filter_content = content_requires_filtering(csp);
2346             }
2347             /*
2348              * Only write if we're not buffering for content modification
2349              */
2350             if (!buffer_and_filter_content)
2351             {
2352                /*
2353                 * Write the server's (modified) header to
2354                 * the client (along with anything else that
2355                 * may be in the buffer)
2356                 */
2357
2358                if (write_socket(csp->cfd, hdr, strlen(hdr))
2359                 || ((len = flush_socket(csp->cfd, csp->iob)) < 0))
2360                {
2361                   log_error(LOG_LEVEL_CONNECT, "write header to client failed: %E");
2362
2363                   /*
2364                    * The write failed, so don't bother mentioning it
2365                    * to the client... it probably can't hear us anyway.
2366                    */
2367                   freez(hdr);
2368                   mark_server_socket_tainted(csp);
2369                   return;
2370                }
2371             }
2372
2373             /* we're finished with the server's header */
2374
2375             freez(hdr);
2376             server_body = 1;
2377
2378             /*
2379              * If this was a MS IIS/5 hack then it means the server
2380              * has already closed the connection. Nothing more to read.
2381              * Time to bail.
2382              */
2383             if (ms_iis5_hack)
2384             {
2385                log_error(LOG_LEVEL_ERROR,
2386                   "Closed server connection detected. "
2387                   "Applying the MS IIS5 hack didn't help.");
2388                log_error(LOG_LEVEL_CLF,
2389                   "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2390                write_socket(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2391                   strlen(INVALID_SERVER_HEADERS_RESPONSE));
2392                mark_server_socket_tainted(csp);
2393                return;
2394             }
2395          }
2396          continue;
2397       }
2398       mark_server_socket_tainted(csp);
2399       return; /* huh? we should never get here */
2400    }
2401
2402    if (csp->content_length == 0)
2403    {
2404       /*
2405        * If Privoxy didn't recalculate the Content-Length,
2406        * byte_count is still correct.
2407        */
2408       csp->content_length = byte_count;
2409    }
2410
2411 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2412    if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2413       && (csp->expected_content_length != byte_count))
2414    {
2415       log_error(LOG_LEVEL_CONNECT,
2416          "Received %llu bytes while expecting %llu.",
2417          byte_count, csp->expected_content_length);
2418       mark_server_socket_tainted(csp);
2419    }
2420 #endif
2421
2422    log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
2423       csp->ip_addr_str, http->ocmd, csp->content_length);
2424
2425    csp->server_connection.timestamp = time(NULL);
2426 }
2427
2428
2429 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2430 /*********************************************************************
2431  *
2432  * Function    :  prepare_csp_for_next_request
2433  *
2434  * Description :  Put the csp in a mostly vergin state.
2435  *
2436  * Parameters  :
2437  *          1  :  csp = Current client state (buffers, headers, etc...)
2438  *
2439  * Returns     :  N/A
2440  *
2441  *********************************************************************/
2442 static void prepare_csp_for_next_request(struct client_state *csp)
2443 {
2444    unsigned int toggled_on_flag_set = (0 != (csp->flags & CSP_FLAG_TOGGLED_ON));
2445
2446    csp->content_type = 0;
2447    csp->content_length = 0;
2448    csp->expected_content_length = 0;
2449    csp->expected_client_content_length = 0;
2450    list_remove_all(csp->headers);
2451    freez(csp->iob->buf);
2452    memset(csp->iob, 0, sizeof(csp->iob));
2453    freez(csp->error_message);
2454    free_http_request(csp->http);
2455    destroy_list(csp->headers);
2456    destroy_list(csp->tags);
2457    free_current_action(csp->action);
2458    if (NULL != csp->fwd)
2459    {
2460       unload_forward_spec(csp->fwd);
2461       csp->fwd = NULL;
2462    }
2463    /* XXX: Store per-connection flags someplace else. */
2464    csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
2465    if (toggled_on_flag_set)
2466    {
2467       csp->flags |= CSP_FLAG_TOGGLED_ON;
2468    }
2469 }
2470 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2471
2472
2473 /*********************************************************************
2474  *
2475  * Function    :  serve
2476  *
2477  * Description :  This is little more than chat.  We only "serve" to
2478  *                to close (or remember) any socket that chat may have
2479  *                opened.
2480  *
2481  * Parameters  :
2482  *          1  :  csp = Current client state (buffers, headers, etc...)
2483  *
2484  * Returns     :  N/A
2485  *
2486  *********************************************************************/
2487 #ifdef AMIGA
2488 void serve(struct client_state *csp)
2489 #else /* ifndef AMIGA */
2490 static void serve(struct client_state *csp)
2491 #endif /* def AMIGA */
2492 {
2493 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2494 #ifdef FEATURE_CONNECTION_SHARING
2495    static int monitor_thread_running = 0;
2496 #endif /* def FEATURE_CONNECTION_SHARING */
2497    int continue_chatting = 0;
2498
2499    do
2500    {
2501       unsigned int latency;
2502       int config_file_change_detected = 0; /* Only used for debugging */
2503
2504       chat(csp);
2505
2506       /*
2507        * If the request has been crunched,
2508        * the calculated latency is zero.
2509        */
2510       latency = (unsigned)(csp->server_connection.response_received -
2511          csp->server_connection.request_sent) / 2;
2512
2513       continue_chatting = (csp->config->feature_flags
2514          & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2515          && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
2516          && ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
2517              || (csp->flags & CSP_FLAG_CRUNCHED))
2518          && (csp->cfd != JB_INVALID_SOCKET)
2519          && ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2520              || (csp->config->feature_flags &
2521                 RUNTIME_FEATURE_CONNECTION_SHARING));
2522
2523       if (continue_chatting && !(csp->flags & CSP_FLAG_CRUNCHED))
2524       {
2525          continue_chatting = (csp->server_connection.sfd != JB_INVALID_SOCKET)
2526             && socket_is_still_alive(csp->server_connection.sfd);
2527          if (continue_chatting)
2528          {
2529             if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
2530             {
2531                csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
2532                log_error(LOG_LEVEL_CONNECT,
2533                   "The server didn't specify how long the connection will stay open. "
2534                   "Assumed timeout is: %u.", csp->server_connection.keep_alive_timeout);
2535             }
2536             continue_chatting = (latency < csp->server_connection.keep_alive_timeout);
2537          }
2538       }
2539
2540       if (continue_chatting && any_loaded_file_changed(csp->config->config_file_list))
2541       {
2542          continue_chatting = 0;
2543          config_file_change_detected = 1;
2544       }
2545
2546       if (continue_chatting)
2547       {
2548          unsigned int client_timeout = 1; /* XXX: Use something else here? */
2549
2550          if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2551          {
2552             if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2553             {
2554                client_timeout = (unsigned)csp->server_connection.keep_alive_timeout - latency;
2555                log_error(LOG_LEVEL_CONNECT,
2556                   "Waiting for the next client request on socket %d. "
2557                   "Keeping the server socket %d to %s open.",
2558                   csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2559             }
2560             else
2561             {
2562                log_error(LOG_LEVEL_CONNECT,
2563                   "Waiting for the next client request on socket %d. "
2564                   "No server socket to keep open.", csp->cfd);
2565             }
2566          }
2567          if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
2568             && data_is_available(csp->cfd, (int)client_timeout)
2569             && socket_is_still_alive(csp->cfd))
2570          {
2571             log_error(LOG_LEVEL_CONNECT,
2572                "Client request arrived in time on socket %d.", csp->cfd);
2573             prepare_csp_for_next_request(csp);
2574          }
2575          else
2576          {
2577             if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
2578             {
2579                log_error(LOG_LEVEL_CONNECT,
2580                   "No additional client request received in time on socket %d.",
2581                   csp->cfd);
2582             }
2583 #ifdef FEATURE_CONNECTION_SHARING
2584             if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2585                && (socket_is_still_alive(csp->server_connection.sfd)))
2586             {
2587                time_t time_open = time(NULL) - csp->server_connection.timestamp;
2588
2589                if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
2590                {
2591                   break;
2592                }
2593
2594                remember_connection(&csp->server_connection);
2595                csp->server_connection.sfd = JB_INVALID_SOCKET;
2596                close_socket(csp->cfd);
2597                csp->cfd = JB_INVALID_SOCKET;
2598                privoxy_mutex_lock(&connection_reuse_mutex);
2599                if (!monitor_thread_running)
2600                {
2601                   monitor_thread_running = 1;
2602                   privoxy_mutex_unlock(&connection_reuse_mutex);
2603                   wait_for_alive_connections();
2604                   privoxy_mutex_lock(&connection_reuse_mutex);
2605                   monitor_thread_running = 0;
2606                }
2607                privoxy_mutex_unlock(&connection_reuse_mutex);
2608             }
2609 #endif /* def FEATURE_CONNECTION_SHARING */
2610             break;
2611          }
2612       }
2613       else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2614       {
2615          log_error(LOG_LEVEL_CONNECT,
2616             "The connection on server socket %d to %s isn't reusable. Closing. "
2617             "Server connection: keep-alive %u, tainted: %u, socket alive %u. "
2618             "Client connection: socket alive: %u. Server timeout: %u. "
2619             "Configuration file change detected: %u",
2620             csp->server_connection.sfd, csp->server_connection.host,
2621             0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
2622             0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
2623             socket_is_still_alive(csp->server_connection.sfd),
2624             socket_is_still_alive(csp->cfd),
2625             csp->server_connection.keep_alive_timeout,
2626             config_file_change_detected);
2627       }
2628    } while (continue_chatting);
2629
2630 #else
2631    chat(csp);
2632 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2633
2634    if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2635    {
2636 #ifdef FEATURE_CONNECTION_SHARING
2637       if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2638       {
2639          forget_connection(csp->server_connection.sfd);
2640       }
2641 #endif /* def FEATURE_CONNECTION_SHARING */
2642       close_socket(csp->server_connection.sfd);
2643    }
2644
2645 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2646    mark_connection_closed(&csp->server_connection);
2647 #endif
2648
2649    if (csp->cfd != JB_INVALID_SOCKET)
2650    {
2651       close_socket(csp->cfd);
2652    }
2653
2654    csp->flags &= ~CSP_FLAG_ACTIVE;
2655
2656 }
2657
2658
2659 #ifdef __BEOS__
2660 /*********************************************************************
2661  *
2662  * Function    :  server_thread
2663  *
2664  * Description :  We only exist to call `serve' in a threaded environment.
2665  *
2666  * Parameters  :
2667  *          1  :  data = Current client state (buffers, headers, etc...)
2668  *
2669  * Returns     :  Always 0.
2670  *
2671  *********************************************************************/
2672 static int32 server_thread(void *data)
2673 {
2674    serve((struct client_state *) data);
2675    return 0;
2676
2677 }
2678 #endif
2679
2680
2681 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2682 /*********************************************************************
2683  *
2684  * Function    :  usage
2685  *
2686  * Description :  Print usage info & exit.
2687  *
2688  * Parameters  :  Pointer to argv[0] for identifying ourselves
2689  *
2690  * Returns     :  No. ,-)
2691  *
2692  *********************************************************************/
2693 static void usage(const char *myname)
2694 {
2695    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
2696           "Usage: %s "
2697 #if defined(unix)
2698           "[--chroot] "
2699 #endif /* defined(unix) */
2700           "[--help] "
2701 #if defined(unix)
2702           "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
2703 #endif /* defined(unix) */
2704           "[--version] [configfile]\n"
2705           "Aborting\n", myname);
2706
2707    exit(2);
2708
2709 }
2710 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
2711
2712
2713 #ifdef MUTEX_LOCKS_AVAILABLE
2714 /*********************************************************************
2715  *
2716  * Function    :  privoxy_mutex_lock
2717  *
2718  * Description :  Locks a mutex.
2719  *
2720  * Parameters  :
2721  *          1  :  mutex = The mutex to lock.
2722  *
2723  * Returns     :  Void. May exit in case of errors.
2724  *
2725  *********************************************************************/
2726 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
2727 {
2728 #ifdef FEATURE_PTHREAD
2729    int err = pthread_mutex_lock(mutex);
2730    if (err)
2731    {
2732       if (mutex != &log_mutex)
2733       {
2734          log_error(LOG_LEVEL_FATAL,
2735             "Mutex locking failed: %s.\n", strerror(err));
2736       }
2737       exit(1);
2738    }
2739 #else
2740    EnterCriticalSection(mutex);
2741 #endif /* def FEATURE_PTHREAD */
2742 }
2743
2744
2745 /*********************************************************************
2746  *
2747  * Function    :  privoxy_mutex_unlock
2748  *
2749  * Description :  Unlocks a mutex.
2750  *
2751  * Parameters  :
2752  *          1  :  mutex = The mutex to unlock.
2753  *
2754  * Returns     :  Void. May exit in case of errors.
2755  *
2756  *********************************************************************/
2757 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
2758 {
2759 #ifdef FEATURE_PTHREAD
2760    int err = pthread_mutex_unlock(mutex);
2761    if (err)
2762    {
2763       if (mutex != &log_mutex)
2764       {
2765          log_error(LOG_LEVEL_FATAL,
2766             "Mutex unlocking failed: %s.\n", strerror(err));
2767       }
2768       exit(1);
2769    }
2770 #else
2771    LeaveCriticalSection(mutex);
2772 #endif /* def FEATURE_PTHREAD */
2773 }
2774
2775
2776 /*********************************************************************
2777  *
2778  * Function    :  privoxy_mutex_init
2779  *
2780  * Description :  Prepares a mutex.
2781  *
2782  * Parameters  :
2783  *          1  :  mutex = The mutex to initialize.
2784  *
2785  * Returns     :  Void. May exit in case of errors.
2786  *
2787  *********************************************************************/
2788 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
2789 {
2790 #ifdef FEATURE_PTHREAD
2791    int err = pthread_mutex_init(mutex, 0);
2792    if (err)
2793    {
2794       printf("Fatal error. Mutex initialization failed: %s.\n",
2795          strerror(err));
2796       exit(1);
2797    }
2798 #else
2799    InitializeCriticalSection(mutex);
2800 #endif /* def FEATURE_PTHREAD */
2801 }
2802 #endif /* def MUTEX_LOCKS_AVAILABLE */
2803
2804 /*********************************************************************
2805  *
2806  * Function    :  initialize_mutexes
2807  *
2808  * Description :  Prepares mutexes if mutex support is available.
2809  *
2810  * Parameters  :  None
2811  *
2812  * Returns     :  Void, exits in case of errors.
2813  *
2814  *********************************************************************/
2815 static void initialize_mutexes(void)
2816 {
2817 #ifdef MUTEX_LOCKS_AVAILABLE
2818    /*
2819     * Prepare global mutex semaphores
2820     */
2821    privoxy_mutex_init(&log_mutex);
2822    privoxy_mutex_init(&log_init_mutex);
2823    privoxy_mutex_init(&connection_reuse_mutex);
2824
2825    /*
2826     * XXX: The assumptions below are a bit naive
2827     * and can cause locks that aren't necessary.
2828     *
2829     * For example older FreeBSD versions (< 6.x?)
2830     * have no gethostbyname_r, but gethostbyname is
2831     * thread safe.
2832     */
2833 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
2834    privoxy_mutex_init(&resolver_mutex);
2835 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
2836    /*
2837     * XXX: should we use a single mutex for
2838     * localtime() and gmtime() as well?
2839     */
2840 #ifndef HAVE_GMTIME_R
2841    privoxy_mutex_init(&gmtime_mutex);
2842 #endif /* ndef HAVE_GMTIME_R */
2843
2844 #ifndef HAVE_LOCALTIME_R
2845    privoxy_mutex_init(&localtime_mutex);
2846 #endif /* ndef HAVE_GMTIME_R */
2847
2848 #ifndef HAVE_RANDOM
2849    privoxy_mutex_init(&rand_mutex);
2850 #endif /* ndef HAVE_RANDOM */
2851
2852 #endif /* def MUTEX_LOCKS_AVAILABLE */
2853 }
2854
2855
2856 /*********************************************************************
2857  *
2858  * Function    :  main
2859  *
2860  * Description :  Load the config file and start the listen loop.
2861  *                This function is a lot more *sane* with the `load_config'
2862  *                and `listen_loop' functions; although it stills does
2863  *                a *little* too much for my taste.
2864  *
2865  * Parameters  :
2866  *          1  :  argc = Number of parameters (including $0).
2867  *          2  :  argv = Array of (char *)'s to the parameters.
2868  *
2869  * Returns     :  1 if : can't open config file, unrecognized directive,
2870  *                stats requested in multi-thread mode, can't open the
2871  *                log file, can't open the jar file, listen port is invalid,
2872  *                any load fails, and can't bind port.
2873  *
2874  *                Else main never returns, the process must be signaled
2875  *                to terminate execution.  Or, on Windows, use the
2876  *                "File", "Exit" menu option.
2877  *
2878  *********************************************************************/
2879 #ifdef __MINGW32__
2880 int real_main(int argc, char **argv)
2881 #else
2882 int main(int argc, char **argv)
2883 #endif
2884 {
2885    int argc_pos = 0;
2886    unsigned int random_seed;
2887 #ifdef unix
2888    struct passwd *pw = NULL;
2889    struct group *grp = NULL;
2890    int do_chroot = 0;
2891    char *pre_chroot_nslookup_to_load_resolver = NULL;
2892 #endif
2893
2894    Argc = argc;
2895    Argv = argv;
2896
2897    configfile =
2898 #if !defined(_WIN32)
2899    "config"
2900 #else
2901    "config.txt"
2902 #endif
2903       ;
2904
2905    /* Prepare mutexes if supported and necessary. */
2906    initialize_mutexes();
2907
2908    /* Enable logging until further notice. */
2909    init_log_module();
2910
2911    /*
2912     * Parse the command line arguments
2913     *
2914     * XXX: simply printing usage information in case of
2915     * invalid arguments isn't particularly user friendly.
2916     */
2917    while (++argc_pos < argc)
2918    {
2919 #ifdef _WIN32
2920       /* Check to see if the service must be installed or uninstalled */
2921       if (strncmp(argv[argc_pos], "--install", 9) == 0)
2922       {
2923          const char *pName = argv[argc_pos] + 9;
2924          if (*pName == ':')
2925             pName++;
2926          exit((install_service(pName)) ? 0 : 1);
2927       }
2928       else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
2929       {
2930          const char *pName = argv[argc_pos] + 11;
2931          if (*pName == ':')
2932             pName++;
2933          exit((uninstall_service(pName)) ? 0 : 1);
2934       }
2935       else if (strcmp(argv[argc_pos], "--service") == 0)
2936       {
2937          bRunAsService = TRUE;
2938          w32_set_service_cwd();
2939          atexit(w32_service_exit_notify);
2940       }
2941       else
2942 #endif /* defined(_WIN32) */
2943
2944
2945 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
2946
2947       if (strcmp(argv[argc_pos], "--help") == 0)
2948       {
2949          usage(argv[0]);
2950       }
2951
2952       else if (strcmp(argv[argc_pos], "--version") == 0)
2953       {
2954          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
2955          exit(0);
2956       }
2957
2958 #if defined(unix)
2959
2960       else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
2961       {
2962          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
2963          daemon_mode = 0;
2964       }
2965
2966       else if (strcmp(argv[argc_pos], "--pidfile") == 0)
2967       {
2968          if (++argc_pos == argc) usage(argv[0]);
2969          pidfile = strdup(argv[argc_pos]);
2970       }
2971
2972       else if (strcmp(argv[argc_pos], "--user") == 0)
2973       {
2974          char *user_arg;
2975          char *group_name;
2976
2977          if (++argc_pos == argc) usage(argv[argc_pos]);
2978
2979          user_arg = strdup(argv[argc_pos]);
2980          if (NULL == user_arg)
2981          {
2982             log_error(LOG_LEVEL_FATAL,
2983                "Out of memory splitting --user argument '%s'.", argv[argc_pos]);
2984          }
2985          group_name = strchr(user_arg, '.');
2986          if (NULL != group_name)
2987          {
2988             /* Nul-terminate the user name */
2989             *group_name = '\0';
2990
2991             /* Skip the former delimiter to actually reach the group name */
2992             group_name++;
2993
2994             grp = getgrnam(group_name);
2995             if (NULL == grp)
2996             {
2997                log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
2998             }
2999          }
3000          pw = getpwnam(user_arg);
3001          if (NULL == pw)
3002          {
3003             log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3004          }
3005
3006          freez(user_arg);
3007       }
3008
3009       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3010       {
3011          if (++argc_pos == argc) usage(argv[0]);
3012          pre_chroot_nslookup_to_load_resolver = strdup(argv[argc_pos]);
3013       }
3014
3015       else if (strcmp(argv[argc_pos], "--chroot") == 0)
3016       {
3017          do_chroot = 1;
3018       }
3019 #endif /* defined(unix) */
3020
3021       else if (argc_pos + 1 != argc)
3022       {
3023          /*
3024           * This is neither the last command line
3025           * option, nor was it recognized before,
3026           * therefore it must be invalid.
3027           */
3028          usage(argv[0]);
3029       }
3030       else
3031
3032 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3033       {
3034          configfile = argv[argc_pos];
3035       }
3036
3037    } /* -END- while (more arguments) */
3038
3039    show_version(Argv[0]);
3040
3041 #if defined(unix)
3042    if (*configfile != '/')
3043    {
3044       char cwd[BUFFER_SIZE];
3045       char *abs_file;
3046       size_t abs_file_size;
3047
3048       /* make config-filename absolute here */
3049       if (NULL == getcwd(cwd, sizeof(cwd)))
3050       {
3051          perror("failed to get current working directory");
3052          exit(1);
3053       }
3054
3055       /* XXX: why + 5? */
3056       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3057       basedir = strdup(cwd);
3058
3059       if (NULL == basedir ||
3060           NULL == (abs_file = malloc(abs_file_size)))
3061       {
3062          perror("malloc failed");
3063          exit(1);
3064       }
3065       strlcpy(abs_file, basedir, abs_file_size);
3066       strlcat(abs_file, "/", abs_file_size);
3067       strlcat(abs_file, configfile, abs_file_size);
3068       configfile = abs_file;
3069    }
3070 #endif /* defined unix */
3071
3072
3073    files->next = NULL;
3074    clients->next = NULL;
3075
3076    /* XXX: factor out initialising after the next stable release. */
3077 #ifdef AMIGA
3078    InitAmiga();
3079 #elif defined(_WIN32)
3080    InitWin32();
3081 #endif
3082
3083    random_seed = (unsigned int)time(NULL);
3084 #ifdef HAVE_RANDOM
3085    srandom(random_seed);
3086 #else
3087    srand(random_seed);
3088 #endif /* ifdef HAVE_RANDOM */
3089
3090    /*
3091     * Unix signal handling
3092     *
3093     * Catch the abort, interrupt and terminate signals for a graceful exit
3094     * Catch the hangup signal so the errlog can be reopened.
3095     * Ignore the broken pipe signals (FIXME: Why?)
3096     */
3097 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3098 {
3099    int idx;
3100    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3101
3102    for (idx = 0; idx < SZ(catched_signals); idx++)
3103    {
3104 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3105       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3106 #else
3107       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3108 #endif /* ifdef sun */
3109       {
3110          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3111       }
3112    }
3113
3114    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3115    {
3116       log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3117    }
3118
3119 }
3120 #else /* ifdef _WIN32 */
3121 # ifdef _WIN_CONSOLE
3122    /*
3123     * We *are* in a windows console app.
3124     * Print a verbose messages about FAQ's and such
3125     */
3126    printf("%s", win32_blurb);
3127 # endif /* def _WIN_CONSOLE */
3128 #endif /* def _WIN32 */
3129
3130
3131    /* Initialize the CGI subsystem */
3132    cgi_init_error_messages();
3133
3134    /*
3135     * If runnig on unix and without the --nodaemon
3136     * option, become a daemon. I.e. fork, detach
3137     * from tty and get process group leadership
3138     */
3139 #if defined(unix)
3140 {
3141    if (daemon_mode)
3142    {
3143       int fd;
3144       pid_t pid = fork();
3145
3146       if (pid < 0) /* error */
3147       {
3148          perror("fork");
3149          exit(3);
3150       }
3151       else if (pid != 0) /* parent */
3152       {
3153          int status;
3154          pid_t wpid;
3155          /*
3156           * must check for errors
3157           * child died due to missing files aso
3158           */
3159          sleep(1);
3160          wpid = waitpid(pid, &status, WNOHANG);
3161          if (wpid != 0)
3162          {
3163             exit(1);
3164          }
3165          exit(0);
3166       }
3167       /* child */
3168
3169       setsid();
3170
3171       /*
3172        * stderr (fd 2) will be closed later on,
3173        * when the config file has been parsed.
3174        */
3175       close(0);
3176       close(1);
3177
3178       /*
3179        * Reserve fd 0 and 1 to prevent abort() and friends
3180        * from sending stuff to the clients or servers.
3181        */
3182       fd = open("/dev/null", O_RDONLY);
3183       if (fd == -1)
3184       {
3185          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3186       }
3187       else if (fd != 0)
3188       {
3189          if (dup2(fd, 0) == -1)
3190          {
3191             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3192          }
3193          close(fd);
3194       }
3195       fd = open("/dev/null", O_WRONLY);
3196       if (fd == -1)
3197       {
3198          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3199       }
3200       else if (fd != 1)
3201       {
3202          if (dup2(fd, 1) == -1)
3203          {
3204             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3205          }
3206          close(fd);
3207       }
3208
3209       chdir("/");
3210
3211    } /* -END- if (daemon_mode) */
3212
3213    /*
3214     * As soon as we have written the PID file, we can switch
3215     * to the user and group ID indicated by the --user option
3216     */
3217    write_pid_file();
3218
3219    if (NULL != pw)
3220    {
3221       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3222       {
3223          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3224       }
3225       if (NULL != grp)
3226       {
3227          if (setgroups(1, &grp->gr_gid))
3228          {
3229             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3230          }
3231       }
3232       else if (initgroups(pw->pw_name, pw->pw_gid))
3233       {
3234          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3235       }
3236       if (do_chroot)
3237       {
3238          if (!pw->pw_dir)
3239          {
3240             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3241          }
3242          /* Read the time zone file from /etc before doing chroot. */
3243          tzset();
3244          if (NULL != pre_chroot_nslookup_to_load_resolver
3245              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3246          {
3247             /* Initialize resolver library. */
3248             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3249          }
3250          if (chroot(pw->pw_dir) < 0)
3251          {
3252             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3253          }
3254          if (chdir ("/"))
3255          {
3256             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3257          }
3258       }
3259       if (setuid(pw->pw_uid))
3260       {
3261          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3262       }
3263       if (do_chroot)
3264       {
3265          char putenv_dummy[64];
3266
3267          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3268          if (putenv(putenv_dummy) != 0)
3269          {
3270             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3271          }
3272
3273          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3274          if (putenv(putenv_dummy) != 0)
3275          {
3276             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3277          }
3278       }
3279    }
3280    else if (do_chroot)
3281    {
3282       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3283    }
3284 }
3285 #endif /* defined unix */
3286
3287 #ifdef _WIN32
3288    /* This will be FALSE unless the command line specified --service
3289     */
3290    if (bRunAsService)
3291    {
3292       /* Yup, so now we must attempt to establish a connection
3293        * with the service dispatcher. This will only work if this
3294        * process was launched by the service control manager to
3295        * actually run as a service. If this isn't the case, i've
3296        * known it take around 30 seconds or so for the call to return.
3297        */
3298
3299       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3300       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3301       {
3302          /* Service has run, and at this point is now being stopped, so just return */
3303          return 0;
3304       }
3305
3306 #ifdef _WIN_CONSOLE
3307       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3308 #endif
3309       /* An error occurred. Usually it's because --service was wrongly specified
3310        * and we were unable to connect to the Service Control Dispatcher because
3311        * it wasn't expecting us and is therefore not listening.
3312        *
3313        * For now, just continue below to call the listen_loop function.
3314        */
3315    }
3316 #endif /* def _WIN32 */
3317
3318    listen_loop();
3319
3320    /* NOTREACHED */
3321    return(-1);
3322
3323 }
3324
3325
3326 /*********************************************************************
3327  *
3328  * Function    :  bind_port_helper
3329  *
3330  * Description :  Bind the listen port.  Handles logging, and aborts
3331  *                on failure.
3332  *
3333  * Parameters  :
3334  *          1  :  haddr = Host addres to bind to. Use NULL to bind to
3335  *                        INADDR_ANY.
3336  *          2  :  hport = Specifies port to bind to.
3337  *
3338  * Returns     :  Port that was opened.
3339  *
3340  *********************************************************************/
3341 static jb_socket bind_port_helper(const char *haddr, int hport)
3342 {
3343    int result;
3344    jb_socket bfd;
3345
3346    result = bind_port(haddr, hport, &bfd);
3347
3348    if (result < 0)
3349    {
3350       const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
3351       switch(result)
3352       {
3353          case -3:
3354             log_error(LOG_LEVEL_FATAL,
3355                "can't bind to %s:%d: There may be another Privoxy "
3356                "or some other proxy running on port %d",
3357                bind_address, hport, hport);
3358
3359          case -2:
3360             log_error(LOG_LEVEL_FATAL,
3361                "can't bind to %s:%d: The hostname is not resolvable",
3362                bind_address, hport);
3363
3364          default:
3365             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
3366                bind_address, hport);
3367       }
3368
3369       /* shouldn't get here */
3370       return JB_INVALID_SOCKET;
3371    }
3372
3373    if (haddr == NULL)
3374    {
3375       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
3376          hport);
3377    }
3378    else
3379    {
3380       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
3381          hport, haddr);
3382    }
3383
3384    return bfd;
3385 }
3386
3387
3388 /*********************************************************************
3389  *
3390  * Function    :  bind_ports_helper
3391  *
3392  * Description :  Bind the listen ports.  Handles logging, and aborts
3393  *                on failure.
3394  *
3395  * Parameters  :
3396  *          1  :  config = Privoxy configuration.  Specifies ports
3397  *                         to bind to.
3398  *          2  :  sockets = Preallocated array of opened sockets
3399  *                          corresponding to specification in config.
3400  *                          All non-opened sockets will be set to
3401  *                          JB_INVALID_SOCKET.
3402  *
3403  * Returns     :  Nothing. Inspect sockets argument.
3404  *
3405  *********************************************************************/
3406 static void bind_ports_helper(struct configuration_spec * config,
3407                               jb_socket sockets[])
3408 {
3409    int i;
3410
3411    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3412    {
3413       if (config->hport[i])
3414       {
3415          sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
3416       }
3417       else
3418       {
3419          sockets[i] = JB_INVALID_SOCKET;
3420       }
3421    }
3422    config->need_bind = 0;
3423 }
3424
3425
3426 /*********************************************************************
3427  *
3428  * Function    :  close_ports_helper
3429  *
3430  * Description :  Close listenings ports.
3431  *
3432  * Parameters  :
3433  *          1  :  sockets = Array of opened and non-opened sockets to
3434  *                          close. All sockets will be set to
3435  *                          JB_INVALID_SOCKET.
3436  *
3437  * Returns     :  Nothing.
3438  *
3439  *********************************************************************/
3440 static void close_ports_helper(jb_socket sockets[])
3441 {
3442    int i;
3443
3444    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
3445    {
3446       if (JB_INVALID_SOCKET != sockets[i])
3447       {
3448          close_socket(sockets[i]);
3449       }
3450       sockets[i] = JB_INVALID_SOCKET;
3451    }
3452 }
3453
3454
3455 #ifdef _WIN32
3456 /* Without this simple workaround we get this compiler warning from _beginthread
3457  *     warning C4028: formal parameter 1 different from declaration
3458  */
3459 void w32_service_listen_loop(void *p)
3460 {
3461    listen_loop();
3462 }
3463 #endif /* def _WIN32 */
3464
3465
3466 /*********************************************************************
3467  *
3468  * Function    :  listen_loop
3469  *
3470  * Description :  bind the listen port and enter a "FOREVER" listening loop.
3471  *
3472  * Parameters  :  N/A
3473  *
3474  * Returns     :  Never.
3475  *
3476  *********************************************************************/
3477 static void listen_loop(void)
3478 {
3479    struct client_states *csp_list = NULL;
3480    struct client_state *csp = NULL;
3481    jb_socket bfds[MAX_LISTENING_SOCKETS];
3482    struct configuration_spec *config;
3483    unsigned int active_threads = 0;
3484
3485    config = load_config();
3486
3487 #ifdef FEATURE_CONNECTION_SHARING
3488    /*
3489     * XXX: Should be relocated once it no
3490     * longer needs to emit log messages.
3491     */
3492    initialize_reusable_connections();
3493 #endif /* def FEATURE_CONNECTION_SHARING */
3494
3495    bind_ports_helper(config, bfds);
3496
3497 #ifdef FEATURE_GRACEFUL_TERMINATION
3498    while (!g_terminate)
3499 #else
3500    for (;;)
3501 #endif
3502    {
3503 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
3504       while (waitpid(-1, NULL, WNOHANG) > 0)
3505       {
3506          /* zombie children */
3507       }
3508 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
3509
3510       /*
3511        * Free data that was used by died threads
3512        */
3513       active_threads = sweep();
3514
3515 #if defined(unix)
3516       /*
3517        * Re-open the errlog after HUP signal
3518        */
3519       if (received_hup_signal)
3520       {
3521          if (NULL != config->logfile)
3522          {
3523             init_error_log(Argv[0], config->logfile);
3524          }
3525          received_hup_signal = 0;
3526       }
3527 #endif
3528
3529       csp_list = (struct client_states *)zalloc(sizeof(*csp_list));
3530       if (NULL == csp_list)
3531       {
3532          log_error(LOG_LEVEL_FATAL,
3533             "malloc(%d) for csp_list failed: %E", sizeof(*csp_list));
3534          continue;
3535       }
3536       csp = &csp_list->csp;
3537
3538       log_error(LOG_LEVEL_CONNECT, "Listening for new connections ... ");
3539
3540       if (!accept_connection(csp, bfds))
3541       {
3542          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
3543
3544 #ifdef AMIGA
3545          if (!childs)
3546          {
3547             exit(1);
3548          }
3549 #endif
3550          freez(csp_list);
3551          continue;
3552       }
3553       else
3554       {
3555          log_error(LOG_LEVEL_CONNECT,
3556             "accepted connection from %s on socket %d",
3557             csp->ip_addr_str, csp->cfd);
3558       }
3559
3560       csp->flags |= CSP_FLAG_ACTIVE;
3561       csp->server_connection.sfd = JB_INVALID_SOCKET;
3562
3563       csp->config = config = load_config();
3564
3565       if (config->need_bind)
3566       {
3567          /*
3568           * Since we were listening to the "old port", we will not see
3569           * a "listen" param change until the next request.  So, at
3570           * least 1 more request must be made for us to find the new
3571           * setting.  I am simply closing the old socket and binding the
3572           * new one.
3573           *
3574           * Which-ever is correct, we will serve 1 more page via the
3575           * old settings.  This should probably be a "show-proxy-args"
3576           * request.  This should not be a so common of an operation
3577           * that this will hurt people's feelings.
3578           */
3579
3580          close_ports_helper(bfds);
3581
3582          bind_ports_helper(config, bfds);
3583       }
3584
3585 #ifdef FEATURE_TOGGLE
3586       if (global_toggle_state)
3587 #endif /* def FEATURE_TOGGLE */
3588       {
3589          csp->flags |= CSP_FLAG_TOGGLED_ON;
3590       }
3591
3592       if (run_loader(csp))
3593       {
3594          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
3595          /* Never get here - LOG_LEVEL_FATAL causes program exit */
3596       }
3597
3598 #ifdef FEATURE_ACL
3599       if (block_acl(NULL,csp))
3600       {
3601          log_error(LOG_LEVEL_CONNECT,
3602             "Connection from %s on socket %d dropped due to ACL", csp->ip_addr_str, csp->cfd);
3603          close_socket(csp->cfd);
3604          freez(csp->ip_addr_str);
3605          freez(csp_list);
3606          continue;
3607       }
3608 #endif /* def FEATURE_ACL */
3609
3610       if ((0 != config->max_client_connections)
3611          && (active_threads >= config->max_client_connections))
3612       {
3613          log_error(LOG_LEVEL_CONNECT,
3614             "Rejecting connection from %s. Maximum number of connections reached.",
3615             csp->ip_addr_str);
3616          write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3617             strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3618          close_socket(csp->cfd);
3619          freez(csp->ip_addr_str);
3620          freez(csp_list);
3621          continue;
3622       }
3623
3624       /* add it to the list of clients */
3625       csp_list->next = clients->next;
3626       clients->next = csp_list;
3627
3628       if (config->multi_threaded)
3629       {
3630          int child_id;
3631
3632 /* this is a switch () statement in the C preprocessor - ugh */
3633 #undef SELECTED_ONE_OPTION
3634
3635 /* Use Pthreads in preference to native code */
3636 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
3637 #define SELECTED_ONE_OPTION
3638          {
3639             pthread_t the_thread;
3640             pthread_attr_t attrs;
3641
3642             pthread_attr_init(&attrs);
3643             pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
3644             errno = pthread_create(&the_thread, &attrs,
3645                (void * (*)(void *))serve, csp);
3646             child_id = errno ? -1 : 0;
3647             pthread_attr_destroy(&attrs);
3648          }
3649 #endif
3650
3651 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
3652 #define SELECTED_ONE_OPTION
3653          child_id = _beginthread(
3654             (void (*)(void *))serve,
3655             64 * 1024,
3656             csp);
3657 #endif
3658
3659 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
3660 #define SELECTED_ONE_OPTION
3661          child_id = _beginthread(
3662             (void(* _Optlink)(void*))serve,
3663             NULL,
3664             64 * 1024,
3665             csp);
3666 #endif
3667
3668 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
3669 #define SELECTED_ONE_OPTION
3670          {
3671             thread_id tid = spawn_thread
3672                (server_thread, "server", B_NORMAL_PRIORITY, csp);
3673
3674             if ((tid >= 0) && (resume_thread(tid) == B_OK))
3675             {
3676                child_id = (int) tid;
3677             }
3678             else
3679             {
3680                child_id = -1;
3681             }
3682          }
3683 #endif
3684
3685 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
3686 #define SELECTED_ONE_OPTION
3687          csp->cfd = ReleaseSocket(csp->cfd, -1);
3688
3689 #ifdef __amigaos4__
3690          child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3691                                            NP_Output, Output(),
3692                                            NP_CloseOutput, FALSE,
3693                                            NP_Name, (ULONG)"privoxy child",
3694                                            NP_Child, TRUE,
3695                                            TAG_DONE);
3696 #else
3697          child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
3698                                            NP_Output, Output(),
3699                                            NP_CloseOutput, FALSE,
3700                                            NP_Name, (ULONG)"privoxy child",
3701                                            NP_StackSize, 200*1024,
3702                                            TAG_DONE);
3703 #endif
3704          if (0 != child_id)
3705          {
3706             childs++;
3707             ((struct Task *)child_id)->tc_UserData = csp;
3708             Signal((struct Task *)child_id, SIGF_SINGLE);
3709             Wait(SIGF_SINGLE);
3710          }
3711 #endif
3712
3713 #if !defined(SELECTED_ONE_OPTION)
3714          child_id = fork();
3715
3716          /* This block is only needed when using fork().
3717           * When using threads, the server thread was
3718           * created and run by the call to _beginthread().
3719           */
3720          if (child_id == 0)   /* child */
3721          {
3722             int rc = 0;
3723 #ifdef FEATURE_TOGGLE
3724             int inherited_toggle_state = global_toggle_state;
3725 #endif /* def FEATURE_TOGGLE */
3726
3727             serve(csp);
3728
3729             /*
3730              * If we've been toggled or we've blocked the request, tell Mom
3731              */
3732
3733 #ifdef FEATURE_TOGGLE
3734             if (inherited_toggle_state != global_toggle_state)
3735             {
3736                rc |= RC_FLAG_TOGGLED;
3737             }
3738 #endif /* def FEATURE_TOGGLE */
3739
3740 #ifdef FEATURE_STATISTICS
3741             if (csp->flags & CSP_FLAG_REJECTED)
3742             {
3743                rc |= RC_FLAG_BLOCKED;
3744             }
3745 #endif /* ndef FEATURE_STATISTICS */
3746
3747             _exit(rc);
3748          }
3749          else if (child_id > 0) /* parent */
3750          {
3751             /* in a fork()'d environment, the parent's
3752              * copy of the client socket and the CSP
3753              * are not used.
3754              */
3755             int child_status;
3756 #if !defined(_WIN32) && !defined(__CYGWIN__)
3757
3758             wait(&child_status);
3759
3760             /*
3761              * Evaluate child's return code: If the child has
3762              *  - been toggled, toggle ourselves
3763              *  - blocked its request, bump up the stats counter
3764              */
3765
3766 #ifdef FEATURE_TOGGLE
3767             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
3768             {
3769                global_toggle_state = !global_toggle_state;
3770             }
3771 #endif /* def FEATURE_TOGGLE */
3772
3773 #ifdef FEATURE_STATISTICS
3774             urls_read++;
3775             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
3776             {
3777                urls_rejected++;
3778             }
3779 #endif /* def FEATURE_STATISTICS */
3780
3781 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
3782             close_socket(csp->cfd);
3783             csp->flags &= ~CSP_FLAG_ACTIVE;
3784          }
3785 #endif
3786
3787 #undef SELECTED_ONE_OPTION
3788 /* end of cpp switch () */
3789
3790          if (child_id < 0)
3791          {
3792             /*
3793              * Spawning the child failed, assume it's because
3794              * there are too many children running already.
3795              * XXX: If you assume ...
3796              */
3797             log_error(LOG_LEVEL_ERROR,
3798                "Unable to take any additional connections: %E");
3799             write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
3800                strlen(TOO_MANY_CONNECTIONS_RESPONSE));
3801             close_socket(csp->cfd);
3802             csp->flags &= ~CSP_FLAG_ACTIVE;
3803          }
3804       }
3805       else
3806       {
3807          serve(csp);
3808       }
3809    }
3810
3811    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
3812
3813    /* Clean up.  Aim: free all memory (no leaks) */
3814 #ifdef FEATURE_GRACEFUL_TERMINATION
3815
3816    log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
3817
3818    unload_current_config_file();
3819    unload_current_actions_file();
3820    unload_current_re_filterfile();
3821 #ifdef FEATURE_TRUST
3822    unload_current_trust_file();
3823 #endif
3824
3825    if (config->multi_threaded)
3826    {
3827       int i = 60;
3828       do
3829       {
3830          sleep(1);
3831          sweep();
3832       } while ((clients->next != NULL) && (--i > 0));
3833
3834       if (i <= 0)
3835       {
3836          log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
3837       }
3838    }
3839    sweep();
3840    sweep();
3841
3842 #if defined(unix)
3843    freez(basedir);
3844 #endif
3845
3846 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
3847    /* Cleanup - remove taskbar icon etc. */
3848    TermLogWindow();
3849 #endif
3850
3851    exit(0);
3852 #endif /* FEATURE_GRACEFUL_TERMINATION */
3853
3854 }
3855
3856
3857 /*
3858   Local Variables:
3859   tab-width: 3
3860   end:
3861 */