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