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