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