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