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