6bcd82e793fa63de846ea78939484f606b6bb238
[privoxy.git] / jcc.c
1 const char jcc_rcs[] = "$Id: jcc.c,v 1.454 2017/05/25 11:14:38 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    const struct forward_spec *fwd;
2704    struct http_request *http;
2705    /* Skeleton for HTTP response, if we should intercept the request */
2706    struct http_response *rsp;
2707
2708    http = csp->http;
2709
2710    if (receive_client_request(csp) != JB_ERR_OK)
2711    {
2712       return;
2713    }
2714    if (parse_client_request(csp) != JB_ERR_OK)
2715    {
2716       return;
2717    }
2718
2719    /* decide how to route the HTTP request */
2720    fwd = forward_url(csp, http);
2721    if (NULL == fwd)
2722    {
2723       log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!?  This can't happen!");
2724       /* Never get here - LOG_LEVEL_FATAL causes program exit */
2725       return;
2726    }
2727
2728    /*
2729     * build the http request to send to the server
2730     * we have to do one of the following:
2731     *
2732     * create = use the original HTTP request to create a new
2733     *          HTTP request that has either the path component
2734     *          without the http://domainspec (w/path) or the
2735     *          full orininal URL (w/url)
2736     *          Note that the path and/or the HTTP version may
2737     *          have been altered by now.
2738     *
2739     * connect = Open a socket to the host:port of the server
2740     *           and short-circuit server and client socket.
2741     *
2742     * pass =  Pass the request unchanged if forwarding a CONNECT
2743     *         request to a parent proxy. Note that we'll be sending
2744     *         the CFAIL message ourselves if connecting to the parent
2745     *         fails, but we won't send a CSUCCEED message if it works,
2746     *         since that would result in a double message (ours and the
2747     *         parent's). After sending the request to the parent, we simply
2748     *         tunnel.
2749     *
2750     * here's the matrix:
2751     *                        SSL
2752     *                    0        1
2753     *                +--------+--------+
2754     *                |        |        |
2755     *             0  | create | connect|
2756     *                | w/path |        |
2757     *  Forwarding    +--------+--------+
2758     *                |        |        |
2759     *             1  | create | pass   |
2760     *                | w/url  |        |
2761     *                +--------+--------+
2762     *
2763     */
2764
2765    if (http->ssl && connect_port_is_forbidden(csp))
2766    {
2767       const char *acceptable_connect_ports =
2768          csp->action->string[ACTION_STRING_LIMIT_CONNECT];
2769       assert(NULL != acceptable_connect_ports);
2770       log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
2771          "limit-connect{%s} doesn't allow CONNECT requests to %s",
2772          csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
2773       csp->action->flags |= ACTION_BLOCK;
2774       http->ssl = 0;
2775    }
2776
2777    if (http->ssl == 0)
2778    {
2779       freez(csp->headers->first->str);
2780       build_request_line(csp, fwd, &csp->headers->first->str);
2781    }
2782
2783    /*
2784     * We have a request. Check if one of the crunchers wants it.
2785     */
2786    if (crunch_response_triggered(csp, crunchers_all))
2787    {
2788       /*
2789        * Yes. The client got the crunch response and we're done here.
2790        */
2791       return;
2792    }
2793
2794    log_applied_actions(csp->action);
2795    log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
2796
2797    if (fwd->forward_host)
2798    {
2799       log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
2800          fwd->forward_host, fwd->forward_port, http->hostport);
2801    }
2802    else
2803    {
2804       log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
2805    }
2806
2807    /* here we connect to the server, gateway, or the forwarder */
2808
2809 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2810    if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
2811       && socket_is_still_alive(csp->server_connection.sfd)
2812       && connection_destination_matches(&csp->server_connection, http, fwd))
2813    {
2814       log_error(LOG_LEVEL_CONNECT,
2815          "Reusing server socket %d connected to %s. Total requests: %u.",
2816          csp->server_connection.sfd, csp->server_connection.host,
2817          csp->server_connection.requests_sent_total);
2818    }
2819    else
2820    {
2821       if (csp->server_connection.sfd != JB_INVALID_SOCKET)
2822       {
2823 #ifdef FEATURE_CONNECTION_SHARING
2824          if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
2825          {
2826             remember_connection(&csp->server_connection);
2827          }
2828          else
2829 #endif /* def FEATURE_CONNECTION_SHARING */
2830          {
2831             log_error(LOG_LEVEL_CONNECT,
2832                "Closing server socket %d connected to %s. Total requests: %u.",
2833                csp->server_connection.sfd, csp->server_connection.host,
2834                csp->server_connection.requests_sent_total);
2835             close_socket(csp->server_connection.sfd);
2836          }
2837          mark_connection_closed(&csp->server_connection);
2838       }
2839 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2840
2841       csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
2842
2843       if (csp->server_connection.sfd == JB_INVALID_SOCKET)
2844       {
2845          if (fwd->type != SOCKS_NONE)
2846          {
2847             /* Socks error. */
2848             rsp = error_response(csp, "forwarding-failed");
2849          }
2850          else if (errno == EINVAL)
2851          {
2852             rsp = error_response(csp, "no-such-domain");
2853          }
2854          else
2855          {
2856             rsp = error_response(csp, "connect-failed");
2857          }
2858
2859          /* Write the answer to the client */
2860          if (rsp != NULL)
2861          {
2862             send_crunch_response(csp, rsp);
2863          }
2864
2865          /*
2866           * Temporary workaround to prevent already-read client
2867           * bodies from being parsed as new requests. For now we
2868           * err on the safe side and throw all the following
2869           * requests under the bus, even if no client body has been
2870           * buffered. A compliant client will repeat the dropped
2871           * requests on an untainted connection.
2872           *
2873           * The proper fix is to discard the no longer needed
2874           * client body in the buffer (if there is one) and to
2875           * continue parsing the bytes that follow.
2876           */
2877          drain_and_close_socket(csp->cfd);
2878          csp->cfd = JB_INVALID_SOCKET;
2879
2880          return;
2881       }
2882 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2883       save_connection_destination(csp->server_connection.sfd,
2884          http, fwd, &csp->server_connection);
2885       csp->server_connection.keep_alive_timeout =
2886          (unsigned)csp->config->keep_alive_timeout;
2887    }
2888 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2889
2890    csp->server_connection.requests_sent_total++;
2891
2892    if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
2893    {
2894       /* Client headers have been sent optimistically */
2895       assert(csp->headers->last == NULL);
2896    }
2897    else if (fwd->forward_host || (http->ssl == 0))
2898    {
2899       if (send_http_request(csp))
2900       {
2901          rsp = error_response(csp, "connect-failed");
2902          if (rsp)
2903          {
2904             send_crunch_response(csp, rsp);
2905          }
2906          return;
2907       }
2908    }
2909    else
2910    {
2911       /*
2912        * We're running an SSL tunnel and we're not forwarding,
2913        * so just ditch the client headers, send the "connect succeeded"
2914        * message to the client, flush the rest, and get out of the way.
2915        */
2916       list_remove_all(csp->headers);
2917       if (write_socket(csp->cfd, CSUCCEED, strlen(CSUCCEED)))
2918       {
2919          return;
2920       }
2921       clear_iob(csp->client_iob);
2922    }
2923
2924    log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
2925
2926    /* XXX: should the time start earlier for optimistically sent data? */
2927    csp->server_connection.request_sent = time(NULL);
2928
2929    handle_established_connection(csp, fwd);
2930 }
2931
2932
2933 #ifdef FUZZ
2934 /*********************************************************************
2935  *
2936  * Function    :  fuzz_server_response
2937  *
2938  * Description :  Treat the input as a whole server response.
2939  *
2940  * Parameters  :
2941  *          1  :  csp = Current client state (buffers, headers, etc...)
2942  *          2  :  fuzz_input_file = File to read the input from.
2943  *
2944  * Returns     :  0
2945  *
2946  *********************************************************************/
2947 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
2948 {
2949    static struct forward_spec fwd; /* Zero'd due to being static */
2950    csp->cfd = 0;
2951
2952    if (strcmp(fuzz_input_file, "-") == 0)
2953    {
2954       /* XXX: Doesn'T work yet. */
2955       csp->server_connection.sfd = 0;
2956    }
2957    else
2958    {
2959       csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
2960       if (csp->server_connection.sfd == -1)
2961       {
2962          log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
2963             fuzz_input_file);
2964       }
2965    }
2966    csp->content_type |= CT_GIF;
2967    csp->action->flags |= ACTION_DEANIMATE;
2968    csp->action->string[ACTION_STRING_DEANIMATE] = "last";
2969
2970    csp->http->path = strdup_or_die("/");
2971    csp->http->host = strdup_or_die("fuzz.example.org");
2972    csp->http->hostport = strdup_or_die("fuzz.example.org:80");
2973    /* Prevent client socket monitoring */
2974    csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
2975    csp->flags |= CSP_FLAG_CHUNKED;
2976
2977    csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
2978    csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2979
2980    csp->content_type |= CT_DECLARED|CT_GIF;
2981
2982    csp->config->socket_timeout = 0;
2983
2984    cgi_init_error_messages();
2985
2986    handle_established_connection(csp, &fwd);
2987
2988    return 0;
2989 }
2990 #endif
2991
2992
2993 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2994 /*********************************************************************
2995  *
2996  * Function    :  prepare_csp_for_next_request
2997  *
2998  * Description :  Put the csp in a mostly vergin state.
2999  *
3000  * Parameters  :
3001  *          1  :  csp = Current client state (buffers, headers, etc...)
3002  *
3003  * Returns     :  N/A
3004  *
3005  *********************************************************************/
3006 static void prepare_csp_for_next_request(struct client_state *csp)
3007 {
3008    csp->content_type = 0;
3009    csp->content_length = 0;
3010    csp->expected_content_length = 0;
3011    csp->expected_client_content_length = 0;
3012    list_remove_all(csp->headers);
3013    clear_iob(csp->iob);
3014    freez(csp->error_message);
3015    free_http_request(csp->http);
3016    destroy_list(csp->headers);
3017    destroy_list(csp->tags);
3018 #ifdef FEATURE_CLIENT_TAGS
3019    destroy_list(csp->client_tags);
3020    freez(csp->client_address);
3021 #endif
3022    free_current_action(csp->action);
3023    if (NULL != csp->fwd)
3024    {
3025       unload_forward_spec(csp->fwd);
3026       csp->fwd = NULL;
3027    }
3028    /* XXX: Store per-connection flags someplace else. */
3029    csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
3030 #ifdef FEATURE_TOGGLE
3031    if (global_toggle_state)
3032 #endif /* def FEATURE_TOGGLE */
3033    {
3034       csp->flags |= CSP_FLAG_TOGGLED_ON;
3035    }
3036
3037    if (csp->client_iob->eod > csp->client_iob->cur)
3038    {
3039       long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
3040       size_t data_length  = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
3041
3042       assert(bytes_to_shift > 0);
3043       assert(data_length > 0);
3044
3045       log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
3046          data_length, bytes_to_shift);
3047       memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
3048       csp->client_iob->cur = csp->client_iob->buf;
3049       assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
3050       csp->client_iob->eod = csp->client_iob->buf + data_length;
3051       memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
3052
3053       csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3054    }
3055    else
3056    {
3057       /*
3058        * We mainly care about resetting client_iob->cur so we don't
3059        * waste buffer space at the beginning and don't mess up the
3060        * request restoration done by cgi_show_request().
3061        *
3062        * Freeing the buffer itself isn't technically necessary,
3063        * but makes debugging more convenient.
3064        */
3065       clear_iob(csp->client_iob);
3066    }
3067 }
3068 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3069
3070
3071 /*********************************************************************
3072  *
3073  * Function    :  serve
3074  *
3075  * Description :  This is little more than chat.  We only "serve" to
3076  *                to close (or remember) any socket that chat may have
3077  *                opened.
3078  *
3079  * Parameters  :
3080  *          1  :  csp = Current client state (buffers, headers, etc...)
3081  *
3082  * Returns     :  N/A
3083  *
3084  *********************************************************************/
3085 #ifdef AMIGA
3086 void serve(struct client_state *csp)
3087 #else /* ifndef AMIGA */
3088 static void serve(struct client_state *csp)
3089 #endif /* def AMIGA */
3090 {
3091    int config_file_change_detected = 0; /* Only used for debugging */
3092 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3093 #ifdef FEATURE_CONNECTION_SHARING
3094    static int monitor_thread_running = 0;
3095 #endif /* def FEATURE_CONNECTION_SHARING */
3096    int continue_chatting = 0;
3097
3098    log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
3099       csp->ip_addr_str, csp->cfd);
3100
3101    do
3102    {
3103       unsigned int latency;
3104
3105       chat(csp);
3106
3107       /*
3108        * If the request has been crunched,
3109        * the calculated latency is zero.
3110        */
3111       latency = (unsigned)(csp->server_connection.response_received -
3112          csp->server_connection.request_sent) / 2;
3113
3114       if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3115          && (csp->flags & CSP_FLAG_CRUNCHED)
3116          && (csp->expected_client_content_length != 0))
3117       {
3118          csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
3119          log_error(LOG_LEVEL_CONNECT,
3120             "Tainting client socket %d due to unread data.", csp->cfd);
3121       }
3122
3123       continue_chatting = (csp->config->feature_flags
3124          & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3125          && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3126          && (csp->cfd != JB_INVALID_SOCKET)
3127          && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3128          && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3129             || (csp->flags & CSP_FLAG_CHUNKED));
3130
3131       if (!(csp->flags & CSP_FLAG_CRUNCHED)
3132          && (csp->server_connection.sfd != JB_INVALID_SOCKET))
3133       {
3134          if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
3135          {
3136             csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
3137          }
3138          if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
3139             || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3140             || !socket_is_still_alive(csp->server_connection.sfd)
3141             || !(latency < csp->server_connection.keep_alive_timeout))
3142          {
3143             log_error(LOG_LEVEL_CONNECT,
3144                "Closing server socket %d connected to %s. "
3145                "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
3146                csp->server_connection.sfd, csp->server_connection.host,
3147                0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3148                0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3149                socket_is_still_alive(csp->server_connection.sfd),
3150                csp->server_connection.keep_alive_timeout);
3151 #ifdef FEATURE_CONNECTION_SHARING
3152             if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3153             {
3154                forget_connection(csp->server_connection.sfd);
3155             }
3156 #endif /* def FEATURE_CONNECTION_SHARING */
3157             close_socket(csp->server_connection.sfd);
3158             mark_connection_closed(&csp->server_connection);
3159          }
3160       }
3161
3162       if (continue_chatting && any_loaded_file_changed(csp))
3163       {
3164          continue_chatting = 0;
3165          config_file_change_detected = 1;
3166       }
3167
3168       if (continue_chatting)
3169       {
3170          if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
3171             && socket_is_still_alive(csp->cfd))
3172          {
3173             log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
3174                "pipelined on socket %d and the socket is still alive.",
3175                csp->requests_received_total+1, csp->cfd);
3176             prepare_csp_for_next_request(csp);
3177             continue;
3178          }
3179
3180          if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3181          {
3182             if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3183             {
3184                log_error(LOG_LEVEL_CONNECT,
3185                   "Waiting for the next client request on socket %d. "
3186                   "Keeping the server socket %d to %s open.",
3187                   csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3188             }
3189             else
3190             {
3191                log_error(LOG_LEVEL_CONNECT,
3192                   "Waiting for the next client request on socket %d. "
3193                   "No server socket to keep open.", csp->cfd);
3194             }
3195          }
3196
3197          if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3198             && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3199             && socket_is_still_alive(csp->cfd))
3200          {
3201             log_error(LOG_LEVEL_CONNECT,
3202                "Client request %u arrived in time on socket %d.",
3203                csp->requests_received_total+1, csp->cfd);
3204             prepare_csp_for_next_request(csp);
3205          }
3206          else
3207          {
3208 #ifdef FEATURE_CONNECTION_SHARING
3209             if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3210                && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3211                && (socket_is_still_alive(csp->server_connection.sfd)))
3212             {
3213                time_t time_open = time(NULL) - csp->server_connection.timestamp;
3214
3215                if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3216                {
3217                   break;
3218                }
3219
3220                remember_connection(&csp->server_connection);
3221                csp->server_connection.sfd = JB_INVALID_SOCKET;
3222                drain_and_close_socket(csp->cfd);
3223                csp->cfd = JB_INVALID_SOCKET;
3224                privoxy_mutex_lock(&connection_reuse_mutex);
3225                if (!monitor_thread_running)
3226                {
3227                   monitor_thread_running = 1;
3228                   privoxy_mutex_unlock(&connection_reuse_mutex);
3229                   wait_for_alive_connections();
3230                   privoxy_mutex_lock(&connection_reuse_mutex);
3231                   monitor_thread_running = 0;
3232                }
3233                privoxy_mutex_unlock(&connection_reuse_mutex);
3234             }
3235 #endif /* def FEATURE_CONNECTION_SHARING */
3236             break;
3237          }
3238       }
3239       else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3240       {
3241          log_error(LOG_LEVEL_CONNECT,
3242             "Closing server socket %d connected to %s. Keep-alive: %u. "
3243             "Tainted: %u. Socket alive: %u. Timeout: %u. "
3244             "Configuration file change detected: %u",
3245             csp->server_connection.sfd, csp->server_connection.host,
3246             0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3247             0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3248             socket_is_still_alive(csp->server_connection.sfd),
3249             csp->server_connection.keep_alive_timeout,
3250             config_file_change_detected);
3251       }
3252    } while (continue_chatting);
3253
3254 #else
3255    chat(csp);
3256 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3257
3258    if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3259    {
3260 #ifdef FEATURE_CONNECTION_SHARING
3261       if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3262       {
3263          forget_connection(csp->server_connection.sfd);
3264       }
3265 #endif /* def FEATURE_CONNECTION_SHARING */
3266       close_socket(csp->server_connection.sfd);
3267    }
3268
3269 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3270    mark_connection_closed(&csp->server_connection);
3271 #endif
3272
3273    if (csp->cfd != JB_INVALID_SOCKET)
3274    {
3275       log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3276          "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3277          "Configuration file change detected: %u. Requests received: %u.",
3278          csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3279          socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3280          config_file_change_detected, csp->requests_received_total);
3281       drain_and_close_socket(csp->cfd);
3282    }
3283
3284    csp->flags &= ~CSP_FLAG_ACTIVE;
3285
3286 }
3287
3288
3289 #ifdef __BEOS__
3290 /*********************************************************************
3291  *
3292  * Function    :  server_thread
3293  *
3294  * Description :  We only exist to call `serve' in a threaded environment.
3295  *
3296  * Parameters  :
3297  *          1  :  data = Current client state (buffers, headers, etc...)
3298  *
3299  * Returns     :  Always 0.
3300  *
3301  *********************************************************************/
3302 static int32 server_thread(void *data)
3303 {
3304    serve((struct client_state *) data);
3305    return 0;
3306
3307 }
3308 #endif
3309
3310
3311 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3312 /*********************************************************************
3313  *
3314  * Function    :  usage
3315  *
3316  * Description :  Print usage info & exit.
3317  *
3318  * Parameters  :  Pointer to argv[0] for identifying ourselves
3319  *
3320  * Returns     :  No. ,-)
3321  *
3322  *********************************************************************/
3323 static void usage(const char *name)
3324 {
3325    printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
3326           "Usage: %s [--config-test] "
3327 #if defined(unix)
3328           "[--chroot] "
3329 #endif /* defined(unix) */
3330           "[--help] "
3331 #if defined(unix)
3332           "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
3333 #endif /* defined(unix) */
3334          "[--version] [configfile]\n",
3335           name);
3336
3337 #ifdef FUZZ
3338    show_fuzz_usage(name);
3339 #endif
3340
3341    printf("Aborting\n");
3342
3343    exit(2);
3344
3345 }
3346 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
3347
3348
3349 #ifdef MUTEX_LOCKS_AVAILABLE
3350 /*********************************************************************
3351  *
3352  * Function    :  privoxy_mutex_lock
3353  *
3354  * Description :  Locks a mutex.
3355  *
3356  * Parameters  :
3357  *          1  :  mutex = The mutex to lock.
3358  *
3359  * Returns     :  Void. May exit in case of errors.
3360  *
3361  *********************************************************************/
3362 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
3363 {
3364 #ifdef FEATURE_PTHREAD
3365    int err = pthread_mutex_lock(mutex);
3366    if (err)
3367    {
3368       if (mutex != &log_mutex)
3369       {
3370          log_error(LOG_LEVEL_FATAL,
3371             "Mutex locking failed: %s.\n", strerror(err));
3372       }
3373       exit(1);
3374    }
3375 #else
3376    EnterCriticalSection(mutex);
3377 #endif /* def FEATURE_PTHREAD */
3378 }
3379
3380
3381 /*********************************************************************
3382  *
3383  * Function    :  privoxy_mutex_unlock
3384  *
3385  * Description :  Unlocks a mutex.
3386  *
3387  * Parameters  :
3388  *          1  :  mutex = The mutex to unlock.
3389  *
3390  * Returns     :  Void. May exit in case of errors.
3391  *
3392  *********************************************************************/
3393 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
3394 {
3395 #ifdef FEATURE_PTHREAD
3396    int err = pthread_mutex_unlock(mutex);
3397    if (err)
3398    {
3399       if (mutex != &log_mutex)
3400       {
3401          log_error(LOG_LEVEL_FATAL,
3402             "Mutex unlocking failed: %s.\n", strerror(err));
3403       }
3404       exit(1);
3405    }
3406 #else
3407    LeaveCriticalSection(mutex);
3408 #endif /* def FEATURE_PTHREAD */
3409 }
3410
3411
3412 /*********************************************************************
3413  *
3414  * Function    :  privoxy_mutex_init
3415  *
3416  * Description :  Prepares a mutex.
3417  *
3418  * Parameters  :
3419  *          1  :  mutex = The mutex to initialize.
3420  *
3421  * Returns     :  Void. May exit in case of errors.
3422  *
3423  *********************************************************************/
3424 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
3425 {
3426 #ifdef FEATURE_PTHREAD
3427    int err = pthread_mutex_init(mutex, 0);
3428    if (err)
3429    {
3430       printf("Fatal error. Mutex initialization failed: %s.\n",
3431          strerror(err));
3432       exit(1);
3433    }
3434 #else
3435    InitializeCriticalSection(mutex);
3436 #endif /* def FEATURE_PTHREAD */
3437 }
3438 #endif /* def MUTEX_LOCKS_AVAILABLE */
3439
3440 /*********************************************************************
3441  *
3442  * Function    :  initialize_mutexes
3443  *
3444  * Description :  Prepares mutexes if mutex support is available.
3445  *
3446  * Parameters  :  None
3447  *
3448  * Returns     :  Void, exits in case of errors.
3449  *
3450  *********************************************************************/
3451 static void initialize_mutexes(void)
3452 {
3453 #ifdef MUTEX_LOCKS_AVAILABLE
3454    /*
3455     * Prepare global mutex semaphores
3456     */
3457    privoxy_mutex_init(&log_mutex);
3458    privoxy_mutex_init(&log_init_mutex);
3459    privoxy_mutex_init(&connection_reuse_mutex);
3460 #ifdef FEATURE_EXTERNAL_FILTERS
3461    privoxy_mutex_init(&external_filter_mutex);
3462 #endif
3463 #ifdef FEATURE_CLIENT_TAGS
3464    privoxy_mutex_init(&client_tags_mutex);
3465 #endif
3466
3467    /*
3468     * XXX: The assumptions below are a bit naive
3469     * and can cause locks that aren't necessary.
3470     *
3471     * For example older FreeBSD versions (< 6.x?)
3472     * have no gethostbyname_r, but gethostbyname is
3473     * thread safe.
3474     */
3475 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
3476    privoxy_mutex_init(&resolver_mutex);
3477 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
3478    /*
3479     * XXX: should we use a single mutex for
3480     * localtime() and gmtime() as well?
3481     */
3482 #ifndef HAVE_GMTIME_R
3483    privoxy_mutex_init(&gmtime_mutex);
3484 #endif /* ndef HAVE_GMTIME_R */
3485
3486 #ifndef HAVE_LOCALTIME_R
3487    privoxy_mutex_init(&localtime_mutex);
3488 #endif /* ndef HAVE_GMTIME_R */
3489
3490 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
3491    privoxy_mutex_init(&rand_mutex);
3492 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
3493
3494 #endif /* def MUTEX_LOCKS_AVAILABLE */
3495 }
3496
3497 /*********************************************************************
3498  *
3499  * Function    :  main
3500  *
3501  * Description :  Load the config file and start the listen loop.
3502  *                This function is a lot more *sane* with the `load_config'
3503  *                and `listen_loop' functions; although it stills does
3504  *                a *little* too much for my taste.
3505  *
3506  * Parameters  :
3507  *          1  :  argc = Number of parameters (including $0).
3508  *          2  :  argv = Array of (char *)'s to the parameters.
3509  *
3510  * Returns     :  1 if : can't open config file, unrecognized directive,
3511  *                stats requested in multi-thread mode, can't open the
3512  *                log file, can't open the jar file, listen port is invalid,
3513  *                any load fails, and can't bind port.
3514  *
3515  *                Else main never returns, the process must be signaled
3516  *                to terminate execution.  Or, on Windows, use the
3517  *                "File", "Exit" menu option.
3518  *
3519  *********************************************************************/
3520 #ifdef __MINGW32__
3521 int real_main(int argc, char **argv)
3522 #else
3523 int main(int argc, char **argv)
3524 #endif
3525 {
3526    int argc_pos = 0;
3527    int do_config_test = 0;
3528 #ifndef HAVE_ARC4RANDOM
3529    unsigned int random_seed;
3530 #endif
3531 #ifdef unix
3532    struct passwd *pw = NULL;
3533    struct group *grp = NULL;
3534    int do_chroot = 0;
3535    char *pre_chroot_nslookup_to_load_resolver = NULL;
3536 #endif
3537 #ifdef FUZZ
3538    char *fuzz_input_type = NULL;
3539    char *fuzz_input_file = NULL;
3540 #endif
3541
3542    Argc = argc;
3543    Argv = argv;
3544
3545    configfile =
3546 #if !defined(_WIN32)
3547    "config"
3548 #else
3549    "config.txt"
3550 #endif
3551       ;
3552
3553    /* Prepare mutexes if supported and necessary. */
3554    initialize_mutexes();
3555
3556    /* Enable logging until further notice. */
3557    init_log_module();
3558
3559    /*
3560     * Parse the command line arguments
3561     *
3562     * XXX: simply printing usage information in case of
3563     * invalid arguments isn't particularly user friendly.
3564     */
3565    while (++argc_pos < argc)
3566    {
3567 #ifdef _WIN32
3568       /* Check to see if the service must be installed or uninstalled */
3569       if (strncmp(argv[argc_pos], "--install", 9) == 0)
3570       {
3571          const char *pName = argv[argc_pos] + 9;
3572          if (*pName == ':')
3573             pName++;
3574          exit((install_service(pName)) ? 0 : 1);
3575       }
3576       else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
3577       {
3578          const char *pName = argv[argc_pos] + 11;
3579          if (*pName == ':')
3580             pName++;
3581          exit((uninstall_service(pName)) ? 0 : 1);
3582       }
3583       else if (strcmp(argv[argc_pos], "--service") == 0)
3584       {
3585          bRunAsService = TRUE;
3586          w32_set_service_cwd();
3587          atexit(w32_service_exit_notify);
3588       }
3589       else
3590 #endif /* defined(_WIN32) */
3591
3592
3593 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
3594
3595       if (strcmp(argv[argc_pos], "--help") == 0)
3596       {
3597          usage(argv[0]);
3598       }
3599
3600       else if (strcmp(argv[argc_pos], "--version") == 0)
3601       {
3602          printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
3603          exit(0);
3604       }
3605
3606 #if defined(unix)
3607
3608       else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
3609       {
3610          set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
3611          daemon_mode = 0;
3612       }
3613
3614       else if (strcmp(argv[argc_pos], "--pidfile") == 0)
3615       {
3616          if (++argc_pos == argc) usage(argv[0]);
3617          pidfile = strdup_or_die(argv[argc_pos]);
3618       }
3619
3620       else if (strcmp(argv[argc_pos], "--user") == 0)
3621       {
3622          char *user_arg;
3623          char *group_name;
3624
3625          if (++argc_pos == argc) usage(argv[argc_pos]);
3626
3627          user_arg = strdup_or_die(argv[argc_pos]);
3628          group_name = strchr(user_arg, '.');
3629          if (NULL != group_name)
3630          {
3631             /* Nul-terminate the user name */
3632             *group_name = '\0';
3633
3634             /* Skip the former delimiter to actually reach the group name */
3635             group_name++;
3636
3637             grp = getgrnam(group_name);
3638             if (NULL == grp)
3639             {
3640                log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
3641             }
3642          }
3643          pw = getpwnam(user_arg);
3644          if (NULL == pw)
3645          {
3646             log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
3647          }
3648
3649          freez(user_arg);
3650       }
3651
3652       else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
3653       {
3654          if (++argc_pos == argc) usage(argv[0]);
3655          pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
3656       }
3657
3658       else if (strcmp(argv[argc_pos], "--chroot") == 0)
3659       {
3660          do_chroot = 1;
3661       }
3662 #endif /* defined(unix) */
3663
3664       else if (strcmp(argv[argc_pos], "--config-test") == 0)
3665       {
3666          do_config_test = 1;
3667       }
3668 #ifdef FUZZ
3669       else if (strcmp(argv[argc_pos], "--fuzz") == 0)
3670       {
3671          argc_pos++;
3672          if (argc < argc_pos + 2) usage(argv[0]);
3673          fuzz_input_type = argv[argc_pos];
3674          argc_pos++;
3675          fuzz_input_file = argv[argc_pos];
3676       }
3677       else if (strcmp(argv[argc_pos], "--stfu") == 0)
3678       {
3679          set_debug_level(LOG_LEVEL_STFU);
3680       }
3681 #endif
3682       else if (argc_pos + 1 != argc)
3683       {
3684          /*
3685           * This is neither the last command line
3686           * option, nor was it recognized before,
3687           * therefore it must be invalid.
3688           */
3689          usage(argv[0]);
3690       }
3691       else
3692
3693 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
3694       {
3695          configfile = argv[argc_pos];
3696       }
3697
3698    } /* -END- while (more arguments) */
3699
3700    show_version(Argv[0]);
3701
3702 #if defined(unix)
3703    if (*configfile != '/')
3704    {
3705       char cwd[BUFFER_SIZE];
3706       char *abs_file;
3707       size_t abs_file_size;
3708
3709       /* make config-filename absolute here */
3710       if (NULL == getcwd(cwd, sizeof(cwd)))
3711       {
3712          perror("failed to get current working directory");
3713          exit(1);
3714       }
3715
3716       basedir = strdup_or_die(cwd);
3717       /* XXX: why + 5? */
3718       abs_file_size = strlen(cwd) + strlen(configfile) + 5;
3719       abs_file = malloc_or_die(abs_file_size);
3720       strlcpy(abs_file, basedir, abs_file_size);
3721       strlcat(abs_file, "/", abs_file_size);
3722       strlcat(abs_file, configfile, abs_file_size);
3723       configfile = abs_file;
3724    }
3725 #endif /* defined unix */
3726
3727
3728    files->next = NULL;
3729    clients->next = NULL;
3730
3731    /* XXX: factor out initialising after the next stable release. */
3732 #ifdef AMIGA
3733    InitAmiga();
3734 #elif defined(_WIN32)
3735    InitWin32();
3736 #endif
3737
3738 #ifndef HAVE_ARC4RANDOM
3739    random_seed = (unsigned int)time(NULL);
3740 #ifdef HAVE_RANDOM
3741    srandom(random_seed);
3742 #else
3743    srand(random_seed);
3744 #endif /* ifdef HAVE_RANDOM */
3745 #endif /* ifndef HAVE_ARC4RANDOM */
3746
3747    /*
3748     * Unix signal handling
3749     *
3750     * Catch the abort, interrupt and terminate signals for a graceful exit
3751     * Catch the hangup signal so the errlog can be reopened.
3752     *
3753     * Ignore the broken pipe signal as connection failures
3754     * are handled when and where they occur without relying
3755     * on a signal.
3756     */
3757 #if !defined(_WIN32) && !defined(__OS2__) && !defined(AMIGA)
3758 {
3759    int idx;
3760    const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
3761
3762    for (idx = 0; idx < SZ(catched_signals); idx++)
3763    {
3764 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
3765       if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
3766 #else
3767       if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
3768 #endif /* ifdef sun */
3769       {
3770          log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
3771       }
3772    }
3773
3774    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
3775    {
3776       log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
3777    }
3778
3779 }
3780 #else /* ifdef _WIN32 */
3781 # ifdef _WIN_CONSOLE
3782    /*
3783     * We *are* in a windows console app.
3784     * Print a verbose messages about FAQ's and such
3785     */
3786    printf("%s", win32_blurb);
3787 # endif /* def _WIN_CONSOLE */
3788 #endif /* def _WIN32 */
3789
3790 #ifdef FUZZ
3791    if (fuzz_input_type != NULL)
3792    {
3793       exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
3794    }
3795 #endif
3796
3797    if (do_config_test)
3798    {
3799       exit(NULL == load_config());
3800    }
3801
3802    /* Initialize the CGI subsystem */
3803    cgi_init_error_messages();
3804
3805    /*
3806     * If running on unix and without the --no-daemon
3807     * option, become a daemon. I.e. fork, detach
3808     * from tty and get process group leadership
3809     */
3810 #if defined(unix)
3811 {
3812    if (daemon_mode)
3813    {
3814       int fd;
3815       pid_t pid = fork();
3816
3817       if (pid < 0) /* error */
3818       {
3819          perror("fork");
3820          exit(3);
3821       }
3822       else if (pid != 0) /* parent */
3823       {
3824          int status;
3825          pid_t wpid;
3826          /*
3827           * must check for errors
3828           * child died due to missing files aso
3829           */
3830          sleep(1);
3831          wpid = waitpid(pid, &status, WNOHANG);
3832          if (wpid != 0)
3833          {
3834             exit(1);
3835          }
3836          exit(0);
3837       }
3838       /* child */
3839
3840       setsid();
3841
3842       /*
3843        * stderr (fd 2) will be closed later on,
3844        * when the config file has been parsed.
3845        */
3846       close(0);
3847       close(1);
3848
3849       /*
3850        * Reserve fd 0 and 1 to prevent abort() and friends
3851        * from sending stuff to the clients or servers.
3852        */
3853       fd = open("/dev/null", O_RDONLY);
3854       if (fd == -1)
3855       {
3856          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3857       }
3858       else if (fd != 0)
3859       {
3860          if (dup2(fd, 0) == -1)
3861          {
3862             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
3863          }
3864          close(fd);
3865       }
3866       fd = open("/dev/null", O_WRONLY);
3867       if (fd == -1)
3868       {
3869          log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
3870       }
3871       else if (fd != 1)
3872       {
3873          if (dup2(fd, 1) == -1)
3874          {
3875             log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
3876          }
3877          close(fd);
3878       }
3879
3880 #ifdef FEATURE_EXTERNAL_FILTERS
3881       for (fd = 0; fd < 3; fd++)
3882       {
3883          mark_socket_for_close_on_execute(fd);
3884       }
3885 #endif
3886
3887       chdir("/");
3888
3889    } /* -END- if (daemon_mode) */
3890
3891    /*
3892     * As soon as we have written the PID file, we can switch
3893     * to the user and group ID indicated by the --user option
3894     */
3895    write_pid_file();
3896
3897    if (NULL != pw)
3898    {
3899       if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
3900       {
3901          log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
3902       }
3903       if (NULL != grp)
3904       {
3905          if (setgroups(1, &grp->gr_gid))
3906          {
3907             log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
3908          }
3909       }
3910       else if (initgroups(pw->pw_name, pw->pw_gid))
3911       {
3912          log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
3913       }
3914       if (do_chroot)
3915       {
3916          if (!pw->pw_dir)
3917          {
3918             log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
3919          }
3920          /* Read the time zone file from /etc before doing chroot. */
3921          tzset();
3922          if (NULL != pre_chroot_nslookup_to_load_resolver
3923              && '\0' != pre_chroot_nslookup_to_load_resolver[0])
3924          {
3925             /* Initialize resolver library. */
3926             (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
3927          }
3928          if (chroot(pw->pw_dir) < 0)
3929          {
3930             log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
3931          }
3932          if (chdir ("/"))
3933          {
3934             log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
3935          }
3936       }
3937       if (setuid(pw->pw_uid))
3938       {
3939          log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
3940       }
3941       if (do_chroot)
3942       {
3943          char putenv_dummy[64];
3944
3945          strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
3946          if (putenv(putenv_dummy) != 0)
3947          {
3948             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
3949          }
3950
3951          snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
3952          if (putenv(putenv_dummy) != 0)
3953          {
3954             log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
3955          }
3956       }
3957    }
3958    else if (do_chroot)
3959    {
3960       log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
3961    }
3962 }
3963 #endif /* defined unix */
3964
3965 #ifdef _WIN32
3966    /* This will be FALSE unless the command line specified --service
3967     */
3968    if (bRunAsService)
3969    {
3970       /* Yup, so now we must attempt to establish a connection
3971        * with the service dispatcher. This will only work if this
3972        * process was launched by the service control manager to
3973        * actually run as a service. If this isn't the case, i've
3974        * known it take around 30 seconds or so for the call to return.
3975        */
3976
3977       /* The StartServiceCtrlDispatcher won't return until the service is stopping */
3978       if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
3979       {
3980          /* Service has run, and at this point is now being stopped, so just return */
3981          return 0;
3982       }
3983
3984 #ifdef _WIN_CONSOLE
3985       printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
3986 #endif
3987       /* An error occurred. Usually it's because --service was wrongly specified
3988        * and we were unable to connect to the Service Control Dispatcher because
3989        * it wasn't expecting us and is therefore not listening.
3990        *
3991        * For now, just continue below to call the listen_loop function.
3992        */
3993    }
3994 #endif /* def _WIN32 */
3995
3996    listen_loop();
3997
3998    /* NOTREACHED */
3999    return(-1);
4000
4001 }
4002
4003
4004 /*********************************************************************
4005  *
4006  * Function    :  bind_port_helper
4007  *
4008  * Description :  Bind the listen port.  Handles logging, and aborts
4009  *                on failure.
4010  *
4011  * Parameters  :
4012  *          1  :  haddr = Host address to bind to. Use NULL to bind to
4013  *                        INADDR_ANY.
4014  *          2  :  hport = Specifies port to bind to.
4015  *
4016  * Returns     :  Port that was opened.
4017  *
4018  *********************************************************************/
4019 static jb_socket bind_port_helper(const char *haddr, int hport)
4020 {
4021    int result;
4022    jb_socket bfd;
4023
4024    result = bind_port(haddr, hport, &bfd);
4025
4026    if (result < 0)
4027    {
4028       const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
4029       switch(result)
4030       {
4031          case -3:
4032             log_error(LOG_LEVEL_FATAL,
4033                "can't bind to %s:%d: There may be another Privoxy "
4034                "or some other proxy running on port %d",
4035                bind_address, hport, hport);
4036
4037          case -2:
4038             log_error(LOG_LEVEL_FATAL,
4039                "can't bind to %s:%d: The hostname is not resolvable",
4040                bind_address, hport);
4041
4042          default:
4043             log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
4044                bind_address, hport);
4045       }
4046
4047       /* shouldn't get here */
4048       return JB_INVALID_SOCKET;
4049    }
4050
4051 #ifndef _WIN32
4052    if (bfd >= FD_SETSIZE)
4053    {
4054       log_error(LOG_LEVEL_FATAL,
4055          "Bind socket number too high to use select(): %d >= %d",
4056          bfd, FD_SETSIZE);
4057    }
4058 #endif
4059
4060    if (haddr == NULL)
4061    {
4062       log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
4063          hport);
4064    }
4065    else
4066    {
4067       log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
4068          hport, haddr);
4069    }
4070
4071    return bfd;
4072 }
4073
4074
4075 /*********************************************************************
4076  *
4077  * Function    :  bind_ports_helper
4078  *
4079  * Description :  Bind the listen ports.  Handles logging, and aborts
4080  *                on failure.
4081  *
4082  * Parameters  :
4083  *          1  :  config = Privoxy configuration.  Specifies ports
4084  *                         to bind to.
4085  *          2  :  sockets = Preallocated array of opened sockets
4086  *                          corresponding to specification in config.
4087  *                          All non-opened sockets will be set to
4088  *                          JB_INVALID_SOCKET.
4089  *
4090  * Returns     :  Nothing. Inspect sockets argument.
4091  *
4092  *********************************************************************/
4093 static void bind_ports_helper(struct configuration_spec * config,
4094                               jb_socket sockets[])
4095 {
4096    int i;
4097
4098    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4099    {
4100       if (config->hport[i])
4101       {
4102          sockets[i] = bind_port_helper(config->haddr[i], config->hport[i]);
4103       }
4104       else
4105       {
4106          sockets[i] = JB_INVALID_SOCKET;
4107       }
4108    }
4109    config->need_bind = 0;
4110 }
4111
4112
4113 /*********************************************************************
4114  *
4115  * Function    :  close_ports_helper
4116  *
4117  * Description :  Close listenings ports.
4118  *
4119  * Parameters  :
4120  *          1  :  sockets = Array of opened and non-opened sockets to
4121  *                          close. All sockets will be set to
4122  *                          JB_INVALID_SOCKET.
4123  *
4124  * Returns     :  Nothing.
4125  *
4126  *********************************************************************/
4127 static void close_ports_helper(jb_socket sockets[])
4128 {
4129    int i;
4130
4131    for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4132    {
4133       if (JB_INVALID_SOCKET != sockets[i])
4134       {
4135          close_socket(sockets[i]);
4136       }
4137       sockets[i] = JB_INVALID_SOCKET;
4138    }
4139 }
4140
4141
4142 #ifdef _WIN32
4143 /* Without this simple workaround we get this compiler warning from _beginthread
4144  *     warning C4028: formal parameter 1 different from declaration
4145  */
4146 void w32_service_listen_loop(void *p)
4147 {
4148    listen_loop();
4149 }
4150 #endif /* def _WIN32 */
4151
4152
4153 /*********************************************************************
4154  *
4155  * Function    :  listen_loop
4156  *
4157  * Description :  bind the listen port and enter a "FOREVER" listening loop.
4158  *
4159  * Parameters  :  N/A
4160  *
4161  * Returns     :  Never.
4162  *
4163  *********************************************************************/
4164 static void listen_loop(void)
4165 {
4166    struct client_states *csp_list = NULL;
4167    struct client_state *csp = NULL;
4168    jb_socket bfds[MAX_LISTENING_SOCKETS];
4169    struct configuration_spec *config;
4170    unsigned int active_threads = 0;
4171
4172    config = load_config();
4173
4174 #ifdef FEATURE_CONNECTION_SHARING
4175    /*
4176     * XXX: Should be relocated once it no
4177     * longer needs to emit log messages.
4178     */
4179    initialize_reusable_connections();
4180 #endif /* def FEATURE_CONNECTION_SHARING */
4181
4182    bind_ports_helper(config, bfds);
4183
4184 #ifdef FEATURE_GRACEFUL_TERMINATION
4185    while (!g_terminate)
4186 #else
4187    for (;;)
4188 #endif
4189    {
4190 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) && !defined(__OS2__)
4191       while (waitpid(-1, NULL, WNOHANG) > 0)
4192       {
4193          /* zombie children */
4194       }
4195 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(AMIGA) */
4196
4197       /*
4198        * Free data that was used by died threads
4199        */
4200       active_threads = sweep();
4201
4202 #if defined(unix)
4203       /*
4204        * Re-open the errlog after HUP signal
4205        */
4206       if (received_hup_signal)
4207       {
4208          if (NULL != config->logfile)
4209          {
4210             init_error_log(Argv[0], config->logfile);
4211          }
4212          received_hup_signal = 0;
4213       }
4214 #endif
4215
4216       csp_list = zalloc_or_die(sizeof(*csp_list));
4217       csp = &csp_list->csp;
4218
4219       log_error(LOG_LEVEL_CONNECT,
4220          "Waiting for the next client connection. Currently active threads: %d",
4221          active_threads);
4222
4223       /*
4224        * This config may be outdated, but for accept_connection()
4225        * it's fresh enough.
4226        */
4227       csp->config = config;
4228
4229       if (!accept_connection(csp, bfds))
4230       {
4231          log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4232
4233 #ifdef AMIGA
4234          if (!childs)
4235          {
4236             exit(1);
4237          }
4238 #endif
4239          freez(csp_list);
4240          continue;
4241       }
4242
4243       csp->flags |= CSP_FLAG_ACTIVE;
4244       csp->server_connection.sfd = JB_INVALID_SOCKET;
4245
4246       csp->config = config = load_config();
4247
4248       if (config->need_bind)
4249       {
4250          /*
4251           * Since we were listening to the "old port", we will not see
4252           * a "listen" param change until the next request.  So, at
4253           * least 1 more request must be made for us to find the new
4254           * setting.  I am simply closing the old socket and binding the
4255           * new one.
4256           *
4257           * Which-ever is correct, we will serve 1 more page via the
4258           * old settings.  This should probably be a "show-proxy-args"
4259           * request.  This should not be a so common of an operation
4260           * that this will hurt people's feelings.
4261           */
4262
4263          close_ports_helper(bfds);
4264
4265          bind_ports_helper(config, bfds);
4266       }
4267
4268 #ifdef FEATURE_TOGGLE
4269       if (global_toggle_state)
4270 #endif /* def FEATURE_TOGGLE */
4271       {
4272          csp->flags |= CSP_FLAG_TOGGLED_ON;
4273       }
4274
4275       if (run_loader(csp))
4276       {
4277          log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
4278          /* Never get here - LOG_LEVEL_FATAL causes program exit */
4279       }
4280
4281 #ifdef FEATURE_ACL
4282       if (block_acl(NULL,csp))
4283       {
4284          log_error(LOG_LEVEL_CONNECT,
4285             "Connection from %s on %s (socket %d) dropped due to ACL",
4286             csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
4287          close_socket(csp->cfd);
4288          freez(csp->ip_addr_str);
4289          freez(csp->listen_addr_str);
4290          freez(csp_list);
4291          continue;
4292       }
4293 #endif /* def FEATURE_ACL */
4294
4295       if ((0 != config->max_client_connections)
4296          && (active_threads >= config->max_client_connections))
4297       {
4298          log_error(LOG_LEVEL_CONNECT,
4299             "Rejecting connection from %s. Maximum number of connections reached.",
4300             csp->ip_addr_str);
4301          write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4302             strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4303          close_socket(csp->cfd);
4304          freez(csp->ip_addr_str);
4305          freez(csp->listen_addr_str);
4306          freez(csp_list);
4307          continue;
4308       }
4309
4310       /* add it to the list of clients */
4311       csp_list->next = clients->next;
4312       clients->next = csp_list;
4313
4314       if (config->multi_threaded)
4315       {
4316          int child_id;
4317
4318 /* this is a switch () statement in the C preprocessor - ugh */
4319 #undef SELECTED_ONE_OPTION
4320
4321 /* Use Pthreads in preference to native code */
4322 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
4323 #define SELECTED_ONE_OPTION
4324          {
4325             pthread_t the_thread;
4326             pthread_attr_t attrs;
4327
4328             pthread_attr_init(&attrs);
4329             pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4330             errno = pthread_create(&the_thread, &attrs,
4331                (void * (*)(void *))serve, csp);
4332             child_id = errno ? -1 : 0;
4333             pthread_attr_destroy(&attrs);
4334          }
4335 #endif
4336
4337 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
4338 #define SELECTED_ONE_OPTION
4339          child_id = _beginthread(
4340             (void (*)(void *))serve,
4341             64 * 1024,
4342             csp);
4343 #endif
4344
4345 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
4346 #define SELECTED_ONE_OPTION
4347          child_id = _beginthread(
4348             (void(* _Optlink)(void*))serve,
4349             NULL,
4350             64 * 1024,
4351             csp);
4352 #endif
4353
4354 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
4355 #define SELECTED_ONE_OPTION
4356          {
4357             thread_id tid = spawn_thread
4358                (server_thread, "server", B_NORMAL_PRIORITY, csp);
4359
4360             if ((tid >= 0) && (resume_thread(tid) == B_OK))
4361             {
4362                child_id = (int) tid;
4363             }
4364             else
4365             {
4366                child_id = -1;
4367             }
4368          }
4369 #endif
4370
4371 #if defined(AMIGA) && !defined(SELECTED_ONE_OPTION)
4372 #define SELECTED_ONE_OPTION
4373          csp->cfd = ReleaseSocket(csp->cfd, -1);
4374
4375 #ifdef __amigaos4__
4376          child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4377                                            NP_Output, Output(),
4378                                            NP_CloseOutput, FALSE,
4379                                            NP_Name, (ULONG)"privoxy child",
4380                                            NP_Child, TRUE,
4381                                            TAG_DONE);
4382 #else
4383          child_id = (int)CreateNewProcTags(NP_Entry, (ULONG)server_thread,
4384                                            NP_Output, Output(),
4385                                            NP_CloseOutput, FALSE,
4386                                            NP_Name, (ULONG)"privoxy child",
4387                                            NP_StackSize, 200*1024,
4388                                            TAG_DONE);
4389 #endif
4390          if (0 != child_id)
4391          {
4392             childs++;
4393             ((struct Task *)child_id)->tc_UserData = csp;
4394             Signal((struct Task *)child_id, SIGF_SINGLE);
4395             Wait(SIGF_SINGLE);
4396          }
4397 #endif
4398
4399 #if !defined(SELECTED_ONE_OPTION)
4400          child_id = fork();
4401
4402          /* This block is only needed when using fork().
4403           * When using threads, the server thread was
4404           * created and run by the call to _beginthread().
4405           */
4406          if (child_id == 0)   /* child */
4407          {
4408             int rc = 0;
4409 #ifdef FEATURE_TOGGLE
4410             int inherited_toggle_state = global_toggle_state;
4411 #endif /* def FEATURE_TOGGLE */
4412
4413             serve(csp);
4414
4415             /*
4416              * If we've been toggled or we've blocked the request, tell Mom
4417              */
4418
4419 #ifdef FEATURE_TOGGLE
4420             if (inherited_toggle_state != global_toggle_state)
4421             {
4422                rc |= RC_FLAG_TOGGLED;
4423             }
4424 #endif /* def FEATURE_TOGGLE */
4425
4426 #ifdef FEATURE_STATISTICS
4427             if (csp->flags & CSP_FLAG_REJECTED)
4428             {
4429                rc |= RC_FLAG_BLOCKED;
4430             }
4431 #endif /* ndef FEATURE_STATISTICS */
4432
4433             _exit(rc);
4434          }
4435          else if (child_id > 0) /* parent */
4436          {
4437             /* in a fork()'d environment, the parent's
4438              * copy of the client socket and the CSP
4439              * are not used.
4440              */
4441             int child_status;
4442 #if !defined(_WIN32) && !defined(__CYGWIN__)
4443
4444             wait(&child_status);
4445
4446             /*
4447              * Evaluate child's return code: If the child has
4448              *  - been toggled, toggle ourselves
4449              *  - blocked its request, bump up the stats counter
4450              */
4451
4452 #ifdef FEATURE_TOGGLE
4453             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
4454             {
4455                global_toggle_state = !global_toggle_state;
4456             }
4457 #endif /* def FEATURE_TOGGLE */
4458
4459 #ifdef FEATURE_STATISTICS
4460             urls_read++;
4461             if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
4462             {
4463                urls_rejected++;
4464             }
4465 #endif /* def FEATURE_STATISTICS */
4466
4467 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
4468             close_socket(csp->cfd);
4469             csp->flags &= ~CSP_FLAG_ACTIVE;
4470          }
4471 #endif
4472
4473 #undef SELECTED_ONE_OPTION
4474 /* end of cpp switch () */
4475
4476          if (child_id < 0)
4477          {
4478             /*
4479              * Spawning the child failed, assume it's because
4480              * there are too many children running already.
4481              * XXX: If you assume ...
4482              */
4483             log_error(LOG_LEVEL_ERROR,
4484                "Unable to take any additional connections: %E. Active threads: %d",
4485                active_threads);
4486             write_socket(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
4487                strlen(TOO_MANY_CONNECTIONS_RESPONSE));
4488             close_socket(csp->cfd);
4489             csp->flags &= ~CSP_FLAG_ACTIVE;
4490          }
4491       }
4492       else
4493       {
4494          serve(csp);
4495       }
4496    }
4497
4498    /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
4499
4500    /* Clean up.  Aim: free all memory (no leaks) */
4501 #ifdef FEATURE_GRACEFUL_TERMINATION
4502
4503    log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
4504
4505    unload_current_config_file();
4506    unload_current_actions_file();
4507    unload_current_re_filterfile();
4508 #ifdef FEATURE_TRUST
4509    unload_current_trust_file();
4510 #endif
4511
4512    if (config->multi_threaded)
4513    {
4514       int i = 60;
4515       do
4516       {
4517          sleep(1);
4518          sweep();
4519       } while ((clients->next != NULL) && (--i > 0));
4520
4521       if (i <= 0)
4522       {
4523          log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
4524       }
4525    }
4526    sweep();
4527    sweep();
4528
4529 #if defined(unix)
4530    freez(basedir);
4531 #endif
4532
4533 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
4534    /* Cleanup - remove taskbar icon etc. */
4535    TermLogWindow();
4536 #endif
4537
4538    exit(0);
4539 #endif /* FEATURE_GRACEFUL_TERMINATION */
4540
4541 }
4542
4543
4544 /*
4545   Local Variables:
4546   tab-width: 3
4547   end:
4548 */