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