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