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