1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
5 * Purpose : Main file. Contains main() method, main loop, and
6 * the main connection-handling function.
8 * Copyright : Written by and Copyright (C) 2001-2021 the
9 * Privoxy team. https://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
66 # include <sys/wait.h>
67 # include <sys/time.h>
68 # include <sys/stat.h>
69 # include <sys/ioctl.h>
72 #include <sys/termios.h>
83 # include <socket.h> /* BeOS has select() for sockets only. */
84 # include <OS.h> /* declarations for threads and stuff. */
92 #endif /* def __GLIBC__ */
97 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
98 #endif /* HAVE_POLL */
105 #ifdef FEATURE_HTTPS_INSPECTION
111 #include "miscutil.h"
113 #include "jbsockets.h"
118 #include "urlmatch.h"
119 #ifdef FEATURE_CLIENT_TAGS
120 #include "client-tags.h"
124 struct client_states clients[1];
125 struct file_list files[1];
127 #ifdef FEATURE_STATISTICS
128 int urls_read = 0; /* total nr of urls read inc rejected */
129 int urls_rejected = 0; /* total nr of urls rejected */
130 #endif /* def FEATURE_STATISTICS */
132 #ifdef FEATURE_GRACEFUL_TERMINATION
137 static void sig_handler(int the_signal);
139 static int client_protocol_is_unsupported(struct client_state *csp, char *req);
140 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
141 static jb_err get_server_headers(struct client_state *csp);
142 static const char *crunch_reason(const struct http_response *rsp);
143 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
144 static char *get_request_line(struct client_state *csp);
145 static jb_err receive_client_request(struct client_state *csp);
146 static jb_err parse_client_request(struct client_state *csp);
147 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
148 static jb_err change_request_destination(struct client_state *csp);
149 static void handle_established_connection(struct client_state *csp);
150 static void chat(struct client_state *csp);
151 static void serve(struct client_state *csp);
152 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
153 static void usage(const char *myname);
155 static void initialize_mutexes(void);
156 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
157 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
158 static void close_ports_helper(jb_socket sockets[]);
159 static void listen_loop(void);
160 static void serve(struct client_state *csp);
163 static int32 server_thread(void *data);
164 #endif /* def __BEOS__ */
167 #define sleep(N) Sleep(((N) * 1000))
171 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
172 void show_fuzz_usage(const char *name);
175 #ifdef MUTEX_LOCKS_AVAILABLE
177 * XXX: Does the locking stuff really belong in this file?
179 privoxy_mutex_t log_mutex;
180 privoxy_mutex_t log_init_mutex;
181 privoxy_mutex_t connection_reuse_mutex;
183 #ifdef FEATURE_HTTPS_INSPECTION
184 privoxy_mutex_t certificate_mutex;
185 privoxy_mutex_t ssl_init_mutex;
188 #ifdef FEATURE_EXTERNAL_FILTERS
189 privoxy_mutex_t external_filter_mutex;
191 #ifdef FEATURE_CLIENT_TAGS
192 privoxy_mutex_t client_tags_mutex;
194 #ifdef FEATURE_EXTENDED_STATISTICS
195 privoxy_mutex_t filter_statistics_mutex;
196 privoxy_mutex_t block_statistics_mutex;
199 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
200 privoxy_mutex_t resolver_mutex;
201 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
203 #ifndef HAVE_GMTIME_R
204 privoxy_mutex_t gmtime_mutex;
205 #endif /* ndef HAVE_GMTIME_R */
207 #ifndef HAVE_LOCALTIME_R
208 privoxy_mutex_t localtime_mutex;
209 #endif /* ndef HAVE_GMTIME_R */
211 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
212 privoxy_mutex_t rand_mutex;
213 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
215 #endif /* def MUTEX_LOCKS_AVAILABLE */
218 const char *basedir = NULL;
219 const char *pidfile = NULL;
220 static int received_hup_signal = 0;
221 #endif /* defined unix */
223 /* HTTP snipplets. */
224 static const char CSUCCEED[] =
225 "HTTP/1.1 200 Connection established\r\n\r\n";
227 static const char CHEADER[] =
228 "HTTP/1.1 400 Invalid header received from client\r\n"
229 "Content-Type: text/plain\r\n"
230 "Connection: close\r\n\r\n"
231 "Invalid header received from client.\r\n";
233 static const char FTP_RESPONSE[] =
234 "HTTP/1.1 400 Invalid request received from client\r\n"
235 "Content-Type: text/plain\r\n"
236 "Connection: close\r\n\r\n"
237 "Invalid request. Privoxy doesn't support FTP.\r\n";
239 static const char GOPHER_RESPONSE[] =
240 "HTTP/1.1 400 Invalid request received from client\r\n"
241 "Content-Type: text/plain\r\n"
242 "Connection: close\r\n\r\n"
243 "Invalid request. Privoxy doesn't support gopher.\r\n";
245 /* XXX: should be a template */
246 static const char MISSING_DESTINATION_RESPONSE[] =
247 "HTTP/1.1 400 Bad request received from client\r\n"
248 "Content-Type: text/plain\r\n"
249 "Connection: close\r\n\r\n"
250 "Bad request. Privoxy was unable to extract the destination.\r\n";
252 /* XXX: should be a template */
253 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
254 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
255 "Content-Type: text/plain\r\n"
256 "Connection: close\r\n\r\n"
257 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
259 /* XXX: should be a template */
260 static const char MESSED_UP_REQUEST_RESPONSE[] =
261 "HTTP/1.1 400 Malformed request after rewriting\r\n"
262 "Content-Type: text/plain\r\n"
263 "Connection: close\r\n\r\n"
264 "Bad request. Messed up with header filters.\r\n";
266 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
267 "HTTP/1.1 503 Too many open connections\r\n"
268 "Content-Type: text/plain\r\n"
269 "Connection: close\r\n\r\n"
270 "Maximum number of open connections reached.\r\n";
272 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
273 "HTTP/1.1 504 Connection timeout\r\n"
274 "Content-Type: text/plain\r\n"
275 "Connection: close\r\n\r\n"
276 "The connection timed out because the client request didn't arrive in time.\r\n";
278 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
279 "HTTP/1.1 400 Failed reading client body\r\n"
280 "Content-Type: text/plain\r\n"
281 "Connection: close\r\n\r\n"
282 "Failed parsing or buffering the chunk-encoded client body.\r\n";
284 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
285 "HTTP/1.1 417 Expecting too much\r\n"
286 "Content-Type: text/plain\r\n"
287 "Connection: close\r\n\r\n"
288 "Privoxy detected an unsupported Expect header value.\r\n";
290 /* A function to crunch a response */
291 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
293 /* Crunch function flags */
294 #define CF_NO_FLAGS 0
295 /* Cruncher applies to forced requests as well */
296 #define CF_IGNORE_FORCE 1
297 /* Crunched requests are counted for the block statistics */
298 #define CF_COUNT_AS_REJECT 2
300 /* A crunch function and its flags */
303 const crunch_func_ptr cruncher;
307 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
309 /* Complete list of cruncher functions */
310 static const struct cruncher crunchers_all[] = {
311 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
312 { block_url, CF_COUNT_AS_REJECT },
314 { trust_url, CF_COUNT_AS_REJECT },
315 #endif /* def FEATURE_TRUST */
316 { redirect_url, CF_NO_FLAGS },
317 { dispatch_cgi, CF_IGNORE_FORCE},
321 /* Light version, used after tags are applied */
322 static const struct cruncher crunchers_light[] = {
323 { block_url, CF_COUNT_AS_REJECT },
324 { redirect_url, CF_NO_FLAGS },
330 * XXX: Don't we really mean
337 /*********************************************************************
339 * Function : sig_handler
341 * Description : Signal handler for different signals.
342 * Exit gracefully on TERM and INT
343 * or set a flag that will cause the errlog
344 * to be reopened by the main thread on HUP.
347 * 1 : the_signal = the signal cause this function to call
351 *********************************************************************/
352 static void sig_handler(int the_signal)
358 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
370 received_hup_signal = 1;
376 * We shouldn't be here, unless we catch signals
377 * in main() that we can't handle here!
379 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
387 /*********************************************************************
389 * Function : get_write_delay
391 * Description : Parse the delay-response parameter.
394 * 1 : csp = Current client state (buffers, headers, etc...)
396 * Returns : Number of milliseconds to delay writes.
398 *********************************************************************/
399 static unsigned int get_write_delay(const struct client_state *csp)
405 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
409 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
411 delay = (unsigned)strtol(newval, &endptr, 0);
414 log_error(LOG_LEVEL_FATAL,
415 "Invalid delay-response{} parameter: '%s'", newval);
423 /*********************************************************************
425 * Function : client_protocol_is_unsupported
427 * Description : Checks if the client used a known unsupported
428 * protocol and deals with it by sending an error
432 * 1 : csp = Current client state (buffers, headers, etc...)
433 * 2 : req = the first request line send by the client
435 * Returns : TRUE if an error response has been generated, or
436 * FALSE if the request doesn't look invalid.
438 *********************************************************************/
439 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
442 * If it's a FTP or gopher request, we don't support it.
444 * These checks are better than nothing, but they might
445 * not work in all configurations and some clients might
446 * have problems digesting the answer.
448 * They should, however, never cause more problems than
449 * Privoxy's old behaviour (returning the misleading HTML
452 * "Could not resolve http://(ftp|gopher)://example.org").
454 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
456 const char *response = NULL;
457 const char *protocol = NULL;
459 if (!strncmpic(req, "GET ftp://", 10))
461 response = FTP_RESPONSE;
466 response = GOPHER_RESPONSE;
469 log_error(LOG_LEVEL_ERROR,
470 "%s tried to use Privoxy as %s proxy: %s",
471 csp->ip_addr_str, protocol, req);
472 log_error(LOG_LEVEL_CLF,
473 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
476 #ifdef FEATURE_HTTPS_INSPECTION
477 if (client_use_ssl(csp))
479 ssl_send_data_delayed(&(csp->ssl_client_attr),
480 (const unsigned char *)response, strlen(response),
481 get_write_delay(csp));
486 write_socket_delayed(csp->cfd, response, strlen(response),
487 get_write_delay(csp));
497 /*********************************************************************
499 * Function : client_has_unsupported_expectations
501 * Description : Checks if the client used an unsupported expectation
502 * in which case an error message is delivered.
505 * 1 : csp = Current client state (buffers, headers, etc...)
507 * Returns : TRUE if an error response has been generated, or
508 * FALSE if the request doesn't look invalid.
510 *********************************************************************/
511 static int client_has_unsupported_expectations(const struct client_state *csp)
513 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
515 log_error(LOG_LEVEL_ERROR,
516 "Rejecting request from client %s with unsupported Expect header value",
518 log_error(LOG_LEVEL_CLF,
519 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
520 write_socket_delayed(csp->cfd,
521 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
522 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
523 get_write_delay(csp));
533 /*********************************************************************
535 * Function : get_request_destination_elsewhere
537 * Description : If the client's request was redirected into
538 * Privoxy without the client's knowledge,
539 * the request line lacks the destination host.
541 * This function tries to get it elsewhere,
542 * provided accept-intercepted-requests is enabled.
544 * "Elsewhere" currently only means "Host: header",
545 * but in the future we may ask the redirecting
546 * packet filter to look the destination up.
548 * If the destination stays unknown, an error
549 * response is send to the client and headers
550 * are freed so that chat() can return directly.
553 * 1 : csp = Current client state (buffers, headers, etc...)
554 * 2 : headers = a header list
556 * Returns : JB_ERR_OK if the destination is now known, or
557 * JB_ERR_PARSE if it isn't.
559 *********************************************************************/
560 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
562 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
564 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
565 " Privoxy isn't configured to accept intercepted requests.",
566 csp->ip_addr_str, csp->http->cmd);
567 /* XXX: Use correct size */
568 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
569 csp->ip_addr_str, csp->http->cmd);
571 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
572 get_write_delay(csp));
573 destroy_list(headers);
577 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
579 /* Split the domain we just got for pattern matching */
580 init_domain_components(csp->http);
586 /* We can't work without destination. Go spread the news.*/
588 /* XXX: Use correct size */
589 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
590 csp->ip_addr_str, csp->http->cmd);
591 log_error(LOG_LEVEL_ERROR,
592 "Privoxy was unable to get the destination for %s's request: %s",
593 csp->ip_addr_str, csp->http->cmd);
595 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
596 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
597 destroy_list(headers);
602 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
603 * to get the destination IP address, use it as host directly
604 * or do a reverse DNS lookup first.
609 /*********************************************************************
611 * Function : get_server_headers
613 * Description : Parses server headers in iob and fills them
614 * into csp->headers so that they can later be
618 * 1 : csp = Current client state (buffers, headers, etc...)
620 * Returns : JB_ERR_OK if everything went fine, or
621 * JB_ERR_PARSE if the headers were incomplete.
623 *********************************************************************/
624 static jb_err get_server_headers(struct client_state *csp)
626 int continue_hack_in_da_house = 0;
629 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
634 * continue hack in da house. Ignore the ending of
635 * this head and continue enlisting header lines.
636 * The reason is described below.
638 enlist(csp->headers, "");
639 continue_hack_in_da_house = 0;
642 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
645 * It's a bodyless continue response, don't
646 * stop header parsing after reaching its end.
648 * As a result Privoxy will concatenate the
649 * next response's head and parse and deliver
650 * the headers as if they belonged to one request.
652 * The client will separate them because of the
653 * empty line between them.
655 * XXX: What we're doing here is clearly against
656 * the intended purpose of the continue header,
657 * and under some conditions (HTTP/1.0 client request)
658 * it's a standard violation.
660 * Anyway, "sort of against the spec" is preferable
661 * to "always getting confused by Continue responses"
662 * (Privoxy's behaviour before this hack was added)
664 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
665 continue_hack_in_da_house = 1;
667 else if (*header == '\0')
670 * If the header is empty, but the Continue hack
671 * isn't active, we can assume that we reached the
672 * end of the buffer before we hit the end of the
675 * Inform the caller an let it decide how to handle it.
680 if (JB_ERR_MEMORY == enlist(csp->headers, header))
683 * XXX: Should we quit the request and return a
684 * out of memory error page instead?
686 log_error(LOG_LEVEL_ERROR,
687 "Out of memory while enlisting server headers. %s lost.",
697 /*********************************************************************
699 * Function : crunch_reason
701 * Description : Translates the crunch reason code into a string.
704 * 1 : rsp = a http_response
706 * Returns : A string with the crunch reason or an error description.
708 *********************************************************************/
709 static const char *crunch_reason(const struct http_response *rsp)
711 char * reason = NULL;
716 return "Internal error while searching for crunch reason";
719 switch (rsp->crunch_reason)
722 reason = "Unsupported HTTP feature";
728 reason = "Untrusted";
731 reason = "Redirected";
737 reason = "DNS failure";
739 case FORWARDING_FAILED:
740 reason = "Forwarding failed";
743 reason = "Connection failure";
746 reason = "Out of memory (may mask other reasons)";
748 case CONNECTION_TIMEOUT:
749 reason = "Connection timeout";
752 reason = "No server data received";
755 reason = "No reason recorded";
763 /*********************************************************************
765 * Function : log_applied_actions
767 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
771 * 1 : actions = Current action spec to log
775 *********************************************************************/
776 static void log_applied_actions(const struct current_action_spec *actions)
779 * The conversion to text requires lots of memory allocations so
780 * we only do the conversion if the user is actually interested.
782 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
784 char *actions_as_text = actions_to_line_of_text(actions);
785 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
786 freez(actions_as_text);
791 /*********************************************************************
793 * Function : send_crunch_response
795 * Description : Delivers already prepared response for
796 * intercepted requests, logs the interception
797 * and frees the response.
800 * 1 : csp = Current client state (buffers, headers, etc...)
801 * 2 : rsp = Fully prepared response. Will be freed on exit.
805 *********************************************************************/
806 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
808 const struct http_request *http = csp->http;
812 assert(rsp->head != NULL);
816 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
820 * Extract the status code from the actual head
821 * that will be send to the client. It is the only
822 * way to get it right for all requests, including
823 * the fixed ones for out-of-memory problems.
825 * A head starts like this: 'HTTP/1.1 200...'
829 status_code[0] = rsp->head[9];
830 status_code[1] = rsp->head[10];
831 status_code[2] = rsp->head[11];
832 status_code[3] = '\0';
834 /* Log that the request was crunched and why. */
835 log_applied_actions(csp->action);
836 #ifdef FEATURE_HTTPS_INSPECTION
837 if (client_use_ssl(csp))
839 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
840 http->hostport, http->path);
841 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
842 csp->ip_addr_str, http->gpc, http->hostport, http->path,
843 http->version, status_code, rsp->content_length);
848 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
849 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
850 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
852 /* Write the answer to the client */
853 #ifdef FEATURE_HTTPS_INSPECTION
854 if (client_use_ssl(csp))
856 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
857 (const unsigned char *)rsp->head, rsp->head_length,
858 get_write_delay(csp)) < 0)
859 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
860 (const unsigned char *)rsp->body, rsp->content_length,
861 get_write_delay(csp)) < 0))
863 /* There is nothing we can do about it. */
864 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
865 "for https://%s%s through client socket %d using TLS/SSL",
866 http->hostport, http->url, csp->cfd);
872 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
873 get_write_delay(csp))
874 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
875 get_write_delay(csp)))
877 /* There is nothing we can do about it. */
878 log_error(LOG_LEVEL_CONNECT,
879 "Couldn't deliver the error message for %s through client socket %d: %E",
880 http->url, csp->cfd);
884 /* Clean up and return */
885 if (cgi_error_memory() != rsp)
887 free_http_response(rsp);
893 /*********************************************************************
895 * Function : crunch_response_triggered
897 * Description : Checks if the request has to be crunched,
898 * and delivers the crunch response if necessary.
901 * 1 : csp = Current client state (buffers, headers, etc...)
902 * 2 : crunchers = list of cruncher functions to run
904 * Returns : TRUE if the request was answered with a crunch response
907 *********************************************************************/
908 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
910 struct http_response *rsp = NULL;
911 const struct cruncher *c;
914 * If CGI request crunching is disabled,
915 * check the CGI dispatcher out of order to
916 * prevent unintentional blocks or redirects.
918 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
919 && (NULL != (rsp = dispatch_cgi(csp))))
921 /* Deliver, log and free the interception response. */
922 send_crunch_response(csp, rsp);
923 csp->flags |= CSP_FLAG_CRUNCHED;
927 for (c = crunchers; c->cruncher != NULL; c++)
930 * Check the cruncher if either Privoxy is toggled
931 * on and the request isn't forced, or if the cruncher
932 * applies to forced requests as well.
934 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
935 !(csp->flags & CSP_FLAG_FORCED)) ||
936 (c->flags & CF_IGNORE_FORCE))
938 rsp = c->cruncher(csp);
941 /* Deliver, log and free the interception response. */
942 send_crunch_response(csp, rsp);
943 csp->flags |= CSP_FLAG_CRUNCHED;
944 #ifdef FEATURE_STATISTICS
945 if (c->flags & CF_COUNT_AS_REJECT)
947 csp->flags |= CSP_FLAG_REJECTED;
949 #endif /* def FEATURE_STATISTICS */
960 /*********************************************************************
962 * Function : build_request_line
964 * Description : Builds the HTTP request line.
966 * If a HTTP forwarder is used it expects the whole URL,
967 * web servers only get the path.
970 * 1 : csp = Current client state (buffers, headers, etc...)
971 * 2 : fwd = The forwarding spec used for the request.
973 * 3 : request_line = The old request line which will be replaced.
975 * Returns : Nothing. Terminates in case of memory problems.
977 *********************************************************************/
978 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
980 struct http_request *http = csp->http;
983 * Downgrade http version from 1.1 to 1.0
984 * if +downgrade action applies.
986 if ((csp->action->flags & ACTION_DOWNGRADE)
987 && (!strcmpic(http->version, "HTTP/1.1")))
989 freez(http->version);
990 http->version = strdup_or_die("HTTP/1.0");
994 * Rebuild the request line.
996 freez(*request_line);
997 *request_line = strdup(http->gpc);
998 string_append(request_line, " ");
1000 if (fwd != NULL && fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1002 string_append(request_line, http->url);
1006 string_append(request_line, http->path);
1008 string_append(request_line, " ");
1009 string_append(request_line, http->version);
1011 if (*request_line == NULL)
1013 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1015 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1019 /*********************************************************************
1021 * Function : change_request_destination
1023 * Description : Parse a (rewritten) request line and regenerate
1024 * the http request data.
1027 * 1 : csp = Current client state (buffers, headers, etc...)
1029 * Returns : Forwards the parse_http_request() return code.
1030 * Terminates in case of memory problems.
1032 *********************************************************************/
1033 static jb_err change_request_destination(struct client_state *csp)
1035 struct http_request *http = csp->http;
1038 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1039 csp->headers->first->str);
1040 free_http_request(http);
1041 err = parse_http_request(csp->headers->first->str, http);
1042 if (JB_ERR_OK != err)
1044 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1045 jb_err_to_string(err));
1047 if (http->ssl && strcmpic(csp->http->gpc, "CONNECT"))
1050 * A client header filter changed the request URL from
1051 * http:// to https:// which we currently don't support.
1053 log_error(LOG_LEVEL_ERROR, "Changing the request destination from http "
1054 "to https behind the client's back currently isn't supported.");
1055 return JB_ERR_PARSE;
1062 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1063 /*********************************************************************
1065 * Function : server_response_is_complete
1067 * Description : Determines whether we should stop reading
1068 * from the server socket.
1071 * 1 : csp = Current client state (buffers, headers, etc...)
1072 * 2 : content_length = Length of content received so far.
1074 * Returns : TRUE if the response is complete,
1077 *********************************************************************/
1078 static int server_response_is_complete(struct client_state *csp,
1079 unsigned long long content_length)
1081 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1083 if (!strcmpic(csp->http->gpc, "HEAD"))
1086 * "HEAD" implies no body, we are thus expecting
1087 * no content. XXX: incomplete "list" of methods?
1089 csp->expected_content_length = 0;
1090 content_length_known = TRUE;
1091 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1094 if (csp->http->status == 204 || csp->http->status == 304)
1097 * Expect no body. XXX: incomplete "list" of status codes?
1099 csp->expected_content_length = 0;
1100 content_length_known = TRUE;
1101 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1104 return (content_length_known && ((0 == csp->expected_content_length)
1105 || (csp->expected_content_length <= content_length)));
1109 #ifdef FEATURE_CONNECTION_SHARING
1110 /*********************************************************************
1112 * Function : wait_for_alive_connections
1114 * Description : Waits for alive connections to timeout.
1120 *********************************************************************/
1121 static void wait_for_alive_connections(void)
1123 int connections_alive = close_unusable_connections();
1125 while (0 < connections_alive)
1127 log_error(LOG_LEVEL_CONNECT,
1128 "Waiting for %d connections to timeout.",
1131 connections_alive = close_unusable_connections();
1134 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1137 #endif /* def FEATURE_CONNECTION_SHARING */
1140 /*********************************************************************
1142 * Function : save_connection_destination
1144 * Description : Remembers a connection for reuse later on.
1147 * 1 : sfd = Open socket to remember.
1148 * 2 : http = The destination for the connection.
1149 * 3 : fwd = The forwarder settings used.
1150 * 4 : server_connection = storage.
1154 *********************************************************************/
1155 void save_connection_destination(jb_socket sfd,
1156 const struct http_request *http,
1157 const struct forward_spec *fwd,
1158 struct reusable_connection *server_connection)
1160 assert(sfd != JB_INVALID_SOCKET);
1161 assert(NULL != http->host);
1163 server_connection->sfd = sfd;
1164 server_connection->host = strdup_or_die(http->host);
1165 server_connection->port = http->port;
1167 assert(NULL != fwd);
1168 assert(server_connection->gateway_host == NULL);
1169 assert(server_connection->gateway_port == 0);
1170 assert(server_connection->forwarder_type == 0);
1171 assert(server_connection->forward_host == NULL);
1172 assert(server_connection->forward_port == 0);
1174 server_connection->forwarder_type = fwd->type;
1175 if (NULL != fwd->gateway_host)
1177 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1181 server_connection->gateway_host = NULL;
1183 server_connection->gateway_port = fwd->gateway_port;
1184 if (NULL != fwd->auth_username)
1186 server_connection->auth_username = strdup_or_die(fwd->auth_username);
1190 server_connection->auth_username = NULL;
1192 if (NULL != fwd->auth_password)
1194 server_connection->auth_password = strdup_or_die(fwd->auth_password);
1198 server_connection->auth_password = NULL;
1201 if (NULL != fwd->forward_host)
1203 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1207 server_connection->forward_host = NULL;
1209 server_connection->forward_port = fwd->forward_port;
1211 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1214 /*********************************************************************
1216 * Function : verify_request_length
1218 * Description : Checks if we already got the whole client requests
1219 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1222 * Data that doesn't belong to the current request is
1223 * either thrown away to let the client retry on a clean
1224 * socket, or stashed to be dealt with after the current
1225 * request is served.
1228 * 1 : csp = Current client state (buffers, headers, etc...)
1232 *********************************************************************/
1233 static void verify_request_length(struct client_state *csp)
1235 unsigned long long buffered_request_bytes =
1236 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1238 if ((csp->expected_client_content_length != 0)
1239 && (buffered_request_bytes != 0))
1241 if (csp->expected_client_content_length >= buffered_request_bytes)
1243 csp->expected_client_content_length -= buffered_request_bytes;
1244 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1245 "to account for the %llu ones we already got.",
1246 csp->expected_client_content_length, buffered_request_bytes);
1250 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1251 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1252 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1253 "Marking the server socket tainted after throwing %llu bytes away.",
1254 buffered_request_bytes - csp->expected_client_content_length);
1255 csp->expected_client_content_length = 0;
1256 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1259 if (csp->expected_client_content_length == 0)
1261 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1265 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1266 && ((csp->client_iob->cur < csp->client_iob->eod)
1267 || (csp->expected_client_content_length != 0)))
1269 if (strcmpic(csp->http->gpc, "GET")
1270 && strcmpic(csp->http->gpc, "HEAD")
1271 && strcmpic(csp->http->gpc, "TRACE")
1272 && strcmpic(csp->http->gpc, "OPTIONS")
1273 && strcmpic(csp->http->gpc, "DELETE"))
1275 /* XXX: this is an incomplete hack */
1276 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1277 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1281 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1283 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1285 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1286 log_error(LOG_LEVEL_CONNECT,
1287 "Possible pipeline attempt detected. The connection will not "
1288 "be kept alive and we will only serve the first request.");
1289 /* Nuke the pipelined requests from orbit, just to be sure. */
1290 clear_iob(csp->client_iob);
1295 * Keep the pipelined data around for now, we'll deal with
1296 * it once we're done serving the current request.
1298 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1299 assert(csp->client_iob->eod >= csp->client_iob->cur);
1300 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1301 "%d bytes of pipelined data received.",
1302 (int)(csp->client_iob->eod - csp->client_iob->cur));
1308 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1309 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1314 /*********************************************************************
1316 * Function : mark_server_socket_tainted
1318 * Description : Makes sure we don't reuse a server socket
1319 * (if we didn't read everything the server sent
1320 * us reusing the socket would lead to garbage).
1323 * 1 : csp = Current client state (buffers, headers, etc...)
1327 *********************************************************************/
1328 static void mark_server_socket_tainted(struct client_state *csp)
1331 * For consistency we always mark the server socket
1332 * tainted, however, to reduce the log noise we only
1333 * emit a log message if the server socket could have
1334 * actually been reused.
1336 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1337 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1339 log_error(LOG_LEVEL_CONNECT,
1340 "Marking the server socket %d tainted.",
1341 csp->server_connection.sfd);
1343 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1346 /*********************************************************************
1348 * Function : get_request_line
1350 * Description : Read the client request line.
1353 * 1 : csp = Current client state (buffers, headers, etc...)
1355 * Returns : Pointer to request line or NULL in case of errors.
1357 *********************************************************************/
1358 static char *get_request_line(struct client_state *csp)
1360 char buf[BUFFER_SIZE];
1361 char *request_line = NULL;
1364 memset(buf, 0, sizeof(buf));
1366 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1369 * If there are multiple pipelined requests waiting,
1370 * the flag will be set again once the next request
1373 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1375 request_line = get_header(csp->client_iob);
1376 if ((NULL != request_line) && ('\0' != *request_line))
1378 return request_line;
1382 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1383 "received yet. Continuing reading from %d.", csp->cfd);
1391 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1393 !data_is_available(csp->cfd, csp->config->socket_timeout)
1396 if (socket_is_still_alive(csp->cfd))
1398 log_error(LOG_LEVEL_CONNECT,
1399 "No request line on socket %d received in time. Timeout: %d.",
1400 csp->cfd, csp->config->socket_timeout);
1401 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1402 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1403 get_write_delay(csp));
1407 log_error(LOG_LEVEL_CONNECT,
1408 "The client side of the connection on socket %d got "
1409 "closed without sending a complete request line.", csp->cfd);
1414 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1416 if (len <= 0) return NULL;
1419 * If there is no memory left for buffering the
1420 * request, there is nothing we can do but hang up
1422 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1427 request_line = get_header(csp->client_iob);
1429 } while ((NULL != request_line) && ('\0' == *request_line));
1431 return request_line;
1437 CHUNK_STATUS_MISSING_DATA,
1438 CHUNK_STATUS_BODY_COMPLETE,
1439 CHUNK_STATUS_PARSE_ERROR
1443 /*********************************************************************
1445 * Function : chunked_body_is_complete
1447 * Description : Figures out whether or not a chunked body is complete.
1449 * Currently it always starts at the beginning of the
1450 * buffer which is somewhat wasteful and prevents Privoxy
1451 * from starting to forward the correctly parsed chunks
1452 * as soon as theoretically possible.
1454 * Should be modified to work with a common buffer,
1455 * and allow the caller to skip already parsed chunks.
1457 * This would allow the function to be used for unbuffered
1458 * response bodies as well.
1461 * 1 : iob = Buffer with the body to check.
1462 * 2 : length = Length of complete body
1464 * Returns : Enum with the result of the check.
1466 *********************************************************************/
1467 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1469 unsigned int chunksize;
1475 * We need at least a single digit, followed by "\r\n",
1476 * followed by an unknown amount of data, followed by "\r\n".
1478 if (p + 5 > iob->eod)
1480 return CHUNK_STATUS_MISSING_DATA;
1482 if (sscanf(p, "%x", &chunksize) != 1)
1484 return CHUNK_STATUS_PARSE_ERROR;
1488 * We want at least a single digit, followed by "\r\n",
1489 * followed by the specified amount of data, followed by "\r\n".
1491 if (p + chunksize + 5 > iob->eod)
1493 return CHUNK_STATUS_MISSING_DATA;
1496 /* Skip chunk-size. */
1497 p = strstr(p, "\r\n");
1500 return CHUNK_STATUS_PARSE_ERROR;
1502 /* Move beyond the chunkdata. */
1505 /* There should be another "\r\n" to skip */
1506 if (memcmp(p, "\r\n", 2))
1508 return CHUNK_STATUS_PARSE_ERROR;
1511 } while (chunksize > 0U);
1513 *length = (size_t)(p - iob->cur);
1514 assert(*length <= (size_t)(iob->eod - iob->cur));
1515 assert(p <= iob->eod);
1517 return CHUNK_STATUS_BODY_COMPLETE;
1522 /*********************************************************************
1524 * Function : receive_chunked_client_request_body
1526 * Description : Read the chunk-encoded client request body.
1527 * Failures are dealt with.
1530 * 1 : csp = Current client state (buffers, headers, etc...)
1532 * Returns : JB_ERR_OK or JB_ERR_PARSE
1534 *********************************************************************/
1535 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1538 enum chunk_status status;
1540 while (CHUNK_STATUS_MISSING_DATA ==
1541 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1543 char buf[BUFFER_SIZE];
1546 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1548 log_error(LOG_LEVEL_ERROR,
1549 "Timeout while waiting for the client body.");
1552 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1555 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1558 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1563 if (status != CHUNK_STATUS_BODY_COMPLETE)
1565 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1566 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1567 log_error(LOG_LEVEL_CLF,
1568 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1569 return JB_ERR_PARSE;
1571 log_error(LOG_LEVEL_CONNECT,
1572 "Chunked client body completely read. Length: %lu", body_length);
1573 csp->expected_client_content_length = body_length;
1581 /*********************************************************************
1583 * Function : fuzz_chunked_transfer_encoding
1585 * Description : Treat the fuzzed input as chunked transfer encoding
1586 * to check and dechunk.
1589 * 1 : csp = Used to store the data.
1590 * 2 : fuzz_input_file = File to read the input from.
1592 * Returns : Result of dechunking
1594 *********************************************************************/
1595 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1598 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1599 enum chunk_status status;
1601 status = chunked_body_is_complete(csp->iob, &length);
1602 if (CHUNK_STATUS_BODY_COMPLETE != status)
1604 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1607 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1612 /*********************************************************************
1614 * Function : fuzz_client_request
1616 * Description : Try to get a client request from the fuzzed input.
1619 * 1 : csp = Current client state (buffers, headers, etc...)
1620 * 2 : fuzz_input_file = File to read the input from.
1622 * Returns : Result of fuzzing.
1624 *********************************************************************/
1625 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1630 csp->ip_addr_str = "fuzzer";
1632 if (strcmp(fuzz_input_file, "-") != 0)
1634 log_error(LOG_LEVEL_FATAL,
1635 "Fuzzed client requests can currently only be read from stdin (-).");
1637 err = receive_client_request(csp);
1638 if (err != JB_ERR_OK)
1642 err = parse_client_request(csp);
1643 if (err != JB_ERR_OK)
1651 #endif /* def FUZZ */
1654 #ifdef FEATURE_FORCE_LOAD
1655 /*********************************************************************
1657 * Function : force_required
1659 * Description : Checks a request line to see if it contains
1660 * the FORCE_PREFIX. If it does, it is removed
1661 * unless enforcing requests has beend disabled.
1664 * 1 : request_line = HTTP request line
1666 * Returns : TRUE if force is required, FALSE otherwise.
1668 *********************************************************************/
1669 static int force_required(const struct client_state *csp, char *request_line)
1673 p = strstr(request_line, "http://");
1677 p += strlen("http://");
1681 /* Intercepted request usually don't specify the protocol. */
1685 /* Go to the beginning of the path */
1690 * If the path is missing the request line is invalid and we
1691 * are done here. The client-visible rejection happens later on.
1696 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1698 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1700 /* XXX: Should clean more carefully */
1701 strclean(request_line, FORCE_PREFIX);
1702 log_error(LOG_LEVEL_FORCE,
1703 "Enforcing request: \"%s\".", request_line);
1707 log_error(LOG_LEVEL_FORCE,
1708 "Ignored force prefix in request: \"%s\".", request_line);
1714 #endif /* def FEATURE_FORCE_LOAD */
1717 /*********************************************************************
1719 * Function : receive_client_request
1721 * Description : Read the client's request (more precisely the
1722 * client headers) and answer it if necessary.
1725 * 1 : csp = Current client state (buffers, headers, etc...)
1727 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1729 *********************************************************************/
1730 static jb_err receive_client_request(struct client_state *csp)
1732 char buf[BUFFER_SIZE];
1735 struct http_request *http;
1739 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1740 struct list header_list;
1741 struct list *headers = &header_list;
1743 /* We don't care if the arriving data is a valid HTTP request or not. */
1744 csp->requests_received_total++;
1748 memset(buf, 0, sizeof(buf));
1750 req = get_request_line(csp);
1753 mark_server_socket_tainted(csp);
1754 return JB_ERR_PARSE;
1756 assert(*req != '\0');
1758 if (client_protocol_is_unsupported(csp, req))
1760 return JB_ERR_PARSE;
1763 #ifdef FEATURE_FORCE_LOAD
1764 if (force_required(csp, req))
1766 csp->flags |= CSP_FLAG_FORCED;
1768 #endif /* def FEATURE_FORCE_LOAD */
1770 err = parse_http_request(req, http);
1772 if (JB_ERR_OK != err)
1774 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1775 get_write_delay(csp));
1776 /* XXX: Use correct size */
1777 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1778 log_error(LOG_LEVEL_ERROR,
1779 "Couldn't parse request line received from %s: %s",
1780 csp->ip_addr_str, jb_err_to_string(err));
1782 free_http_request(http);
1783 return JB_ERR_PARSE;
1786 /* grab the rest of the client's headers */
1790 p = get_header(csp->client_iob);
1794 /* There are no additional headers to read. */
1801 * We didn't receive a complete header
1802 * line yet, get the rest of it.
1804 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1806 log_error(LOG_LEVEL_ERROR,
1807 "Stopped grabbing the client headers.");
1808 destroy_list(headers);
1809 return JB_ERR_PARSE;
1812 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1815 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1816 destroy_list(headers);
1817 return JB_ERR_PARSE;
1820 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1823 * If there is no memory left for buffering the
1824 * request, there is nothing we can do but hang up
1826 destroy_list(headers);
1827 return JB_ERR_MEMORY;
1832 if (!strncmpic(p, "Transfer-Encoding:", 18))
1835 * XXX: should be called through sed()
1836 * but currently can't.
1838 client_transfer_encoding(csp, &p);
1841 * We were able to read a complete
1842 * header and can finally enlist it.
1849 if (http->host == NULL)
1852 * If we still don't know the request destination,
1853 * the request is invalid or the client uses
1854 * Privoxy without its knowledge.
1856 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1859 * Our attempts to get the request destination
1860 * elsewhere failed or Privoxy is configured
1861 * to only accept proxy requests.
1863 * An error response has already been send
1864 * and we're done here.
1866 return JB_ERR_PARSE;
1870 #ifdef FEATURE_CLIENT_TAGS
1871 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1872 set_client_address(csp, headers);
1873 get_tag_list_for_client(csp->client_tags, csp->client_address);
1877 * Determine the actions for this URL
1879 #ifdef FEATURE_TOGGLE
1880 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1882 /* Most compatible set of actions (i.e. none) */
1883 init_current_action(csp->action);
1886 #endif /* ndef FEATURE_TOGGLE */
1888 get_url_actions(csp, http);
1891 enlist(csp->headers, http->cmd);
1893 /* Append the previously read headers */
1894 err = list_append_list_unique(csp->headers, headers);
1895 destroy_list(headers);
1902 /*********************************************************************
1904 * Function : parse_client_request
1906 * Description : Parses the client's request and decides what to do
1909 * Note that since we're not using select() we could get
1910 * blocked here if a client connected, then didn't say
1914 * 1 : csp = Current client state (buffers, headers, etc...)
1916 * Returns : JB_ERR_OK or JB_ERR_PARSE
1918 *********************************************************************/
1919 static jb_err parse_client_request(struct client_state *csp)
1921 struct http_request *http = csp->http;
1924 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1925 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1926 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1927 && (csp->http->ssl == 0))
1929 /* Assume persistence until further notice */
1930 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1932 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1934 if (csp->http->ssl == 0)
1937 * This whole block belongs to chat() but currently
1938 * has to be executed before sed().
1940 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1942 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1944 return JB_ERR_PARSE;
1949 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1951 verify_request_length(csp);
1953 #ifndef FEATURE_HTTPS_INSPECTION
1956 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1960 err = sed(csp, FILTER_CLIENT_HEADERS);
1961 if (JB_ERR_OK != err)
1963 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1965 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1966 csp->ip_addr_str, csp->http->cmd);
1967 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1968 return JB_ERR_PARSE;
1970 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1972 /* Check request line for rewrites. */
1973 if ((NULL == csp->headers->first->str)
1974 || (strcmp(http->cmd, csp->headers->first->str) &&
1975 (JB_ERR_OK != change_request_destination(csp))))
1978 * A header filter broke the request line - bail out.
1980 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1981 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1982 /* XXX: Use correct size */
1983 log_error(LOG_LEVEL_CLF,
1984 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
1985 log_error(LOG_LEVEL_ERROR,
1986 "Invalid request line after applying header filters.");
1987 free_http_request(http);
1989 return JB_ERR_PARSE;
1992 if (client_has_unsupported_expectations(csp))
1994 return JB_ERR_PARSE;
2002 /*********************************************************************
2004 * Function : read_http_request_body
2006 * Description : Reads remaining request body from the client.
2009 * 1 : csp = Current client state (buffers, headers, etc...)
2011 * Returns : 0 on success, anything else is an error.
2013 *********************************************************************/
2014 static int read_http_request_body(struct client_state *csp)
2016 size_t to_read = csp->expected_client_content_length;
2019 assert(to_read != 0);
2021 /* check if all data has been already read */
2022 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2027 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2028 to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2029 to_read -= (unsigned)len)
2031 char buf[BUFFER_SIZE];
2032 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2034 log_error(LOG_LEVEL_CONNECT,
2035 "Waiting for up to %d bytes of request body from the client.",
2037 len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2040 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2043 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2047 assert(to_read >= len);
2052 log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %d more bytes",
2053 csp->expected_client_content_length);
2056 log_error(LOG_LEVEL_CONNECT, "The last %d bytes of the request body have been read",
2057 csp->expected_client_content_length);
2062 /*********************************************************************
2064 * Function : update_client_headers
2066 * Description : Updates the HTTP headers from the client request.
2069 * 1 : csp = Current client state (buffers, headers, etc...)
2070 * 2 : new_content_length = new content length value to set
2072 * Returns : 0 on success, anything else is an error.
2074 *********************************************************************/
2075 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2077 static const char content_length[] = "Content-Length:";
2079 struct list_entry *p;
2081 #ifndef FEATURE_HTTPS_INSPECTION
2082 for (p = csp->headers->first;
2084 for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2086 !updated && (p != NULL); p = p->next)
2088 /* Header crunch()ed in previous run? -> ignore */
2094 /* Does the current parser handle this header? */
2095 if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2097 updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2109 /*********************************************************************
2111 * Function : can_filter_request_body
2113 * Description : Checks if the current request body can be stored in
2114 * the client_iob without hitting buffer limit.
2117 * 1 : csp = Current client state (buffers, headers, etc...)
2119 * Returns : TRUE if the current request size do not exceed buffer limit
2122 *********************************************************************/
2123 static int can_filter_request_body(const struct client_state *csp)
2125 if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2126 csp->expected_client_content_length))
2128 log_error(LOG_LEVEL_INFO,
2129 "Not filtering request body from %s: buffer limit %d will be exceeded "
2130 "(content length %d)", csp->ip_addr_str, csp->config->buffer_limit,
2131 csp->expected_client_content_length);
2138 /*********************************************************************
2140 * Function : send_http_request
2142 * Description : Sends the HTTP headers from the client request
2143 * and all the body data that has already been received.
2146 * 1 : csp = Current client state (buffers, headers, etc...)
2148 * Returns : 0 on success, anything else is an error.
2150 *********************************************************************/
2151 static int send_http_request(struct client_state *csp)
2155 const char *to_send;
2157 int filter_client_body = csp->expected_client_content_length != 0 &&
2158 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2160 if (filter_client_body)
2162 if (read_http_request_body(csp))
2166 to_send_len = csp->expected_client_content_length;
2167 to_send = execute_client_body_filters(csp, &to_send_len);
2168 if (to_send == NULL)
2170 /* just flush client_iob */
2171 filter_client_body = FALSE;
2173 else if (to_send_len != csp->expected_client_content_length &&
2174 update_client_headers(csp, to_send_len))
2176 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2179 csp->expected_client_content_length = 0;
2182 hdr = list_to_text(csp->headers);
2185 /* FIXME Should handle error properly */
2186 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2188 list_remove_all(csp->headers);
2191 * Write the client's (modified) header to the server
2192 * (along with anything else that may be in the buffer)
2194 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2199 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2200 csp->http->hostport);
2204 if (filter_client_body)
2206 write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2210 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2211 csp->http->hostport);
2216 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2217 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2219 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2220 csp->http->hostport);
2227 #ifdef FEATURE_HTTPS_INSPECTION
2228 /*********************************************************************
2230 * Function : read_https_request_body
2232 * Description : Reads remaining request body from the client.
2235 * 1 : csp = Current client state (buffers, headers, etc...)
2237 * Returns : 0 on success, anything else is an error.
2239 *********************************************************************/
2240 static int read_https_request_body(struct client_state *csp)
2242 size_t to_read = csp->expected_client_content_length;
2245 assert(to_read != 0);
2247 /* check if all data has been already read */
2248 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2253 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2254 to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2255 data_is_available(csp->cfd, csp->config->socket_timeout));
2256 to_read -= (unsigned)len)
2258 unsigned char buf[BUFFER_SIZE];
2259 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2261 log_error(LOG_LEVEL_CONNECT,
2262 "Waiting for up to %d bytes of request body from the client.",
2264 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2265 (unsigned)max_bytes_to_read);
2268 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2271 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2275 assert(to_read >= len);
2280 log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %d more bytes", to_read);
2284 log_error(LOG_LEVEL_CONNECT, "The last %d bytes of the request body have been read",
2285 csp->expected_client_content_length);
2290 /*********************************************************************
2292 * Function : receive_and_send_encrypted_post_data
2294 * Description : Reads remaining request body from the client and sends
2298 * 1 : csp = Current client state (buffers, headers, etc...)
2300 * Returns : 0 on success, anything else is an error.
2302 *********************************************************************/
2303 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2305 int content_length_known = csp->expected_client_content_length != 0;
2307 while (is_ssl_pending(&(csp->ssl_client_attr))
2308 || (content_length_known && csp->expected_client_content_length != 0))
2310 unsigned char buf[BUFFER_SIZE];
2312 int max_bytes_to_read = sizeof(buf);
2314 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2316 max_bytes_to_read = (int)csp->expected_client_content_length;
2318 log_error(LOG_LEVEL_CONNECT,
2319 "Waiting for up to %d bytes of request body from the client.",
2321 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2322 (unsigned)max_bytes_to_read);
2329 /* XXX: Does this actually happen? */
2332 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2334 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2339 if (csp->expected_client_content_length != 0)
2341 if (csp->expected_client_content_length >= len)
2343 csp->expected_client_content_length -= (unsigned)len;
2345 if (csp->expected_client_content_length == 0)
2347 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2353 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2360 /*********************************************************************
2362 * Function : send_https_request
2364 * Description : Sends the HTTP headers from the client request
2365 * and all the body data that has already been received.
2368 * 1 : csp = Current client state (buffers, headers, etc...)
2370 * Returns : 0 on success, anything else is an error.
2372 *********************************************************************/
2373 static int send_https_request(struct client_state *csp)
2378 const char *to_send;
2380 int filter_client_body = csp->expected_client_content_length != 0 &&
2381 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2383 if (filter_client_body)
2385 if (read_https_request_body(csp))
2389 to_send_len = csp->expected_client_content_length;
2390 to_send = execute_client_body_filters(csp, &to_send_len);
2391 if (to_send == NULL)
2393 /* just flush client_iob */
2394 filter_client_body = FALSE;
2396 else if (to_send_len != csp->expected_client_content_length &&
2397 update_client_headers(csp, to_send_len))
2399 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2402 csp->expected_client_content_length = 0;
2405 hdr = list_to_text(csp->https_headers);
2408 /* FIXME Should handle error properly */
2409 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2411 list_remove_all(csp->https_headers);
2414 * Write the client's (modified) header to the server
2415 * (along with anything else that may be in the buffer)
2417 ret = ssl_send_data(&(csp->ssl_server_attr),
2418 (const unsigned char *)hdr, strlen(hdr));
2423 log_error(LOG_LEVEL_CONNECT,
2424 "Failed sending encrypted request headers to: %s: %E",
2425 csp->http->hostport);
2426 mark_server_socket_tainted(csp);
2430 if (filter_client_body)
2432 ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2436 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2437 csp->http->hostport);
2442 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2443 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2444 csp->client_iob)) < 0))
2446 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2447 csp->http->hostport);
2450 if (flushed != 0 || csp->expected_client_content_length != 0)
2452 if (csp->expected_client_content_length != 0)
2454 if (csp->expected_client_content_length < flushed)
2456 log_error(LOG_LEVEL_ERROR,
2457 "Flushed %ld bytes of request body while only expecting %llu",
2458 flushed, csp->expected_client_content_length);
2459 csp->expected_client_content_length = 0;
2463 log_error(LOG_LEVEL_CONNECT,
2464 "Flushed %ld bytes of request body while expecting %llu",
2465 flushed, csp->expected_client_content_length);
2466 csp->expected_client_content_length -= (unsigned)flushed;
2467 if (receive_and_send_encrypted_post_data(csp))
2475 log_error(LOG_LEVEL_CONNECT,
2476 "Flushed %ld bytes of request body", flushed);
2480 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2487 /*********************************************************************
2489 * Function : receive_encrypted_request
2491 * Description : Receives an encrypted request.
2494 * 1 : csp = Current client state (buffers, headers, etc...)
2496 * Returns : JB_ERR_OK on success,
2497 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2499 *********************************************************************/
2500 static jb_err receive_encrypted_request(struct client_state *csp)
2502 char buf[BUFFER_SIZE];
2508 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2509 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2510 !data_is_available(csp->cfd, csp->config->socket_timeout))
2512 log_error(LOG_LEVEL_CONNECT,
2513 "Socket %d timed out while waiting for client headers", csp->cfd);
2514 return JB_ERR_PARSE;
2516 len = ssl_recv_data(&(csp->ssl_client_attr),
2517 (unsigned char *)buf, sizeof(buf));
2520 log_error(LOG_LEVEL_CONNECT,
2521 "Socket %d closed while waiting for client headers", csp->cfd);
2522 return JB_ERR_PARSE;
2526 return JB_ERR_PARSE;
2528 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2530 return JB_ERR_MEMORY;
2532 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2533 } while (p == NULL);
2535 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2541 /*********************************************************************
2543 * Function : change_encrypted_request_destination
2545 * Description : Parse a (rewritten) request line from an encrypted
2546 * request and regenerate the http request data.
2549 * 1 : csp = Current client state (buffers, headers, etc...)
2551 * Returns : Forwards the parse_http_request() return code.
2552 * Terminates in case of memory problems.
2554 *********************************************************************/
2555 static jb_err change_encrypted_request_destination(struct client_state *csp)
2558 char *original_host = csp->http->host;
2560 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2561 csp->https_headers->first->str);
2562 csp->http->host = NULL;
2563 free_http_request(csp->http);
2564 err = parse_http_request(csp->https_headers->first->str, csp->http);
2565 if (JB_ERR_OK != err)
2567 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2568 jb_err_to_string(err));
2569 freez(original_host);
2573 if (csp->http->host == NULL)
2576 * The rewritten request line did not specify a host
2577 * which means we can use the original host specified
2580 csp->http->host = original_host;
2581 log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2584 * If the rewritten request line didn't contain a host
2585 * it also didn't contain a port so we can reuse the host
2586 * and set the port to 443.
2588 freez(csp->http->hostport);
2589 csp->http->hostport = strdup_or_die(csp->http->host);
2590 csp->http->port = 443;
2592 * While the request line didn't mention it,
2593 * we're https-inspecting and want to speak TLS
2596 csp->http->server_ssl = 1;
2601 /* The rewrite filter added a host so we can ditch the original */
2602 freez(original_host);
2603 csp->http->server_ssl = csp->http->ssl;
2606 csp->http->client_ssl = 1;
2608 freez(csp->https_headers->first->str);
2609 build_request_line(csp, NULL, &csp->https_headers->first->str);
2611 if (!server_use_ssl(csp))
2613 log_error(LOG_LEVEL_REDIRECTS,
2614 "Rewritten request line results in downgrade to http");
2616 * Replace the unencryptd headers received with the
2617 * CONNECT request with the ones we received securely.
2619 destroy_list(csp->headers);
2620 csp->headers->first = csp->https_headers->first;
2621 csp->headers->last = csp->https_headers->last;
2622 csp->https_headers->first = NULL;
2623 csp->https_headers->last = NULL;
2631 /*********************************************************************
2633 * Function : process_encrypted_request
2635 * Description : Receives and parses an encrypted request.
2638 * 1 : csp = Current client state (buffers, headers, etc...)
2640 * Returns : JB_ERR_OK on success,
2641 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2643 *********************************************************************/
2644 static jb_err process_encrypted_request(struct client_state *csp)
2649 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2650 struct list header_list;
2651 struct list *headers = &header_list;
2653 assert(csp->ssl_with_client_is_opened);
2655 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2656 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2658 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2661 err = receive_encrypted_request(csp);
2662 if (err != JB_ERR_OK)
2664 if (csp->client_iob->cur == NULL ||
2665 csp->client_iob->cur == csp->client_iob->eod)
2668 * We did not receive any data, most likely because the
2669 * client is done. Don't log this as a parse failure.
2671 return JB_ERR_PARSE;
2673 /* XXX: Also used for JB_ERR_MEMORY */
2674 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2675 jb_err_to_string(err));
2676 ssl_send_data_delayed(&(csp->ssl_client_attr),
2677 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2681 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2682 request_line = get_header(csp->client_iob);
2683 if (request_line == NULL)
2685 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2686 ssl_send_data_delayed(&(csp->ssl_client_attr),
2687 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2688 return JB_ERR_PARSE;
2690 assert(*request_line != '\0');
2692 if (client_protocol_is_unsupported(csp, request_line))
2695 * If the protocol is unsupported we're done here.
2696 * client_protocol_is_unsupported() took care of sending
2697 * the error response and logging the error message.
2699 return JB_ERR_PARSE;
2702 #ifdef FEATURE_FORCE_LOAD
2703 if (force_required(csp, request_line))
2705 csp->flags |= CSP_FLAG_FORCED;
2707 #endif /* def FEATURE_FORCE_LOAD */
2709 free_http_request(csp->http);
2711 err = parse_http_request(request_line, csp->http);
2712 /* XXX: Restore ssl setting. This is ugly */
2713 csp->http->client_ssl = 1;
2714 csp->http->server_ssl = 1;
2716 freez(request_line);
2717 if (JB_ERR_OK != err)
2719 ssl_send_data_delayed(&(csp->ssl_client_attr),
2720 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2721 /* XXX: Use correct size */
2722 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2723 log_error(LOG_LEVEL_ERROR,
2724 "Couldn't parse request line received from %s: %s",
2725 csp->ip_addr_str, jb_err_to_string(err));
2727 free_http_request(csp->http);
2728 return JB_ERR_PARSE;
2731 /* Parse the rest of the client's headers. */
2735 p = get_header(csp->client_iob);
2739 /* There are no additional headers to read. */
2746 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2749 * Our attempts to get the request destination
2752 log_error(LOG_LEVEL_ERROR,
2753 "Failed to get the encrypted request destination");
2754 ssl_send_data_delayed(&(csp->ssl_client_attr),
2755 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2756 return JB_ERR_PARSE;
2759 /* Split the domain we just got for pattern matching */
2760 init_domain_components(csp->http);
2762 #ifdef FEATURE_CLIENT_TAGS
2763 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2764 if (csp->client_address == NULL)
2766 set_client_address(csp, headers);
2767 get_tag_list_for_client(csp->client_tags, csp->client_address);
2771 #ifdef FEATURE_TOGGLE
2772 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2776 * Determine the actions for this request after
2777 * clearing the ones from the previous one.
2779 free_current_action(csp->action);
2780 get_url_actions(csp, csp->http);
2783 enlist(csp->https_headers, csp->http->cmd);
2785 /* Append the previously read headers */
2786 err = list_append_list_unique(csp->https_headers, headers);
2787 destroy_list(headers);
2788 if (JB_ERR_OK != err)
2790 /* XXX: Send error message */
2794 /* XXX: Work around crash */
2795 csp->error_message = NULL;
2797 /* XXX: Why do this here? */
2800 err = sed_https(csp);
2801 if (JB_ERR_OK != err)
2803 ssl_send_data_delayed(&(csp->ssl_client_attr),
2804 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2805 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2807 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2808 csp->ip_addr_str, csp->http->cmd);
2809 return JB_ERR_PARSE;
2812 if ((NULL == csp->https_headers->first->str)
2813 || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2814 (JB_ERR_OK != change_encrypted_request_destination(csp))))
2816 ssl_send_data_delayed(&(csp->ssl_client_attr),
2817 (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2818 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2819 log_error(LOG_LEVEL_ERROR,
2820 "Invalid request line after applying header filters.");
2821 /* XXX: Use correct size */
2822 log_error(LOG_LEVEL_CLF,
2823 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2825 return JB_ERR_PARSE;
2828 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2829 log_applied_actions(csp->action);
2830 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2837 /*********************************************************************
2839 * Function : cgi_page_requested
2841 * Description : Checks if a request is for an internal CGI page.
2844 * 1 : host = The host requested by the client.
2846 * Returns : 1 if a CGI page has been requested, 0 otherwise
2848 *********************************************************************/
2849 static int cgi_page_requested(const char *host)
2851 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2852 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2853 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2854 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2864 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2865 /*********************************************************************
2867 * Function : continue_https_chat
2869 * Description : Behaves similar to chat() but only deals with
2870 * https-inspected requests that arrive on an already
2871 * established connection. The first request is always
2872 * served by chat() which is a lot more complex as it
2873 * has to deal with forwarding settings and connection
2876 * If a connection to the server has already been
2877 * opened it is reused unless the request is blocked
2878 * or the forwarder changed.
2880 * If a connection to the server has not yet been
2881 * opened (because the previous request was crunched),
2882 * or the forwarder changed, the connection is dropped
2883 * so that the client retries on a fresh one.
2886 * 1 : csp = Current client state (buffers, headers, etc...)
2888 * Returns : Nothing.
2890 *********************************************************************/
2891 static void continue_https_chat(struct client_state *csp)
2893 const struct forward_spec *fwd;
2895 if (JB_ERR_OK != process_encrypted_request(csp))
2900 csp->requests_received_total++;
2903 * We have an encrypted request. Check if one of the crunchers wants it.
2905 if (crunch_response_triggered(csp, crunchers_all))
2908 * Yes. The client got the crunch response and we're done here.
2912 if (csp->ssl_with_server_is_opened == 0)
2914 log_error(LOG_LEVEL_CONNECT,
2915 "Dropping the client connection on socket %d. "
2916 "The server connection has not been established yet.",
2918 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2921 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2923 fwd = forward_url(csp, csp->http);
2924 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2926 log_error(LOG_LEVEL_CONNECT,
2927 "Dropping the client connection on socket %d with "
2928 "server socket %d connected to %s. The forwarder has changed.",
2929 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2930 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2934 log_error(LOG_LEVEL_CONNECT,
2935 "Reusing server socket %d connected to %s. Requests already sent: %u.",
2936 csp->server_connection.sfd, csp->server_connection.host,
2937 csp->server_connection.requests_sent_total);
2939 if (send_https_request(csp))
2942 * Most likely the server connection timed out. We can't easily
2943 * create a new one so simply drop the client connection without a
2944 * error response to let the client retry.
2946 log_error(LOG_LEVEL_CONNECT,
2947 "Dropping client connection on socket %d. "
2948 "Forwarding the encrypted client request failed.",
2952 csp->server_connection.requests_sent_total++;
2953 handle_established_connection(csp);
2954 freez(csp->receive_buffer);
2956 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2960 /*********************************************************************
2962 * Function : handle_established_connection
2964 * Description : Shuffle data between client and server once the
2965 * connection has been established.
2968 * 1 : csp = Current client state (buffers, headers, etc...)
2970 * Returns : Nothing.
2972 *********************************************************************/
2973 static void handle_established_connection(struct client_state *csp)
2979 struct pollfd poll_fds[2];
2983 struct timeval timeout;
2986 int ms_iis5_hack = 0;
2987 unsigned long long byte_count = 0;
2988 struct http_request *http;
2989 long len = 0; /* for buffer sizes (and negative error codes) */
2990 int buffer_and_filter_content = 0;
2991 unsigned int write_delay;
2992 #ifdef FEATURE_HTTPS_INSPECTION
2994 int use_ssl_tunnel = 0;
2995 csp->dont_verify_certificate = 0;
2997 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2999 /* Pass encrypted content without filtering. */
3004 /* Skeleton for HTTP response, if we should intercept the request */
3005 struct http_response *rsp;
3006 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3007 int watch_client_socket;
3010 csp->receive_buffer_size = csp->config->receive_buffer_size;
3011 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3012 if (csp->receive_buffer == NULL)
3014 log_error(LOG_LEVEL_ERROR,
3015 "Out of memory. Failed to allocate the receive buffer.");
3016 rsp = cgi_error_memory();
3017 send_crunch_response(csp, rsp);
3024 maxfd = (csp->cfd > csp->server_connection.sfd) ?
3025 csp->cfd : csp->server_connection.sfd;
3028 /* pass data between the client and server
3029 * until one or the other shuts down the connection.
3034 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3035 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3037 write_delay = get_write_delay(csp);
3043 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3044 if (!watch_client_socket)
3046 maxfd = csp->server_connection.sfd;
3049 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3051 FD_SET(csp->cfd, &rfds);
3054 FD_SET(csp->server_connection.sfd, &rfds);
3055 #endif /* ndef HAVE_POLL */
3057 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3058 if ((csp->flags & CSP_FLAG_CHUNKED)
3059 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3060 && ((csp->iob->eod - csp->iob->cur) >= 5)
3061 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3064 * XXX: This check should be obsolete now,
3065 * but let's wait a while to be sure.
3067 log_error(LOG_LEVEL_CONNECT,
3068 "Looks like we got the last chunk together with "
3069 "the server headers but didn't detect it earlier. "
3070 "We better stop reading.");
3071 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3072 csp->expected_content_length = byte_count;
3073 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3075 if (server_body && server_response_is_complete(csp, byte_count))
3077 if (csp->expected_content_length == byte_count)
3079 log_error(LOG_LEVEL_CONNECT,
3080 "Done reading from server. Content length: %llu as expected. "
3081 "Bytes most recently read: %ld.",
3086 log_error(LOG_LEVEL_CONNECT,
3087 "Done reading from server. Expected content length: %llu. "
3088 "Actual content length: %llu. Bytes most recently read: %ld.",
3089 csp->expected_content_length, byte_count, len);
3093 * XXX: Should not jump around, handle_established_connection()
3094 * is complicated enough already.
3098 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3101 poll_fds[0].fd = csp->cfd;
3102 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3103 if (!watch_client_socket)
3106 * Ignore incoming data, but still watch out
3107 * for disconnects etc. These flags are always
3108 * implied anyway but explicitly setting them
3111 poll_fds[0].events = POLLERR|POLLHUP;
3116 poll_fds[0].events = POLLIN;
3118 poll_fds[1].fd = csp->server_connection.sfd;
3119 poll_fds[1].events = POLLIN;
3120 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3122 timeout.tv_sec = csp->config->socket_timeout;
3123 timeout.tv_usec = 0;
3124 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3125 #endif /* def HAVE_POLL */
3127 /*server or client not responding in timeout */
3130 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3131 csp->config->socket_timeout, http->url);
3132 if ((byte_count == 0) && (http->ssl == 0))
3134 send_crunch_response(csp, error_response(csp, "connection-timeout"));
3136 mark_server_socket_tainted(csp);
3137 #ifdef FEATURE_HTTPS_INSPECTION
3138 close_client_and_server_ssl_connections(csp);
3145 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3147 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3149 mark_server_socket_tainted(csp);
3150 #ifdef FEATURE_HTTPS_INSPECTION
3151 close_client_and_server_ssl_connections(csp);
3157 * This is the body of the browser's request,
3158 * just read and write it.
3160 * Receives data from browser and sends it to server
3162 * XXX: Make sure the client doesn't use pipelining
3163 * behind Privoxy's back.
3166 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3168 log_error(LOG_LEVEL_CONNECT,
3169 "The client socket %d has become unusable while "
3170 "the server socket %d is still open.",
3171 csp->cfd, csp->server_connection.sfd);
3172 mark_server_socket_tainted(csp);
3176 if (poll_fds[0].revents != 0)
3178 if (FD_ISSET(csp->cfd, &rfds))
3179 #endif /* def HAVE_POLL*/
3181 int max_bytes_to_read = (int)csp->receive_buffer_size;
3183 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3184 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3186 if (data_is_available(csp->cfd, 0))
3189 * If the next request is already waiting, we have
3190 * to stop select()ing the client socket. Otherwise
3191 * we would always return right away and get nothing
3194 watch_client_socket = 0;
3195 log_error(LOG_LEVEL_CONNECT,
3196 "Stop watching client socket %d. "
3197 "There's already another request waiting.",
3202 * If the client socket is set, but there's no data
3203 * available on the socket, the client went fishing
3204 * and continuing talking to the server makes no sense.
3206 log_error(LOG_LEVEL_CONNECT,
3207 "The client closed socket %d while "
3208 "the server socket %d is still open.",
3209 csp->cfd, csp->server_connection.sfd);
3210 mark_server_socket_tainted(csp);
3213 if (csp->expected_client_content_length != 0)
3215 if (csp->expected_client_content_length < csp->receive_buffer_size)
3217 max_bytes_to_read = (int)csp->expected_client_content_length;
3219 log_error(LOG_LEVEL_CONNECT,
3220 "Waiting for up to %d bytes from the client.",
3223 assert(max_bytes_to_read <= csp->receive_buffer_size);
3224 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3226 #ifdef FEATURE_HTTPS_INSPECTION
3227 if (client_use_ssl(csp))
3229 if (csp->http->status == 101)
3231 len = ssl_recv_data(&(csp->ssl_client_attr),
3232 (unsigned char *)csp->receive_buffer,
3233 (size_t)max_bytes_to_read);
3236 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3237 "on client socket %d for an upgraded connection",
3243 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3244 "on client socket %d for an upgraded connection",
3248 byte_count += (unsigned long long)len;
3249 len = ssl_send_data(&(csp->ssl_server_attr),
3250 (unsigned char *)csp->receive_buffer, (size_t)len);
3253 log_error(LOG_LEVEL_ERROR, "Failed to send data "
3254 "on server socket %d for an upgraded connection",
3255 csp->server_connection.sfd);
3260 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3264 #endif /* def FEATURE_HTTPS_INSPECTION */
3266 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3270 /* XXX: not sure if this is necessary. */
3271 mark_server_socket_tainted(csp);
3272 break; /* "game over, man" */
3275 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3276 if (csp->expected_client_content_length != 0)
3278 assert(len <= max_bytes_to_read);
3279 csp->expected_client_content_length -= (unsigned)len;
3280 log_error(LOG_LEVEL_CONNECT,
3281 "Expected client content length set to %llu "
3282 "after reading %ld bytes.",
3283 csp->expected_client_content_length, len);
3284 if (csp->expected_client_content_length == 0)
3286 log_error(LOG_LEVEL_CONNECT,
3287 "Done reading from the client.");
3288 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3291 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3293 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3295 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3296 mark_server_socket_tainted(csp);
3304 * The server wants to talk. It could be the header or the body.
3305 * If `hdr' is null, then it's the header otherwise it's the body.
3306 * FIXME: Does `hdr' really mean `host'? No.
3309 if (poll_fds[1].revents != 0)
3311 if (FD_ISSET(csp->server_connection.sfd, &rfds))
3312 #endif /* HAVE_POLL */
3314 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3316 * If we are buffering content, we don't want to eat up to
3317 * buffer-limit bytes if the client no longer cares about them.
3318 * If we aren't buffering, however, a dead client socket will be
3319 * noticed pretty much right away anyway, so we can reduce the
3320 * overhead by skipping the check.
3322 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3325 log_error(LOG_LEVEL_CONNECT,
3326 "The server still wants to talk, but the client may already have hung up on us.");
3328 log_error(LOG_LEVEL_CONNECT,
3329 "The server still wants to talk, but the client hung up on us.");
3330 mark_server_socket_tainted(csp);
3331 #ifdef FEATURE_HTTPS_INSPECTION
3332 close_client_and_server_ssl_connections(csp);
3335 #endif /* def _WIN32 */
3337 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3339 #ifdef FEATURE_HTTPS_INSPECTION
3341 * Reading data from standard or secured connection (HTTP/HTTPS)
3343 if (server_use_ssl(csp))
3345 len = ssl_recv_data(&(csp->ssl_server_attr),
3346 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3351 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3352 (int)csp->receive_buffer_size);
3357 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3359 if ((http->ssl && (csp->fwd == NULL))
3360 #ifdef FEATURE_HTTPS_INSPECTION
3366 * Just hang up. We already confirmed the client's CONNECT
3367 * request with status code 200 and unencrypted content is
3368 * no longer welcome.
3370 log_error(LOG_LEVEL_ERROR,
3371 "CONNECT already confirmed. Unable to tell the client about the problem.");
3374 else if (byte_count)
3377 * Just hang up. We already transmitted the original headers
3378 * and parts of the original content and therefore missed the
3379 * chance to send an error message (without risking data corruption).
3381 * XXX: we could retry with a fancy range request here.
3383 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3384 "Unable to tell the client about the problem.");
3385 mark_server_socket_tainted(csp);
3386 #ifdef FEATURE_HTTPS_INSPECTION
3387 close_client_and_server_ssl_connections(csp);
3392 * XXX: Consider handling the cases above the same.
3394 mark_server_socket_tainted(csp);
3398 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3399 if (csp->flags & CSP_FLAG_CHUNKED)
3401 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3403 /* XXX: this is a temporary hack */
3404 log_error(LOG_LEVEL_CONNECT,
3405 "Looks like we reached the end of the last chunk. "
3406 "We better stop reading.");
3407 csp->expected_content_length = byte_count + (unsigned long long)len;
3408 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3412 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3415 * This is guaranteed by allocating with zalloc_or_die()
3416 * and never (intentionally) writing to the last byte.
3418 * csp->receive_buffer_size is the size of the part of the
3419 * buffer we intentionally write to, but we actually
3420 * allocated csp->receive_buffer_size+1 bytes so the assertion
3421 * stays within the allocated range.
3423 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3426 * Add a trailing zero to let be able to use string operations.
3427 * XXX: do we still need this with filter_popups gone?
3429 assert(len <= csp->receive_buffer_size);
3430 csp->receive_buffer[len] = '\0';
3433 * Normally, this would indicate that we've read
3434 * as much as the server has sent us and we can
3435 * close the client connection. However, Microsoft
3436 * in its wisdom has released IIS/5 with a bug that
3437 * prevents it from sending the trailing \r\n in
3438 * a 302 redirect header (and possibly other headers).
3439 * To work around this if we've haven't parsed
3440 * a full header we'll append a trailing \r\n
3441 * and see if this now generates a valid one.
3443 * This hack shouldn't have any impacts. If we've
3444 * already transmitted the header or if this is a
3445 * SSL connection, then we won't bother with this
3446 * hack. So we only work on partially received
3447 * headers. If we append a \r\n and this still
3448 * doesn't generate a valid header, then we won't
3449 * transmit anything to the client.
3454 if (server_body || (http->ssl
3455 #ifdef FEATURE_HTTPS_INSPECTION
3461 * If we have been buffering up the document,
3462 * now is the time to apply content modification
3463 * and send the result to the client.
3465 if (buffer_and_filter_content)
3467 p = execute_content_filters(csp);
3469 * If content filtering fails, use the original
3470 * buffer and length.
3471 * (see p != NULL ? p : csp->iob->cur below)
3475 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3477 #ifdef FEATURE_COMPRESSION
3478 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3479 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3481 char *compressed_content = compress_buffer(p,
3482 (size_t *)&csp->content_length, csp->config->compression_level);
3483 if (compressed_content != NULL)
3486 p = compressed_content;
3487 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3492 if (JB_ERR_OK != update_server_headers(csp))
3494 log_error(LOG_LEVEL_FATAL,
3495 "Failed to update server headers. after filtering.");
3498 hdr = list_to_text(csp->headers);
3501 /* FIXME Should handle error properly */
3502 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3505 #ifdef FEATURE_HTTPS_INSPECTION
3507 * Sending data with standard or secured connection (HTTP/HTTPS)
3509 if (client_use_ssl(csp))
3511 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3512 (const unsigned char *)hdr, strlen(hdr),
3513 get_write_delay(csp)) < 0)
3514 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3515 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3516 csp->content_length, get_write_delay(csp)) < 0))
3518 log_error(LOG_LEVEL_ERROR, "write modified content to "
3519 "client over TLS/SSL failed");
3522 mark_server_socket_tainted(csp);
3523 close_client_and_server_ssl_connections(csp);
3528 #endif /* def FEATURE_HTTPS_INSPECTION */
3530 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3531 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3532 (size_t)csp->content_length, write_delay))
3534 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3537 mark_server_socket_tainted(csp);
3546 break; /* "game over, man" */
3550 * This is NOT the body, so
3551 * Let's pretend the server just sent us a blank line.
3553 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3554 len = (int)strlen(csp->receive_buffer);
3557 * Now, let the normal header parsing algorithm below do its
3558 * job. If it fails, we'll exit instead of continuing.
3565 * If we're in the body of the server document, just write it to
3566 * the client, unless we need to buffer the body for later
3567 * content-filtering.
3569 if (server_body || (http->ssl
3570 #ifdef FEATURE_HTTPS_INSPECTION
3575 if (buffer_and_filter_content)
3578 * If there is no memory left for buffering the content, or the buffer limit
3579 * has been reached, switch to non-filtering mode, i.e. make & write the
3580 * header, flush the iob and buf, and get out of the way.
3582 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3587 log_error(LOG_LEVEL_INFO,
3588 "Flushing header and buffers. Stepping back from filtering.");
3590 hdr = list_to_text(csp->headers);
3594 * Memory is too tight to even generate the header.
3595 * Send our static "Out-of-memory" page.
3597 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3598 rsp = cgi_error_memory();
3599 send_crunch_response(csp, rsp);
3600 mark_server_socket_tainted(csp);
3601 #ifdef FEATURE_HTTPS_INSPECTION
3602 close_client_and_server_ssl_connections(csp);
3606 hdrlen = strlen(hdr);
3608 #ifdef FEATURE_HTTPS_INSPECTION
3610 * Sending data with standard or secured connection (HTTP/HTTPS)
3612 if (client_use_ssl(csp))
3614 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3615 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3616 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3618 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3619 (const unsigned char *)csp->receive_buffer, (size_t)len,
3620 get_write_delay(csp)) < 0))
3622 log_error(LOG_LEVEL_CONNECT,
3623 "Flush header and buffers to client failed");
3625 mark_server_socket_tainted(csp);
3626 close_client_and_server_ssl_connections(csp);
3631 #endif /* def FEATURE_HTTPS_INSPECTION */
3633 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3634 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3635 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3638 log_error(LOG_LEVEL_CONNECT,
3639 "Flush header and buffers to client failed: %E");
3641 mark_server_socket_tainted(csp);
3647 * Reset the byte_count to the amount of bytes
3648 * we just flushed. len will be added a few lines below,
3649 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3651 byte_count = (unsigned long long)flushed;
3653 buffer_and_filter_content = 0;
3659 #ifdef FEATURE_HTTPS_INSPECTION
3661 * Sending data with standard or secured connection (HTTP/HTTPS)
3663 if (client_use_ssl(csp))
3665 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3666 (const unsigned char *)csp->receive_buffer, (size_t)len,
3667 get_write_delay(csp));
3670 log_error(LOG_LEVEL_ERROR,
3671 "Sending data to client failed");
3672 mark_server_socket_tainted(csp);
3673 close_client_and_server_ssl_connections(csp);
3678 #endif /* def FEATURE_HTTPS_INSPECTION */
3680 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3681 (size_t)len, write_delay))
3683 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3684 mark_server_socket_tainted(csp);
3689 byte_count += (unsigned long long)len;
3695 * We're still looking for the end of the server's header.
3696 * Buffer up the data we just read. If that fails, there's
3697 * little we can do but send our static out-of-memory page.
3699 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3701 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3702 rsp = cgi_error_memory();
3703 send_crunch_response(csp, rsp);
3704 mark_server_socket_tainted(csp);
3705 #ifdef FEATURE_HTTPS_INSPECTION
3706 close_client_and_server_ssl_connections(csp);
3711 /* Convert iob into something sed() can digest */
3712 if (JB_ERR_PARSE == get_server_headers(csp))
3717 * Well, we tried our MS IIS/5 hack and it didn't work.
3718 * The header is incomplete and there isn't anything
3719 * we can do about it.
3721 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3722 "Applying the MS IIS5 hack didn't help.");
3723 log_error(LOG_LEVEL_CLF,
3724 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3725 #ifdef FEATURE_HTTPS_INSPECTION
3727 * Sending data with standard or secured connection (HTTP/HTTPS)
3729 if (client_use_ssl(csp))
3731 ssl_send_data_delayed(&(csp->ssl_client_attr),
3732 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3733 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3736 #endif /* def FEATURE_HTTPS_INSPECTION */
3738 write_socket_delayed(csp->cfd,
3739 INVALID_SERVER_HEADERS_RESPONSE,
3740 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3742 mark_server_socket_tainted(csp);
3743 #ifdef FEATURE_HTTPS_INSPECTION
3744 close_client_and_server_ssl_connections(csp);
3751 * Since we have to wait for more from the server before
3752 * we can parse the headers we just continue here.
3754 log_error(LOG_LEVEL_CONNECT,
3755 "Continuing buffering server headers from socket %d. "
3756 "Bytes most recently read: %ld.", csp->cfd, len);
3763 * Account for the content bytes we
3764 * might have gotten with the headers.
3766 assert(csp->iob->eod >= csp->iob->cur);
3767 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3770 /* Did we actually get anything? */
3771 if (NULL == csp->headers->first)
3773 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3775 log_error(LOG_LEVEL_ERROR,
3776 "No server or forwarder response received on socket %d. "
3777 "Closing client socket %d without sending data.",
3778 csp->server_connection.sfd, csp->cfd);
3779 log_error(LOG_LEVEL_CLF,
3780 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3784 log_error(LOG_LEVEL_ERROR,
3785 "No server or forwarder response received on socket %d.",
3786 csp->server_connection.sfd);
3787 send_crunch_response(csp, error_response(csp, "no-server-data"));
3789 free_http_request(http);
3790 mark_server_socket_tainted(csp);
3791 #ifdef FEATURE_HTTPS_INSPECTION
3792 close_client_and_server_ssl_connections(csp);
3797 if (!csp->headers->first->str)
3799 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3801 assert(csp->headers->first->str);
3803 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3804 strncmpic(csp->headers->first->str, "ICY", 3))
3807 * It doesn't look like a HTTP (or Shoutcast) response:
3808 * tell the client and log the problem.
3810 if (strlen(csp->headers->first->str) > 30)
3812 csp->headers->first->str[30] = '\0';
3814 log_error(LOG_LEVEL_ERROR,
3815 "Invalid server or forwarder response. Starts with: %s",
3816 csp->headers->first->str);
3817 log_error(LOG_LEVEL_CLF,
3818 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3819 #ifdef FEATURE_HTTPS_INSPECTION
3821 * Sending data with standard or secured connection (HTTP/HTTPS)
3823 if (client_use_ssl(csp))
3825 ssl_send_data_delayed(&(csp->ssl_client_attr),
3826 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3827 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3828 get_write_delay(csp));
3831 #endif /* def FEATURE_HTTPS_INSPECTION */
3833 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3834 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3836 free_http_request(http);
3837 mark_server_socket_tainted(csp);
3838 #ifdef FEATURE_HTTPS_INSPECTION
3839 close_client_and_server_ssl_connections(csp);
3845 * We have now received the entire server header,
3846 * filter it and send the result to the client
3848 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3850 log_error(LOG_LEVEL_CLF,
3851 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3852 #ifdef FEATURE_HTTPS_INSPECTION
3854 * Sending data with standard or secured connection (HTTP/HTTPS)
3856 if (client_use_ssl(csp))
3858 ssl_send_data_delayed(&(csp->ssl_client_attr),
3859 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3860 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3861 get_write_delay(csp));
3866 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3867 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3869 free_http_request(http);
3870 mark_server_socket_tainted(csp);
3871 #ifdef FEATURE_HTTPS_INSPECTION
3872 close_client_and_server_ssl_connections(csp);
3876 hdr = list_to_text(csp->headers);
3879 /* FIXME Should handle error properly */
3880 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3883 if ((csp->flags & CSP_FLAG_CHUNKED)
3884 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3885 && ((csp->iob->eod - csp->iob->cur) >= 5)
3886 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3888 log_error(LOG_LEVEL_CONNECT,
3889 "Looks like we got the last chunk together with "
3890 "the server headers. We better stop reading.");
3891 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3892 csp->expected_content_length = byte_count;
3893 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3896 csp->server_connection.response_received = time(NULL);
3898 if (crunch_response_triggered(csp, crunchers_light))
3901 * One of the tags created by a server-header
3902 * tagger triggered a crunch. We already
3903 * delivered the crunch response to the client
3904 * and are done here after cleaning up.
3907 mark_server_socket_tainted(csp);
3908 #ifdef FEATURE_HTTPS_INSPECTION
3909 close_client_and_server_ssl_connections(csp);
3914 /* Buffer and pcrs filter this if appropriate. */
3915 buffer_and_filter_content = content_requires_filtering(csp);
3917 if (!buffer_and_filter_content)
3920 * Write the server's (modified) header to
3921 * the client (along with anything else that
3922 * may be in the buffer). Use standard or secured
3925 #ifdef FEATURE_HTTPS_INSPECTION
3926 if (client_use_ssl(csp))
3928 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3929 (const unsigned char *)hdr, strlen(hdr),
3930 get_write_delay(csp)) < 0)
3931 || (len = ssl_flush_socket(&(csp->ssl_client_attr),
3934 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3937 * The write failed, so don't bother mentioning it
3938 * to the client... it probably can't hear us anyway.
3941 mark_server_socket_tainted(csp);
3942 #ifdef FEATURE_HTTPS_INSPECTION
3943 close_client_and_server_ssl_connections(csp);
3949 #endif /* def FEATURE_HTTPS_INSPECTION */
3951 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3952 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3954 log_error(LOG_LEVEL_ERROR,
3955 "write header to client failed");
3957 * The write failed, so don't bother mentioning it
3958 * to the client... it probably can't hear us anyway.
3961 mark_server_socket_tainted(csp);
3967 /* we're finished with the server's header */
3973 * If this was a MS IIS/5 hack then it means the server
3974 * has already closed the connection. Nothing more to read.
3979 log_error(LOG_LEVEL_ERROR,
3980 "Closed server connection detected. "
3981 "Applying the MS IIS5 hack didn't help.");
3982 log_error(LOG_LEVEL_CLF,
3983 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3984 #ifdef FEATURE_HTTPS_INSPECTION
3986 * Sending data with standard or secured connection (HTTP/HTTPS)
3988 if (client_use_ssl(csp))
3990 ssl_send_data_delayed(&(csp->ssl_client_attr),
3991 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3992 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3993 get_write_delay(csp));
3996 #endif /* def FEATURE_HTTPS_INSPECTION */
3998 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3999 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4001 mark_server_socket_tainted(csp);
4002 #ifdef FEATURE_HTTPS_INSPECTION
4003 close_client_and_server_ssl_connections(csp);
4010 mark_server_socket_tainted(csp);
4011 #ifdef FEATURE_HTTPS_INSPECTION
4012 close_client_and_server_ssl_connections(csp);
4014 return; /* huh? we should never get here */
4017 if (csp->content_length == 0)
4020 * If Privoxy didn't recalculate the Content-Length,
4021 * byte_count is still correct.
4023 csp->content_length = byte_count;
4026 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4027 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4028 && (csp->expected_content_length != byte_count))
4030 log_error(LOG_LEVEL_CONNECT,
4031 "Received %llu bytes while expecting %llu.",
4032 byte_count, csp->expected_content_length);
4033 mark_server_socket_tainted(csp);
4037 #ifdef FEATURE_HTTPS_INSPECTION
4038 if (client_use_ssl(csp))
4040 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4041 csp->ip_addr_str, http->gpc, http->hostport, http->path,
4042 http->version, csp->content_length);
4047 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4048 csp->ip_addr_str, http->ocmd, csp->content_length);
4050 csp->server_connection.timestamp = time(NULL);
4054 /*********************************************************************
4058 * Description : Once a connection from the client has been accepted,
4059 * this function is called (via serve()) to handle the
4060 * main business of the communication. This function
4061 * returns after dealing with a single request. It can
4062 * be called multiple times with the same client socket
4063 * if the client is keeping the connection alive.
4065 * The decision whether or not a client connection will
4066 * be kept alive is up to the caller which also must
4067 * close the client socket when done.
4069 * FIXME: chat is nearly thousand lines long.
4073 * 1 : csp = Current client state (buffers, headers, etc...)
4075 * Returns : Nothing.
4077 *********************************************************************/
4078 static void chat(struct client_state *csp)
4080 const struct forward_spec *fwd;
4081 struct http_request *http;
4082 /* Skeleton for HTTP response, if we should intercept the request */
4083 struct http_response *rsp;
4084 #ifdef FEATURE_HTTPS_INSPECTION
4085 int use_ssl_tunnel = 0;
4090 if (receive_client_request(csp) != JB_ERR_OK)
4094 if (parse_client_request(csp) != JB_ERR_OK)
4099 /* decide how to route the HTTP request */
4100 fwd = forward_url(csp, http);
4102 #ifdef FEATURE_HTTPS_INSPECTION
4104 * Setting flags to use old solution with SSL tunnel and to disable
4105 * certificate verification.
4107 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4108 && !cgi_page_requested(csp->http->host))
4113 if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4115 csp->dont_verify_certificate = 1;
4120 * build the http request to send to the server
4121 * we have to do one of the following:
4123 * create = use the original HTTP request to create a new
4124 * HTTP request that has either the path component
4125 * without the http://domainspec (w/path) or the
4126 * full orininal URL (w/url)
4127 * Note that the path and/or the HTTP version may
4128 * have been altered by now.
4130 * SSL proxy = Open a socket to the host:port of the server
4131 * and create TLS/SSL connection with server and
4132 * with client. Then behave like mediator between
4133 * client and server over TLS/SSL.
4135 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4136 * with request to a parent proxy. Note that we'll be sending
4137 * forwarding the CFAIL message ourselves if connecting to the parent
4138 * fails, but we won't send a CSUCCEED message if it works,
4139 * since that would result in a double message (ours and the
4140 * parent's). After sending the request to the parent, we
4141 * must parse answer and send it to client. If connection
4142 * with server is established, we do TLS/SSL proxy. Otherwise
4143 * we send parent response to client and close connections.
4145 * here's the matrix:
4148 * +--------+--------+
4150 * 0 | create | SSL |
4151 * | w/path | proxy |
4152 * Forwarding +--------+--------+
4154 * 1 | create | proxy |
4155 * | w/url |+forward|
4156 * +--------+--------+
4160 #ifdef FEATURE_HTTPS_INSPECTION
4162 * Presetting SSL client and server flags
4164 if (http->ssl && !use_ssl_tunnel)
4166 http->client_ssl = 1;
4167 http->server_ssl = 1;
4171 http->client_ssl = 0;
4172 http->server_ssl = 0;
4176 #ifdef FEATURE_HTTPS_INSPECTION
4178 * Log the request unless we're https inspecting
4179 * in which case we don't have the path yet and
4180 * will log the request later.
4182 if (!client_use_ssl(csp))
4185 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4188 if (http->ssl && connect_port_is_forbidden(csp))
4190 const char *acceptable_connect_ports =
4191 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4192 assert(NULL != acceptable_connect_ports);
4193 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4194 "limit-connect{%s} doesn't allow CONNECT requests to %s",
4195 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4196 csp->action->flags |= ACTION_BLOCK;
4198 #ifdef FEATURE_HTTPS_INSPECTION
4199 http->client_ssl = 0;
4200 http->server_ssl = 0;
4205 freez(csp->headers->first->str);
4206 build_request_line(csp, fwd, &csp->headers->first->str);
4209 * We have a request. Check if one of the crunchers wants it
4210 * unless the client wants to use TLS/SSL in which case we
4211 * haven't setup the TLS context yet and will send the crunch
4215 #ifdef FEATURE_HTTPS_INSPECTION
4216 !client_use_ssl(csp) &&
4218 crunch_response_triggered(csp, crunchers_all))
4221 * Yes. The client got the crunch response and we're done here.
4226 log_applied_actions(csp->action);
4227 if (fwd->forward_host)
4229 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4230 fwd->forward_host, fwd->forward_port, http->hostport);
4234 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4237 /* here we connect to the server, gateway, or the forwarder */
4239 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4240 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4241 && socket_is_still_alive(csp->server_connection.sfd)
4242 && connection_destination_matches(&csp->server_connection, http, fwd))
4244 log_error(LOG_LEVEL_CONNECT,
4245 "Reusing server socket %d connected to %s. Total requests: %u.",
4246 csp->server_connection.sfd, csp->server_connection.host,
4247 csp->server_connection.requests_sent_total);
4251 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4253 #ifdef FEATURE_CONNECTION_SHARING
4254 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4255 #ifdef FEATURE_HTTPS_INSPECTION
4256 && !server_use_ssl(csp)
4260 remember_connection(&csp->server_connection);
4263 #endif /* def FEATURE_CONNECTION_SHARING */
4265 log_error(LOG_LEVEL_CONNECT,
4266 "Closing server socket %d connected to %s. Total requests: %u.",
4267 csp->server_connection.sfd, csp->server_connection.host,
4268 csp->server_connection.requests_sent_total);
4269 close_socket(csp->server_connection.sfd);
4271 mark_connection_closed(&csp->server_connection);
4273 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4274 #ifdef FEATURE_HTTPS_INSPECTION
4275 if (client_use_ssl(csp) && !use_ssl_tunnel)
4279 * Creating a SSL proxy.
4281 * By sending the CSUCCEED message we're lying to the client as
4282 * the connection hasn't actually been established yet. We don't
4283 * establish the connection until we have seen and parsed the
4284 * encrypted client headers.
4286 if (write_socket_delayed(csp->cfd, CSUCCEED,
4287 strlen(CSUCCEED), get_write_delay(csp)) != 0)
4289 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4293 ret = create_client_ssl_connection(csp);
4296 log_error(LOG_LEVEL_ERROR,
4297 "Failed to open a secure connection with the client");
4300 if (JB_ERR_OK != process_encrypted_request(csp))
4302 close_client_ssl_connection(csp);
4306 * We have an encrypted request. Check if one of the crunchers now
4307 * wants it (for example because the previously invisible path was
4308 * required to match).
4310 if (crunch_response_triggered(csp, crunchers_all))
4313 * Yes. The client got the crunch response and we're done here.
4320 * Connecting to destination server
4322 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4324 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4326 if (fwd->type != SOCKS_NONE)
4329 rsp = error_response(csp, "forwarding-failed");
4331 else if (errno == EINVAL)
4333 rsp = error_response(csp, "no-such-domain");
4337 rsp = error_response(csp, "connect-failed");
4340 /* Write the answer to the client */
4343 send_crunch_response(csp, rsp);
4347 * Temporary workaround to prevent already-read client
4348 * bodies from being parsed as new requests. For now we
4349 * err on the safe side and throw all the following
4350 * requests under the bus, even if no client body has been
4351 * buffered. A compliant client will repeat the dropped
4352 * requests on an untainted connection.
4354 * The proper fix is to discard the no longer needed
4355 * client body in the buffer (if there is one) and to
4356 * continue parsing the bytes that follow.
4358 #ifdef FEATURE_HTTPS_INSPECTION
4359 close_client_ssl_connection(csp);
4361 drain_and_close_socket(csp->cfd);
4362 csp->cfd = JB_INVALID_SOCKET;
4367 #ifdef FEATURE_HTTPS_INSPECTION
4369 * Creating TLS/SSL connections with destination server or parent
4370 * proxy. If forwarding is enabled, we must send client request to
4371 * parent proxy and receive, parse and resend parent proxy answer.
4373 if (http->ssl && !use_ssl_tunnel)
4375 if (fwd->forward_host != NULL)
4377 char server_response[BUFFER_SIZE];
4380 char *hdr = list_to_text(csp->headers);
4381 memset(server_response, 0, sizeof(server_response));
4385 log_error(LOG_LEVEL_FATAL,
4386 "Out of memory parsing client header");
4388 list_remove_all(csp->headers);
4391 * Sending client's CONNECT request to the parent proxy
4393 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4399 log_error(LOG_LEVEL_CONNECT,
4400 "Sending request headers to: %s failed", http->hostport);
4401 mark_server_socket_tainted(csp);
4402 close_client_ssl_connection(csp);
4406 /* Waiting for parent proxy server response */
4407 len = read_socket(csp->server_connection.sfd, server_response,
4408 sizeof(server_response)-1);
4412 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4413 "server on socket %d.", csp->server_connection.sfd);
4415 rsp = error_response(csp, "no-server-data");
4418 send_crunch_response(csp, rsp);
4420 mark_server_socket_tainted(csp);
4421 close_client_ssl_connection(csp);
4426 * Test if the connection to the destination server was
4427 * established successfully by the parent proxy.
4429 if (!tunnel_established_successfully(server_response, (unsigned int)len))
4431 log_error(LOG_LEVEL_ERROR,
4432 "The forwarder %s failed to establish a connection with %s",
4433 fwd->forward_host, http->host);
4434 rsp = error_response(csp, "connect-failed");
4437 send_crunch_response(csp, rsp);
4439 mark_server_socket_tainted(csp);
4440 close_client_ssl_connection(csp);
4443 } /* -END- if (fwd->forward_host != NULL) */
4446 * We can now create the TLS/SSL connection with the destination server.
4448 int ret = create_server_ssl_connection(csp);
4451 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4452 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4455 * If the server certificate is invalid, we must inform
4456 * the client and then close connection to the client.
4458 ssl_send_certificate_error(csp);
4459 close_client_and_server_ssl_connections(csp);
4462 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4463 || csp->server_cert_verification_result == SSL_CERT_VALID)
4466 * The TLS/SSL connection wasn't created but an invalid
4467 * certificate wasn't detected. Report it as connection
4470 rsp = error_response(csp, "connect-failed");
4473 send_crunch_response(csp, rsp);
4475 close_client_and_server_ssl_connections(csp);
4479 }/* -END- if (http->ssl) */
4480 #endif /* def FEATURE_HTTPS_INSPECTION */
4482 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4483 save_connection_destination(csp->server_connection.sfd,
4484 http, fwd, &csp->server_connection);
4485 csp->server_connection.keep_alive_timeout =
4486 (unsigned)csp->config->keep_alive_timeout;
4488 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4490 csp->server_connection.requests_sent_total++;
4492 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4494 /* Client headers have been sent optimistically */
4495 assert(csp->headers->last == NULL);
4497 else if (http->ssl == 0 || (fwd->forward_host
4498 #ifdef FEATURE_HTTPS_INSPECTION
4503 if (send_http_request(csp))
4505 rsp = error_response(csp, "connect-failed");
4508 send_crunch_response(csp, rsp);
4516 * Using old solution with SSL tunnel or new solution with SSL proxy
4518 list_remove_all(csp->headers);
4519 #ifdef FEATURE_HTTPS_INSPECTION
4524 * We're running an SSL tunnel and we're not forwarding,
4525 * so just ditch the client headers, send the "connect succeeded"
4526 * message to the client, flush the rest, and get out of the way.
4528 if (write_socket_delayed(csp->cfd, CSUCCEED,
4529 strlen(CSUCCEED), get_write_delay(csp)))
4534 #ifdef FEATURE_HTTPS_INSPECTION
4538 * If server certificate has been verified and is invalid,
4539 * we must inform the client and then close the connection
4540 * with client and server.
4542 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4543 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4545 ssl_send_certificate_error(csp);
4546 close_client_and_server_ssl_connections(csp);
4549 if (send_https_request(csp))
4551 rsp = error_response(csp, "connect-failed");
4554 send_crunch_response(csp, rsp);
4556 close_client_and_server_ssl_connections(csp);
4560 #endif /* def FEATURE_HTTPS_INSPECTION */
4561 clear_iob(csp->client_iob);
4562 }/* -END- else ... if (http->ssl == 1) */
4564 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4566 /* XXX: should the time start earlier for optimistically sent data? */
4567 csp->server_connection.request_sent = time(NULL);
4569 handle_established_connection(csp);
4570 freez(csp->receive_buffer);
4575 /*********************************************************************
4577 * Function : fuzz_server_response
4579 * Description : Treat the input as a whole server response.
4582 * 1 : csp = Current client state (buffers, headers, etc...)
4583 * 2 : fuzz_input_file = File to read the input from.
4587 *********************************************************************/
4588 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4590 static struct forward_spec fwd; /* Zero'd due to being static */
4593 if (strcmp(fuzz_input_file, "-") == 0)
4595 /* XXX: Doesn't work yet. */
4596 csp->server_connection.sfd = 0;
4600 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4601 if (csp->server_connection.sfd == -1)
4603 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4608 csp->content_type |= CT_GIF;
4609 csp->action->flags |= ACTION_DEANIMATE;
4610 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4612 csp->http->path = strdup_or_die("/");
4613 csp->http->host = strdup_or_die("fuzz.example.org");
4614 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4615 /* Prevent client socket monitoring */
4616 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4617 csp->flags |= CSP_FLAG_CHUNKED;
4619 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4620 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4622 csp->content_type |= CT_DECLARED|CT_GIF;
4624 csp->config->socket_timeout = 0;
4626 cgi_init_error_messages();
4628 handle_established_connection(csp);
4629 freez(csp->receive_buffer);
4636 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4637 /*********************************************************************
4639 * Function : prepare_csp_for_next_request
4641 * Description : Put the csp in a mostly vergin state.
4644 * 1 : csp = Current client state (buffers, headers, etc...)
4648 *********************************************************************/
4649 static void prepare_csp_for_next_request(struct client_state *csp)
4651 csp->content_type = 0;
4652 csp->content_length = 0;
4653 csp->expected_content_length = 0;
4654 csp->expected_client_content_length = 0;
4655 list_remove_all(csp->headers);
4656 clear_iob(csp->iob);
4657 freez(csp->error_message);
4658 free_http_request(csp->http);
4659 destroy_list(csp->headers);
4660 #ifdef FEATURE_HTTPS_INSPECTION
4661 destroy_list(csp->https_headers);
4663 destroy_list(csp->tags);
4664 #ifdef FEATURE_CLIENT_TAGS
4665 destroy_list(csp->client_tags);
4666 freez(csp->client_address);
4668 free_current_action(csp->action);
4669 if (NULL != csp->fwd)
4671 unload_forward_spec(csp->fwd);
4674 /* XXX: Store per-connection flags someplace else. */
4675 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4676 #ifdef FEATURE_TOGGLE
4677 if (global_toggle_state)
4678 #endif /* def FEATURE_TOGGLE */
4680 csp->flags |= CSP_FLAG_TOGGLED_ON;
4683 if (csp->client_iob->eod > csp->client_iob->cur)
4685 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4686 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4688 assert(bytes_to_shift > 0);
4689 assert(data_length > 0);
4691 log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4692 data_length, bytes_to_shift);
4693 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4694 csp->client_iob->cur = csp->client_iob->buf;
4695 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4696 csp->client_iob->eod = csp->client_iob->buf + data_length;
4697 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4699 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4704 * We mainly care about resetting client_iob->cur so we don't
4705 * waste buffer space at the beginning and don't mess up the
4706 * request restoration done by cgi_show_request().
4708 * Freeing the buffer itself isn't technically necessary,
4709 * but makes debugging more convenient.
4711 clear_iob(csp->client_iob);
4714 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4717 /*********************************************************************
4721 * Description : This is little more than chat. We only "serve" to
4722 * to close (or remember) any socket that chat may have
4726 * 1 : csp = Current client state (buffers, headers, etc...)
4730 *********************************************************************/
4731 static void serve(struct client_state *csp)
4733 int config_file_change_detected = 0; /* Only used for debugging */
4734 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4735 #ifdef FEATURE_CONNECTION_SHARING
4736 static int monitor_thread_running = 0;
4737 #endif /* def FEATURE_CONNECTION_SHARING */
4738 int continue_chatting = 0;
4740 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4741 csp->ip_addr_str, csp->cfd);
4745 unsigned int latency;
4747 #ifdef FEATURE_HTTPS_INSPECTION
4748 if (continue_chatting && client_use_ssl(csp))
4750 continue_https_chat(csp);
4759 * If the request has been crunched,
4760 * the calculated latency is zero.
4762 latency = (unsigned)(csp->server_connection.response_received -
4763 csp->server_connection.request_sent) / 2;
4765 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4766 && (csp->flags & CSP_FLAG_CRUNCHED)
4767 && (csp->expected_client_content_length != 0))
4769 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4770 log_error(LOG_LEVEL_CONNECT,
4771 "Tainting client socket %d due to unread data.", csp->cfd);
4774 continue_chatting = (csp->config->feature_flags
4775 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4776 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4777 && (csp->cfd != JB_INVALID_SOCKET)
4778 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4779 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4780 || (csp->flags & CSP_FLAG_CHUNKED));
4782 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4783 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4785 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4787 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4789 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4790 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4791 || !socket_is_still_alive(csp->server_connection.sfd)
4792 || !(latency < csp->server_connection.keep_alive_timeout))
4794 log_error(LOG_LEVEL_CONNECT,
4795 "Closing server socket %d connected to %s. "
4796 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4797 csp->server_connection.sfd, csp->server_connection.host,
4798 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4799 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4800 socket_is_still_alive(csp->server_connection.sfd),
4801 csp->server_connection.keep_alive_timeout);
4802 #ifdef FEATURE_CONNECTION_SHARING
4803 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4805 forget_connection(csp->server_connection.sfd);
4807 #endif /* def FEATURE_CONNECTION_SHARING */
4808 #ifdef FEATURE_HTTPS_INSPECTION
4809 close_server_ssl_connection(csp);
4811 close_socket(csp->server_connection.sfd);
4812 mark_connection_closed(&csp->server_connection);
4816 if (continue_chatting && any_loaded_file_changed(csp))
4818 continue_chatting = 0;
4819 config_file_change_detected = 1;
4821 #ifdef FEATURE_HTTPS_INSPECTION
4822 if (continue_chatting && client_use_ssl(csp) &&
4823 csp->ssl_with_client_is_opened == 0)
4825 continue_chatting = 0;
4826 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4827 "The TLS session has been terminated.", csp->cfd);
4831 if (continue_chatting)
4833 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4834 && socket_is_still_alive(csp->cfd))
4836 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4837 "pipelined on socket %d and the socket is still alive.",
4838 csp->requests_received_total+1, csp->cfd);
4839 prepare_csp_for_next_request(csp);
4843 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4845 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4847 log_error(LOG_LEVEL_CONNECT,
4848 "Waiting for the next client request on socket %d. "
4849 "Keeping the server socket %d to %s open.",
4850 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4854 log_error(LOG_LEVEL_CONNECT,
4855 "Waiting for the next client request on socket %d. "
4856 "No server socket to keep open.", csp->cfd);
4860 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4861 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4862 && socket_is_still_alive(csp->cfd))
4864 log_error(LOG_LEVEL_CONNECT,
4865 "Data arrived in time on client socket %d. Requests so far: %u",
4866 csp->cfd, csp->requests_received_total);
4867 prepare_csp_for_next_request(csp);
4871 #ifdef FEATURE_CONNECTION_SHARING
4872 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4873 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4874 && (socket_is_still_alive(csp->server_connection.sfd))
4875 #ifdef FEATURE_HTTPS_INSPECTION
4876 && !server_use_ssl(csp)
4880 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4882 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4887 remember_connection(&csp->server_connection);
4888 csp->server_connection.sfd = JB_INVALID_SOCKET;
4889 drain_and_close_socket(csp->cfd);
4890 csp->cfd = JB_INVALID_SOCKET;
4891 privoxy_mutex_lock(&connection_reuse_mutex);
4892 if (!monitor_thread_running)
4894 monitor_thread_running = 1;
4895 privoxy_mutex_unlock(&connection_reuse_mutex);
4896 wait_for_alive_connections();
4897 privoxy_mutex_lock(&connection_reuse_mutex);
4898 monitor_thread_running = 0;
4900 privoxy_mutex_unlock(&connection_reuse_mutex);
4902 #endif /* def FEATURE_CONNECTION_SHARING */
4906 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4908 log_error(LOG_LEVEL_CONNECT,
4909 "Closing server socket %d connected to %s. Keep-alive: %u. "
4910 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4911 "Configuration file change detected: %u",
4912 csp->server_connection.sfd, csp->server_connection.host,
4913 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4914 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4915 socket_is_still_alive(csp->server_connection.sfd),
4916 csp->server_connection.keep_alive_timeout,
4917 config_file_change_detected);
4919 } while (continue_chatting);
4923 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4925 if (csp->cfd != JB_INVALID_SOCKET)
4927 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4928 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4929 "Configuration file change detected: %u. Requests received: %u.",
4930 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4931 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4932 config_file_change_detected, csp->requests_received_total);
4933 #ifdef FEATURE_HTTPS_INSPECTION
4934 close_client_ssl_connection(csp);
4936 drain_and_close_socket(csp->cfd);
4939 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4941 #ifdef FEATURE_CONNECTION_SHARING
4942 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4944 forget_connection(csp->server_connection.sfd);
4946 #endif /* def FEATURE_CONNECTION_SHARING */
4948 #ifdef FEATURE_HTTPS_INSPECTION
4949 close_server_ssl_connection(csp);
4950 #endif /* def FEATURE_HTTPS_INSPECTION */
4952 close_socket(csp->server_connection.sfd);
4955 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4956 mark_connection_closed(&csp->server_connection);
4959 free_csp_resources(csp);
4961 csp->flags &= ~CSP_FLAG_ACTIVE;
4967 /*********************************************************************
4969 * Function : server_thread
4971 * Description : We only exist to call `serve' in a threaded environment.
4974 * 1 : data = Current client state (buffers, headers, etc...)
4976 * Returns : Always 0.
4978 *********************************************************************/
4979 static int32 server_thread(void *data)
4981 serve((struct client_state *) data);
4988 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4989 /*********************************************************************
4993 * Description : Print usage info & exit.
4995 * Parameters : Pointer to argv[0] for identifying ourselves
4999 *********************************************************************/
5000 static void usage(const char *name)
5002 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
5003 "Usage: %s [--config-test] "
5006 #endif /* defined(unix) */
5009 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
5010 #endif /* defined(unix) */
5011 "[--version] [configfile]\n",
5015 show_fuzz_usage(name);
5018 printf("Aborting\n");
5023 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5026 #ifdef MUTEX_LOCKS_AVAILABLE
5027 /*********************************************************************
5029 * Function : privoxy_mutex_lock
5031 * Description : Locks a mutex.
5034 * 1 : mutex = The mutex to lock.
5036 * Returns : Void. May exit in case of errors.
5038 *********************************************************************/
5039 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5041 #ifdef FEATURE_PTHREAD
5042 int err = pthread_mutex_lock(mutex);
5045 if (mutex != &log_mutex)
5047 log_error(LOG_LEVEL_FATAL,
5048 "Mutex locking failed: %s.\n", strerror(err));
5053 EnterCriticalSection(mutex);
5054 #endif /* def FEATURE_PTHREAD */
5058 /*********************************************************************
5060 * Function : privoxy_mutex_unlock
5062 * Description : Unlocks a mutex.
5065 * 1 : mutex = The mutex to unlock.
5067 * Returns : Void. May exit in case of errors.
5069 *********************************************************************/
5070 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5072 #ifdef FEATURE_PTHREAD
5073 int err = pthread_mutex_unlock(mutex);
5076 if (mutex != &log_mutex)
5078 log_error(LOG_LEVEL_FATAL,
5079 "Mutex unlocking failed: %s.\n", strerror(err));
5084 LeaveCriticalSection(mutex);
5085 #endif /* def FEATURE_PTHREAD */
5089 /*********************************************************************
5091 * Function : privoxy_mutex_init
5093 * Description : Prepares a mutex.
5096 * 1 : mutex = The mutex to initialize.
5098 * Returns : Void. May exit in case of errors.
5100 *********************************************************************/
5101 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5103 #ifdef FEATURE_PTHREAD
5104 int err = pthread_mutex_init(mutex, 0);
5107 printf("Fatal error. Mutex initialization failed: %s.\n",
5112 InitializeCriticalSection(mutex);
5113 #endif /* def FEATURE_PTHREAD */
5115 #endif /* def MUTEX_LOCKS_AVAILABLE */
5117 /*********************************************************************
5119 * Function : initialize_mutexes
5121 * Description : Prepares mutexes if mutex support is available.
5125 * Returns : Void, exits in case of errors.
5127 *********************************************************************/
5128 static void initialize_mutexes(void)
5130 #ifdef MUTEX_LOCKS_AVAILABLE
5132 * Prepare global mutex semaphores
5135 #ifdef FEATURE_HTTPS_INSPECTION
5136 privoxy_mutex_init(&certificate_mutex);
5137 privoxy_mutex_init(&ssl_init_mutex);
5140 privoxy_mutex_init(&log_mutex);
5141 privoxy_mutex_init(&log_init_mutex);
5142 privoxy_mutex_init(&connection_reuse_mutex);
5143 #ifdef FEATURE_EXTERNAL_FILTERS
5144 privoxy_mutex_init(&external_filter_mutex);
5146 #ifdef FEATURE_CLIENT_TAGS
5147 privoxy_mutex_init(&client_tags_mutex);
5149 #ifdef FEATURE_EXTENDED_STATISTICS
5150 privoxy_mutex_init(&filter_statistics_mutex);
5151 privoxy_mutex_init(&block_statistics_mutex);
5155 * XXX: The assumptions below are a bit naive
5156 * and can cause locks that aren't necessary.
5158 * For example older FreeBSD versions (< 6.x?)
5159 * have no gethostbyname_r, but gethostbyname is
5162 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5163 privoxy_mutex_init(&resolver_mutex);
5164 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5166 * XXX: should we use a single mutex for
5167 * localtime() and gmtime() as well?
5169 #ifndef HAVE_GMTIME_R
5170 privoxy_mutex_init(&gmtime_mutex);
5171 #endif /* ndef HAVE_GMTIME_R */
5173 #ifndef HAVE_LOCALTIME_R
5174 privoxy_mutex_init(&localtime_mutex);
5175 #endif /* ndef HAVE_GMTIME_R */
5177 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5178 privoxy_mutex_init(&rand_mutex);
5179 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5181 #endif /* def MUTEX_LOCKS_AVAILABLE */
5184 /*********************************************************************
5188 * Description : Load the config file and start the listen loop.
5189 * This function is a lot more *sane* with the `load_config'
5190 * and `listen_loop' functions; although it stills does
5191 * a *little* too much for my taste.
5194 * 1 : argc = Number of parameters (including $0).
5195 * 2 : argv = Array of (char *)'s to the parameters.
5197 * Returns : 1 if : can't open config file, unrecognized directive,
5198 * stats requested in multi-thread mode, can't open the
5199 * log file, can't open the jar file, listen port is invalid,
5200 * any load fails, and can't bind port.
5202 * Else main never returns, the process must be signaled
5203 * to terminate execution. Or, on Windows, use the
5204 * "File", "Exit" menu option.
5206 *********************************************************************/
5208 int real_main(int argc, char **argv)
5210 int main(int argc, char **argv)
5214 int do_config_test = 0;
5215 #ifndef HAVE_ARC4RANDOM
5216 unsigned int random_seed;
5219 struct passwd *pw = NULL;
5220 struct group *grp = NULL;
5222 char *pre_chroot_nslookup_to_load_resolver = NULL;
5225 char *fuzz_input_type = NULL;
5226 char *fuzz_input_file = NULL;
5233 #if !defined(_WIN32)
5240 /* Prepare mutexes if supported and necessary. */
5241 initialize_mutexes();
5243 /* Enable logging until further notice. */
5247 * Parse the command line arguments
5249 * XXX: simply printing usage information in case of
5250 * invalid arguments isn't particularly user friendly.
5252 while (++argc_pos < argc)
5255 /* Check to see if the service must be installed or uninstalled */
5256 if (strncmp(argv[argc_pos], "--install", 9) == 0)
5258 const char *pName = argv[argc_pos] + 9;
5261 exit((install_service(pName)) ? 0 : 1);
5263 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5265 const char *pName = argv[argc_pos] + 11;
5268 exit((uninstall_service(pName)) ? 0 : 1);
5270 else if (strcmp(argv[argc_pos], "--service") == 0)
5272 bRunAsService = TRUE;
5273 w32_set_service_cwd();
5274 atexit(w32_service_exit_notify);
5277 #endif /* defined(_WIN32) */
5280 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5282 if (strcmp(argv[argc_pos], "--help") == 0)
5287 else if (strcmp(argv[argc_pos], "--version") == 0)
5289 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5295 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5297 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5301 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5303 if (++argc_pos == argc) usage(argv[0]);
5304 pidfile = strdup_or_die(argv[argc_pos]);
5307 else if (strcmp(argv[argc_pos], "--user") == 0)
5312 if (++argc_pos == argc) usage(argv[argc_pos]);
5314 user_arg = strdup_or_die(argv[argc_pos]);
5315 group_name = strchr(user_arg, '.');
5316 if (NULL != group_name)
5318 /* Nul-terminate the user name */
5321 /* Skip the former delimiter to actually reach the group name */
5324 grp = getgrnam(group_name);
5327 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5330 pw = getpwnam(user_arg);
5333 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5339 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5341 if (++argc_pos == argc) usage(argv[0]);
5342 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5345 else if (strcmp(argv[argc_pos], "--chroot") == 0)
5349 #endif /* defined(unix) */
5351 else if (strcmp(argv[argc_pos], "--config-test") == 0)
5356 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5359 if (argc < argc_pos + 2) usage(argv[0]);
5360 fuzz_input_type = argv[argc_pos];
5362 fuzz_input_file = argv[argc_pos];
5364 else if (strcmp(argv[argc_pos], "--stfu") == 0)
5366 set_debug_level(LOG_LEVEL_STFU);
5369 else if (argc_pos + 1 != argc)
5372 * This is neither the last command line
5373 * option, nor was it recognized before,
5374 * therefore it must be invalid.
5380 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5382 configfile = argv[argc_pos];
5385 } /* -END- while (more arguments) */
5387 show_version(Argv[0]);
5390 if (*configfile != '/')
5392 char cwd[BUFFER_SIZE];
5394 size_t abs_file_size;
5396 /* make config-filename absolute here */
5397 if (NULL == getcwd(cwd, sizeof(cwd)))
5399 perror("failed to get current working directory");
5403 basedir = strdup_or_die(cwd);
5405 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5406 abs_file = malloc_or_die(abs_file_size);
5407 strlcpy(abs_file, basedir, abs_file_size);
5408 strlcat(abs_file, "/", abs_file_size);
5409 strlcat(abs_file, configfile, abs_file_size);
5410 configfile = abs_file;
5412 #endif /* defined unix */
5416 clients->next = NULL;
5418 /* XXX: factor out initialising after the next stable release. */
5423 #ifndef HAVE_ARC4RANDOM
5424 random_seed = (unsigned int)time(NULL);
5426 srandom(random_seed);
5429 #endif /* ifdef HAVE_RANDOM */
5430 #endif /* ifndef HAVE_ARC4RANDOM */
5433 * Unix signal handling
5435 * Catch the abort, interrupt and terminate signals for a graceful exit
5436 * Catch the hangup signal so the errlog can be reopened.
5438 * Ignore the broken pipe signal as connection failures
5439 * are handled when and where they occur without relying
5442 #if !defined(_WIN32)
5445 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5447 for (idx = 0; idx < SZ(catched_signals); idx++)
5449 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5450 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5452 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5453 #endif /* ifdef sun */
5455 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5459 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5461 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5465 #else /* ifdef _WIN32 */
5466 # ifdef _WIN_CONSOLE
5468 * We *are* in a windows console app.
5469 * Print a verbose messages about FAQ's and such
5471 printf("%s", win32_blurb);
5472 # endif /* def _WIN_CONSOLE */
5473 #endif /* def _WIN32 */
5476 if (fuzz_input_type != NULL)
5478 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5480 log_error(LOG_LEVEL_FATAL,
5481 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5482 "Various data structures are static which is unsafe when using threads.");
5487 exit(NULL == load_config());
5490 /* Initialize the CGI subsystem */
5491 cgi_init_error_messages();
5494 * If running on unix and without the --no-daemon
5495 * option, become a daemon. I.e. fork, detach
5496 * from tty and get process group leadership
5505 if (pid < 0) /* error */
5510 else if (pid != 0) /* parent */
5515 * must check for errors
5516 * child died due to missing files aso
5519 wpid = waitpid(pid, &status, WNOHANG);
5531 * stderr (fd 2) will be closed later on,
5532 * when the config file has been parsed.
5538 * Reserve fd 0 and 1 to prevent abort() and friends
5539 * from sending stuff to the clients or servers.
5541 fd = open("/dev/null", O_RDONLY);
5544 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5548 if (dup2(fd, 0) == -1)
5550 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5554 fd = open("/dev/null", O_WRONLY);
5557 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5561 if (dup2(fd, 1) == -1)
5563 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5568 #ifdef FEATURE_EXTERNAL_FILTERS
5569 for (fd = 0; fd < 3; fd++)
5571 mark_socket_for_close_on_execute(fd);
5575 if (chdir("/") != 0)
5577 log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5580 } /* -END- if (daemon_mode) */
5583 * As soon as we have written the PID file, we can switch
5584 * to the user and group ID indicated by the --user option
5586 if (pidfile != NULL)
5588 write_pid_file(pidfile);
5592 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5594 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5598 if (setgroups(1, &grp->gr_gid))
5600 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5603 else if (initgroups(pw->pw_name, pw->pw_gid))
5605 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5611 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5613 /* Read the time zone file from /etc before doing chroot. */
5615 if (NULL != pre_chroot_nslookup_to_load_resolver
5616 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5618 /* Initialize resolver library. */
5619 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5621 if (chroot(pw->pw_dir) < 0)
5623 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5627 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5630 if (setuid(pw->pw_uid))
5632 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5636 char putenv_dummy[64];
5638 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5639 if (putenv(putenv_dummy) != 0)
5641 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5644 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5645 if (putenv(putenv_dummy) != 0)
5647 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5653 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5656 #endif /* defined unix */
5659 /* This will be FALSE unless the command line specified --service
5663 /* Yup, so now we must attempt to establish a connection
5664 * with the service dispatcher. This will only work if this
5665 * process was launched by the service control manager to
5666 * actually run as a service. If this isn't the case, i've
5667 * known it take around 30 seconds or so for the call to return.
5670 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5671 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5673 /* Service has run, and at this point is now being stopped, so just return */
5678 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5680 /* An error occurred. Usually it's because --service was wrongly specified
5681 * and we were unable to connect to the Service Control Dispatcher because
5682 * it wasn't expecting us and is therefore not listening.
5684 * For now, just continue below to call the listen_loop function.
5687 #endif /* def _WIN32 */
5697 /*********************************************************************
5699 * Function : bind_port_helper
5701 * Description : Bind the listen port. Handles logging, and aborts
5705 * 1 : haddr = Host address to bind to. Use NULL to bind to
5707 * 2 : hport = Specifies port to bind to.
5708 * 3 : backlog = Listen backlog.
5710 * Returns : Port that was opened.
5712 *********************************************************************/
5713 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5718 result = bind_port(haddr, hport, backlog, &bfd);
5722 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5726 log_error(LOG_LEVEL_FATAL,
5727 "can't bind to %s:%d: There may be another Privoxy "
5728 "or some other proxy running on port %d",
5729 bind_address, hport, hport);
5732 log_error(LOG_LEVEL_FATAL,
5733 "can't bind to %s:%d: The hostname is not resolvable",
5734 bind_address, hport);
5737 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5738 bind_address, hport);
5741 /* shouldn't get here */
5742 return JB_INVALID_SOCKET;
5747 if (bfd >= FD_SETSIZE)
5749 log_error(LOG_LEVEL_FATAL,
5750 "Bind socket number too high to use select(): %d >= %d",
5758 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5763 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5771 /*********************************************************************
5773 * Function : bind_ports_helper
5775 * Description : Bind the listen ports. Handles logging, and aborts
5779 * 1 : config = Privoxy configuration. Specifies ports
5781 * 2 : sockets = Preallocated array of opened sockets
5782 * corresponding to specification in config.
5783 * All non-opened sockets will be set to
5784 * JB_INVALID_SOCKET.
5786 * Returns : Nothing. Inspect sockets argument.
5788 *********************************************************************/
5789 static void bind_ports_helper(struct configuration_spec * config,
5790 jb_socket sockets[])
5794 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5796 if (config->hport[i])
5798 sockets[i] = bind_port_helper(config->haddr[i],
5799 config->hport[i], config->listen_backlog);
5800 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5801 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5803 struct accept_filter_arg af_options;
5804 bzero(&af_options, sizeof(af_options));
5805 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5806 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5807 sizeof(af_options)))
5809 log_error(LOG_LEVEL_ERROR,
5810 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5817 sockets[i] = JB_INVALID_SOCKET;
5820 config->need_bind = 0;
5824 /*********************************************************************
5826 * Function : close_ports_helper
5828 * Description : Close listenings ports.
5831 * 1 : sockets = Array of opened and non-opened sockets to
5832 * close. All sockets will be set to
5833 * JB_INVALID_SOCKET.
5835 * Returns : Nothing.
5837 *********************************************************************/
5838 static void close_ports_helper(jb_socket sockets[])
5842 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5844 if (JB_INVALID_SOCKET != sockets[i])
5846 close_socket(sockets[i]);
5848 sockets[i] = JB_INVALID_SOCKET;
5854 /* Without this simple workaround we get this compiler warning from _beginthread
5855 * warning C4028: formal parameter 1 different from declaration
5857 void w32_service_listen_loop(void *p)
5861 #endif /* def _WIN32 */
5864 /*********************************************************************
5866 * Function : listen_loop
5868 * Description : bind the listen port and enter a "FOREVER" listening loop.
5874 *********************************************************************/
5875 static void listen_loop(void)
5877 struct client_states *csp_list = NULL;
5878 struct client_state *csp = NULL;
5879 jb_socket bfds[MAX_LISTENING_SOCKETS];
5880 struct configuration_spec *config;
5881 unsigned int active_threads = 0;
5882 #if defined(FEATURE_PTHREAD)
5883 pthread_attr_t attrs;
5885 pthread_attr_init(&attrs);
5886 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5889 config = load_config();
5891 #ifdef FEATURE_CONNECTION_SHARING
5893 * XXX: Should be relocated once it no
5894 * longer needs to emit log messages.
5896 initialize_reusable_connections();
5897 #endif /* def FEATURE_CONNECTION_SHARING */
5899 bind_ports_helper(config, bfds);
5901 #ifdef FEATURE_GRACEFUL_TERMINATION
5902 while (!g_terminate)
5907 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
5908 while (waitpid(-1, NULL, WNOHANG) > 0)
5910 /* zombie children */
5912 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5915 * Free data that was used by died threads
5917 active_threads = sweep();
5921 * Re-open the errlog after HUP signal
5923 if (received_hup_signal)
5925 if (NULL != config->logfile)
5927 init_error_log(Argv[0], config->logfile);
5929 received_hup_signal = 0;
5933 csp_list = zalloc_or_die(sizeof(*csp_list));
5934 csp = &csp_list->csp;
5936 log_error(LOG_LEVEL_CONNECT,
5937 "Waiting for the next client connection. Currently active threads: %u",
5941 * This config may be outdated, but for accept_connection()
5942 * it's fresh enough.
5944 csp->config = config;
5946 if (!accept_connection(csp, bfds))
5948 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5953 csp->flags |= CSP_FLAG_ACTIVE;
5954 csp->server_connection.sfd = JB_INVALID_SOCKET;
5956 csp->config = config = load_config();
5958 if (config->need_bind)
5961 * Since we were listening to the "old port", we will not see
5962 * a "listen" param change until the next request. So, at
5963 * least 1 more request must be made for us to find the new
5964 * setting. I am simply closing the old socket and binding the
5967 * Which-ever is correct, we will serve 1 more page via the
5968 * old settings. This should probably be a "show-status"
5969 * request. This should not be a so common of an operation
5970 * that this will hurt people's feelings.
5973 close_ports_helper(bfds);
5975 bind_ports_helper(config, bfds);
5978 #ifdef FEATURE_TOGGLE
5979 if (global_toggle_state)
5980 #endif /* def FEATURE_TOGGLE */
5982 csp->flags |= CSP_FLAG_TOGGLED_ON;
5985 if (run_loader(csp))
5987 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5988 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5992 if (block_acl(NULL,csp))
5994 log_error(LOG_LEVEL_CONNECT,
5995 "Connection from %s on %s (socket %d) dropped due to ACL",
5996 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5997 close_socket(csp->cfd);
5998 freez(csp->ip_addr_str);
5999 freez(csp->listen_addr_str);
6003 #endif /* def FEATURE_ACL */
6005 if ((0 != config->max_client_connections)
6006 && (active_threads >= config->max_client_connections))
6008 log_error(LOG_LEVEL_CONNECT,
6009 "Rejecting connection from %s. Maximum number of connections reached.",
6011 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6012 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6013 close_socket(csp->cfd);
6014 freez(csp->ip_addr_str);
6015 freez(csp->listen_addr_str);
6020 /* add it to the list of clients */
6021 csp_list->next = clients->next;
6022 clients->next = csp_list;
6024 if (config->multi_threaded)
6028 /* this is a switch () statement in the C preprocessor - ugh */
6029 #undef SELECTED_ONE_OPTION
6031 /* Use Pthreads in preference to native code */
6032 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6033 #define SELECTED_ONE_OPTION
6035 pthread_t the_thread;
6038 ret = pthread_create(&the_thread, &attrs,
6039 (void * (*)(void *))serve, csp);
6040 child_id = ret ? -1 : 0;
6044 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
6045 #define SELECTED_ONE_OPTION
6046 child_id = _beginthread(
6047 (void (*)(void *))serve,
6052 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6053 #define SELECTED_ONE_OPTION
6055 thread_id tid = spawn_thread
6056 (server_thread, "server", B_NORMAL_PRIORITY, csp);
6058 if ((tid >= 0) && (resume_thread(tid) == B_OK))
6060 child_id = (int) tid;
6069 #if !defined(SELECTED_ONE_OPTION)
6072 /* This block is only needed when using fork().
6073 * When using threads, the server thread was
6074 * created and run by the call to _beginthread().
6076 if (child_id == 0) /* child */
6079 #ifdef FEATURE_TOGGLE
6080 int inherited_toggle_state = global_toggle_state;
6081 #endif /* def FEATURE_TOGGLE */
6086 * If we've been toggled or we've blocked the request, tell Mom
6089 #ifdef FEATURE_TOGGLE
6090 if (inherited_toggle_state != global_toggle_state)
6092 rc |= RC_FLAG_TOGGLED;
6094 #endif /* def FEATURE_TOGGLE */
6096 #ifdef FEATURE_STATISTICS
6097 if (csp->flags & CSP_FLAG_REJECTED)
6099 rc |= RC_FLAG_BLOCKED;
6101 #endif /* ndef FEATURE_STATISTICS */
6105 else if (child_id > 0) /* parent */
6107 /* in a fork()'d environment, the parent's
6108 * copy of the client socket and the CSP
6112 #if !defined(_WIN32) && !defined(__CYGWIN__)
6114 wait(&child_status);
6117 * Evaluate child's return code: If the child has
6118 * - been toggled, toggle ourselves
6119 * - blocked its request, bump up the stats counter
6122 #ifdef FEATURE_TOGGLE
6123 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6125 global_toggle_state = !global_toggle_state;
6127 #endif /* def FEATURE_TOGGLE */
6129 #ifdef FEATURE_STATISTICS
6131 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6135 #endif /* def FEATURE_STATISTICS */
6137 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6138 close_socket(csp->cfd);
6139 csp->flags &= ~CSP_FLAG_ACTIVE;
6143 #undef SELECTED_ONE_OPTION
6144 /* end of cpp switch () */
6149 * Spawning the child failed, assume it's because
6150 * there are too many children running already.
6151 * XXX: If you assume ...
6153 log_error(LOG_LEVEL_ERROR,
6154 "Unable to take any additional connections: %E. Active threads: %u",
6156 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6157 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6158 close_socket(csp->cfd);
6159 csp->flags &= ~CSP_FLAG_ACTIVE;
6168 #if defined(FEATURE_PTHREAD)
6169 pthread_attr_destroy(&attrs);
6172 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6174 #ifdef FEATURE_HTTPS_INSPECTION
6175 /* Clean up. Aim: free all memory (no leaks) */
6179 #ifdef FEATURE_GRACEFUL_TERMINATION
6181 log_error(LOG_LEVEL_INFO, "Graceful termination requested");
6183 unload_current_config_file();
6184 unload_current_actions_file();
6185 unload_current_re_filterfile();
6186 #ifdef FEATURE_TRUST
6187 unload_current_trust_file();
6190 if (config->multi_threaded)
6197 } while ((clients->next != NULL) && (--i > 0));
6201 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
6211 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6212 /* Cleanup - remove taskbar icon etc. */
6217 #endif /* FEATURE_GRACEFUL_TERMINATION */