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,
380 "sig_handler: exiting on unexpected signal %d", the_signal);
388 /*********************************************************************
390 * Function : get_write_delay
392 * Description : Parse the delay-response parameter.
395 * 1 : csp = Current client state (buffers, headers, etc...)
397 * Returns : Number of milliseconds to delay writes.
399 *********************************************************************/
400 static unsigned int get_write_delay(const struct client_state *csp)
406 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
410 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
412 delay = (unsigned)strtol(newval, &endptr, 0);
415 log_error(LOG_LEVEL_FATAL,
416 "Invalid delay-response{} parameter: '%s'", newval);
424 /*********************************************************************
426 * Function : client_protocol_is_unsupported
428 * Description : Checks if the client used a known unsupported
429 * protocol and deals with it by sending an error
433 * 1 : csp = Current client state (buffers, headers, etc...)
434 * 2 : req = the first request line send by the client
436 * Returns : TRUE if an error response has been generated, or
437 * FALSE if the request doesn't look invalid.
439 *********************************************************************/
440 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
443 * If it's a FTP or gopher request, we don't support it.
445 * These checks are better than nothing, but they might
446 * not work in all configurations and some clients might
447 * have problems digesting the answer.
449 * They should, however, never cause more problems than
450 * Privoxy's old behaviour (returning the misleading HTML
453 * "Could not resolve http://(ftp|gopher)://example.org").
455 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
457 const char *response = NULL;
458 const char *protocol = NULL;
460 if (!strncmpic(req, "GET ftp://", 10))
462 response = FTP_RESPONSE;
467 response = GOPHER_RESPONSE;
470 log_error(LOG_LEVEL_ERROR,
471 "%s tried to use Privoxy as %s proxy: %s",
472 csp->ip_addr_str, protocol, req);
473 log_error(LOG_LEVEL_CLF,
474 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
477 #ifdef FEATURE_HTTPS_INSPECTION
478 if (client_use_ssl(csp))
480 ssl_send_data_delayed(&(csp->ssl_client_attr),
481 (const unsigned char *)response, strlen(response),
482 get_write_delay(csp));
487 write_socket_delayed(csp->cfd, response, strlen(response),
488 get_write_delay(csp));
498 /*********************************************************************
500 * Function : client_has_unsupported_expectations
502 * Description : Checks if the client used an unsupported expectation
503 * in which case an error message is delivered.
506 * 1 : csp = Current client state (buffers, headers, etc...)
508 * Returns : TRUE if an error response has been generated, or
509 * FALSE if the request doesn't look invalid.
511 *********************************************************************/
512 static int client_has_unsupported_expectations(const struct client_state *csp)
514 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
516 log_error(LOG_LEVEL_ERROR,
517 "Rejecting request from client %s with unsupported Expect header value",
519 log_error(LOG_LEVEL_CLF,
520 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
521 write_socket_delayed(csp->cfd,
522 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
523 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
524 get_write_delay(csp));
534 /*********************************************************************
536 * Function : get_request_destination_elsewhere
538 * Description : If the client's request was redirected into
539 * Privoxy without the client's knowledge,
540 * the request line lacks the destination host.
542 * This function tries to get it elsewhere,
543 * provided accept-intercepted-requests is enabled.
545 * "Elsewhere" currently only means "Host: header",
546 * but in the future we may ask the redirecting
547 * packet filter to look the destination up.
549 * If the destination stays unknown, an error
550 * response is send to the client and headers
551 * are freed so that chat() can return directly.
554 * 1 : csp = Current client state (buffers, headers, etc...)
555 * 2 : headers = a header list
557 * Returns : JB_ERR_OK if the destination is now known, or
558 * JB_ERR_PARSE if it isn't.
560 *********************************************************************/
561 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
563 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
565 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
566 " Privoxy isn't configured to accept intercepted requests.",
567 csp->ip_addr_str, csp->http->cmd);
568 /* XXX: Use correct size */
569 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
570 csp->ip_addr_str, csp->http->cmd);
572 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
573 get_write_delay(csp));
574 destroy_list(headers);
578 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
580 /* Split the domain we just got for pattern matching */
581 init_domain_components(csp->http);
587 /* We can't work without destination. Go spread the news.*/
589 /* XXX: Use correct size */
590 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
591 csp->ip_addr_str, csp->http->cmd);
592 log_error(LOG_LEVEL_ERROR,
593 "Privoxy was unable to get the destination for %s's request: %s",
594 csp->ip_addr_str, csp->http->cmd);
596 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
597 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
598 destroy_list(headers);
603 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
604 * to get the destination IP address, use it as host directly
605 * or do a reverse DNS lookup first.
610 /*********************************************************************
612 * Function : get_server_headers
614 * Description : Parses server headers in iob and fills them
615 * into csp->headers so that they can later be
619 * 1 : csp = Current client state (buffers, headers, etc...)
621 * Returns : JB_ERR_OK if everything went fine, or
622 * JB_ERR_PARSE if the headers were incomplete.
624 *********************************************************************/
625 static jb_err get_server_headers(struct client_state *csp)
627 int continue_hack_in_da_house = 0;
630 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
635 * continue hack in da house. Ignore the ending of
636 * this head and continue enlisting header lines.
637 * The reason is described below.
639 enlist(csp->headers, "");
640 continue_hack_in_da_house = 0;
643 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
646 * It's a bodyless continue response, don't
647 * stop header parsing after reaching its end.
649 * As a result Privoxy will concatenate the
650 * next response's head and parse and deliver
651 * the headers as if they belonged to one request.
653 * The client will separate them because of the
654 * empty line between them.
656 * XXX: What we're doing here is clearly against
657 * the intended purpose of the continue header,
658 * and under some conditions (HTTP/1.0 client request)
659 * it's a standard violation.
661 * Anyway, "sort of against the spec" is preferable
662 * to "always getting confused by Continue responses"
663 * (Privoxy's behaviour before this hack was added)
665 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
666 continue_hack_in_da_house = 1;
668 else if (*header == '\0')
671 * If the header is empty, but the Continue hack
672 * isn't active, we can assume that we reached the
673 * end of the buffer before we hit the end of the
676 * Inform the caller an let it decide how to handle it.
681 if (JB_ERR_MEMORY == enlist(csp->headers, header))
684 * XXX: Should we quit the request and return a
685 * out of memory error page instead?
687 log_error(LOG_LEVEL_ERROR,
688 "Out of memory while enlisting server headers. %s lost.",
698 /*********************************************************************
700 * Function : crunch_reason
702 * Description : Translates the crunch reason code into a string.
705 * 1 : rsp = a http_response
707 * Returns : A string with the crunch reason or an error description.
709 *********************************************************************/
710 static const char *crunch_reason(const struct http_response *rsp)
712 char * reason = NULL;
717 return "Internal error while searching for crunch reason";
720 switch (rsp->crunch_reason)
723 reason = "Unsupported HTTP feature";
729 reason = "Untrusted";
732 reason = "Redirected";
738 reason = "DNS failure";
740 case FORWARDING_FAILED:
741 reason = "Forwarding failed";
744 reason = "Connection failure";
747 reason = "Out of memory (may mask other reasons)";
749 case CONNECTION_TIMEOUT:
750 reason = "Connection timeout";
753 reason = "No server data received";
756 reason = "No reason recorded";
764 /*********************************************************************
766 * Function : log_applied_actions
768 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
772 * 1 : actions = Current action spec to log
776 *********************************************************************/
777 static void log_applied_actions(const struct current_action_spec *actions)
780 * The conversion to text requires lots of memory allocations so
781 * we only do the conversion if the user is actually interested.
783 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
785 char *actions_as_text = actions_to_line_of_text(actions);
786 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
787 freez(actions_as_text);
792 /*********************************************************************
794 * Function : send_crunch_response
796 * Description : Delivers already prepared response for
797 * intercepted requests, logs the interception
798 * and frees the response.
801 * 1 : csp = Current client state (buffers, headers, etc...)
802 * 2 : rsp = Fully prepared response. Will be freed on exit.
806 *********************************************************************/
807 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
809 const struct http_request *http = csp->http;
813 assert(rsp->head != NULL);
817 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
821 * Extract the status code from the actual head
822 * that will be send to the client. It is the only
823 * way to get it right for all requests, including
824 * the fixed ones for out-of-memory problems.
826 * A head starts like this: 'HTTP/1.1 200...'
830 status_code[0] = rsp->head[9];
831 status_code[1] = rsp->head[10];
832 status_code[2] = rsp->head[11];
833 status_code[3] = '\0';
835 /* Log that the request was crunched and why. */
836 log_applied_actions(csp->action);
837 #ifdef FEATURE_HTTPS_INSPECTION
838 if (client_use_ssl(csp))
840 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
841 http->hostport, http->path);
842 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
843 csp->ip_addr_str, http->gpc, http->hostport, http->path,
844 http->version, status_code, rsp->content_length);
849 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
850 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
851 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
853 /* Write the answer to the client */
854 #ifdef FEATURE_HTTPS_INSPECTION
855 if (client_use_ssl(csp))
857 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
858 (const unsigned char *)rsp->head, rsp->head_length,
859 get_write_delay(csp)) < 0)
860 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
861 (const unsigned char *)rsp->body, rsp->content_length,
862 get_write_delay(csp)) < 0))
864 /* There is nothing we can do about it. */
865 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
866 "for https://%s%s through client socket %d using TLS/SSL",
867 http->hostport, http->url, csp->cfd);
873 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
874 get_write_delay(csp))
875 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
876 get_write_delay(csp)))
878 /* There is nothing we can do about it. */
879 log_error(LOG_LEVEL_CONNECT,
880 "Couldn't deliver the error message for %s through client socket %d: %E",
881 http->url, csp->cfd);
885 /* Clean up and return */
886 if (cgi_error_memory() != rsp)
888 free_http_response(rsp);
894 /*********************************************************************
896 * Function : crunch_response_triggered
898 * Description : Checks if the request has to be crunched,
899 * and delivers the crunch response if necessary.
902 * 1 : csp = Current client state (buffers, headers, etc...)
903 * 2 : crunchers = list of cruncher functions to run
905 * Returns : TRUE if the request was answered with a crunch response
908 *********************************************************************/
909 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
911 struct http_response *rsp = NULL;
912 const struct cruncher *c;
915 * If CGI request crunching is disabled,
916 * check the CGI dispatcher out of order to
917 * prevent unintentional blocks or redirects.
919 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
920 && (NULL != (rsp = dispatch_cgi(csp))))
922 /* Deliver, log and free the interception response. */
923 send_crunch_response(csp, rsp);
924 csp->flags |= CSP_FLAG_CRUNCHED;
928 for (c = crunchers; c->cruncher != NULL; c++)
931 * Check the cruncher if either Privoxy is toggled
932 * on and the request isn't forced, or if the cruncher
933 * applies to forced requests as well.
935 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
936 !(csp->flags & CSP_FLAG_FORCED)) ||
937 (c->flags & CF_IGNORE_FORCE))
939 rsp = c->cruncher(csp);
942 /* Deliver, log and free the interception response. */
943 send_crunch_response(csp, rsp);
944 csp->flags |= CSP_FLAG_CRUNCHED;
945 #ifdef FEATURE_STATISTICS
946 if (c->flags & CF_COUNT_AS_REJECT)
948 csp->flags |= CSP_FLAG_REJECTED;
950 #endif /* def FEATURE_STATISTICS */
961 /*********************************************************************
963 * Function : build_request_line
965 * Description : Builds the HTTP request line.
967 * If a HTTP forwarder is used it expects the whole URL,
968 * web servers only get the path.
971 * 1 : csp = Current client state (buffers, headers, etc...)
972 * 2 : fwd = The forwarding spec used for the request.
974 * 3 : request_line = The old request line which will be replaced.
976 * Returns : Nothing. Terminates in case of memory problems.
978 *********************************************************************/
979 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
981 struct http_request *http = csp->http;
984 * Downgrade http version from 1.1 to 1.0
985 * if +downgrade action applies.
987 if ((csp->action->flags & ACTION_DOWNGRADE)
988 && (!strcmpic(http->version, "HTTP/1.1")))
990 freez(http->version);
991 http->version = strdup_or_die("HTTP/1.0");
995 * Rebuild the request line.
997 freez(*request_line);
998 *request_line = strdup(http->gpc);
999 string_append(request_line, " ");
1001 if (fwd != NULL && fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1003 string_append(request_line, http->url);
1007 string_append(request_line, http->path);
1009 string_append(request_line, " ");
1010 string_append(request_line, http->version);
1012 if (*request_line == NULL)
1014 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1016 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1020 /*********************************************************************
1022 * Function : change_request_destination
1024 * Description : Parse a (rewritten) request line and regenerate
1025 * the http request data.
1028 * 1 : csp = Current client state (buffers, headers, etc...)
1030 * Returns : Forwards the parse_http_request() return code.
1031 * Terminates in case of memory problems.
1033 *********************************************************************/
1034 static jb_err change_request_destination(struct client_state *csp)
1036 struct http_request *http = csp->http;
1039 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1040 csp->headers->first->str);
1041 free_http_request(http);
1042 err = parse_http_request(csp->headers->first->str, http);
1043 if (JB_ERR_OK != err)
1045 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1046 jb_err_to_string(err));
1048 if (http->ssl && strcmpic(csp->http->gpc, "CONNECT"))
1051 * A client header filter changed the request URL from
1052 * http:// to https:// which we currently don't support.
1054 log_error(LOG_LEVEL_ERROR, "Changing the request destination from http "
1055 "to https behind the client's back currently isn't supported.");
1056 return JB_ERR_PARSE;
1063 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1064 /*********************************************************************
1066 * Function : server_response_is_complete
1068 * Description : Determines whether we should stop reading
1069 * from the server socket.
1072 * 1 : csp = Current client state (buffers, headers, etc...)
1073 * 2 : content_length = Length of content received so far.
1075 * Returns : TRUE if the response is complete,
1078 *********************************************************************/
1079 static int server_response_is_complete(struct client_state *csp,
1080 unsigned long long content_length)
1082 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1084 if (!strcmpic(csp->http->gpc, "HEAD"))
1087 * "HEAD" implies no body, we are thus expecting
1088 * no content. XXX: incomplete "list" of methods?
1090 csp->expected_content_length = 0;
1091 content_length_known = TRUE;
1092 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1095 if (csp->http->status == 204 || csp->http->status == 304)
1098 * Expect no body. XXX: incomplete "list" of status codes?
1100 csp->expected_content_length = 0;
1101 content_length_known = TRUE;
1102 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1105 return (content_length_known && ((0 == csp->expected_content_length)
1106 || (csp->expected_content_length <= content_length)));
1110 #ifdef FEATURE_CONNECTION_SHARING
1111 /*********************************************************************
1113 * Function : wait_for_alive_connections
1115 * Description : Waits for alive connections to timeout.
1121 *********************************************************************/
1122 static void wait_for_alive_connections(void)
1124 int connections_alive = close_unusable_connections();
1126 while (0 < connections_alive)
1128 log_error(LOG_LEVEL_CONNECT,
1129 "Waiting for %d connections to timeout.",
1132 connections_alive = close_unusable_connections();
1135 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1138 #endif /* def FEATURE_CONNECTION_SHARING */
1141 /*********************************************************************
1143 * Function : save_connection_destination
1145 * Description : Remembers a connection for reuse later on.
1148 * 1 : sfd = Open socket to remember.
1149 * 2 : http = The destination for the connection.
1150 * 3 : fwd = The forwarder settings used.
1151 * 4 : server_connection = storage.
1155 *********************************************************************/
1156 void save_connection_destination(jb_socket sfd,
1157 const struct http_request *http,
1158 const struct forward_spec *fwd,
1159 struct reusable_connection *server_connection)
1161 assert(sfd != JB_INVALID_SOCKET);
1162 assert(NULL != http->host);
1164 server_connection->sfd = sfd;
1165 server_connection->host = strdup_or_die(http->host);
1166 server_connection->port = http->port;
1168 assert(NULL != fwd);
1169 assert(server_connection->gateway_host == NULL);
1170 assert(server_connection->gateway_port == 0);
1171 assert(server_connection->forwarder_type == 0);
1172 assert(server_connection->forward_host == NULL);
1173 assert(server_connection->forward_port == 0);
1175 server_connection->forwarder_type = fwd->type;
1176 if (NULL != fwd->gateway_host)
1178 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1182 server_connection->gateway_host = NULL;
1184 server_connection->gateway_port = fwd->gateway_port;
1185 if (NULL != fwd->auth_username)
1187 server_connection->auth_username = strdup_or_die(fwd->auth_username);
1191 server_connection->auth_username = NULL;
1193 if (NULL != fwd->auth_password)
1195 server_connection->auth_password = strdup_or_die(fwd->auth_password);
1199 server_connection->auth_password = NULL;
1202 if (NULL != fwd->forward_host)
1204 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1208 server_connection->forward_host = NULL;
1210 server_connection->forward_port = fwd->forward_port;
1212 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1215 /*********************************************************************
1217 * Function : verify_request_length
1219 * Description : Checks if we already got the whole client requests
1220 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1223 * Data that doesn't belong to the current request is
1224 * either thrown away to let the client retry on a clean
1225 * socket, or stashed to be dealt with after the current
1226 * request is served.
1229 * 1 : csp = Current client state (buffers, headers, etc...)
1233 *********************************************************************/
1234 static void verify_request_length(struct client_state *csp)
1236 unsigned long long buffered_request_bytes =
1237 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1239 if ((csp->expected_client_content_length != 0)
1240 && (buffered_request_bytes != 0))
1242 if (csp->expected_client_content_length >= buffered_request_bytes)
1244 csp->expected_client_content_length -= buffered_request_bytes;
1245 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1246 "to account for the %llu ones we already got.",
1247 csp->expected_client_content_length, buffered_request_bytes);
1251 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1252 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1253 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1254 "Marking the server socket tainted after throwing %llu bytes away.",
1255 buffered_request_bytes - csp->expected_client_content_length);
1256 csp->expected_client_content_length = 0;
1257 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1260 if (csp->expected_client_content_length == 0)
1262 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1266 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1267 && ((csp->client_iob->cur < csp->client_iob->eod)
1268 || (csp->expected_client_content_length != 0)))
1270 if (strcmpic(csp->http->gpc, "GET")
1271 && strcmpic(csp->http->gpc, "HEAD")
1272 && strcmpic(csp->http->gpc, "TRACE")
1273 && strcmpic(csp->http->gpc, "OPTIONS")
1274 && strcmpic(csp->http->gpc, "DELETE"))
1276 /* XXX: this is an incomplete hack */
1277 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1278 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1282 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1284 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1286 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1287 log_error(LOG_LEVEL_CONNECT,
1288 "Possible pipeline attempt detected. The connection will not "
1289 "be kept alive and we will only serve the first request.");
1290 /* Nuke the pipelined requests from orbit, just to be sure. */
1291 clear_iob(csp->client_iob);
1296 * Keep the pipelined data around for now, we'll deal with
1297 * it once we're done serving the current request.
1299 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1300 assert(csp->client_iob->eod >= csp->client_iob->cur);
1301 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1302 "%d bytes of pipelined data received.",
1303 (int)(csp->client_iob->eod - csp->client_iob->cur));
1309 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1310 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1315 /*********************************************************************
1317 * Function : mark_server_socket_tainted
1319 * Description : Makes sure we don't reuse a server socket
1320 * (if we didn't read everything the server sent
1321 * us reusing the socket would lead to garbage).
1324 * 1 : csp = Current client state (buffers, headers, etc...)
1328 *********************************************************************/
1329 static void mark_server_socket_tainted(struct client_state *csp)
1332 * For consistency we always mark the server socket
1333 * tainted, however, to reduce the log noise we only
1334 * emit a log message if the server socket could have
1335 * actually been reused.
1337 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1338 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1340 log_error(LOG_LEVEL_CONNECT,
1341 "Marking the server socket %d tainted.",
1342 csp->server_connection.sfd);
1344 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1347 /*********************************************************************
1349 * Function : get_request_line
1351 * Description : Read the client request line.
1354 * 1 : csp = Current client state (buffers, headers, etc...)
1356 * Returns : Pointer to request line or NULL in case of errors.
1358 *********************************************************************/
1359 static char *get_request_line(struct client_state *csp)
1361 char buf[BUFFER_SIZE];
1362 char *request_line = NULL;
1365 memset(buf, 0, sizeof(buf));
1367 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1370 * If there are multiple pipelined requests waiting,
1371 * the flag will be set again once the next request
1374 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1376 request_line = get_header(csp->client_iob);
1377 if ((NULL != request_line) && ('\0' != *request_line))
1379 return request_line;
1383 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1384 "received yet. Continuing reading from %d.", csp->cfd);
1392 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1394 !data_is_available(csp->cfd, csp->config->socket_timeout)
1397 if (socket_is_still_alive(csp->cfd))
1399 log_error(LOG_LEVEL_CONNECT,
1400 "No request line on socket %d received in time. Timeout: %d.",
1401 csp->cfd, csp->config->socket_timeout);
1402 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1403 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1404 get_write_delay(csp));
1408 log_error(LOG_LEVEL_CONNECT,
1409 "The client side of the connection on socket %d got "
1410 "closed without sending a complete request line.", csp->cfd);
1415 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1417 if (len <= 0) return NULL;
1420 * If there is no memory left for buffering the
1421 * request, there is nothing we can do but hang up
1423 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1428 request_line = get_header(csp->client_iob);
1430 } while ((NULL != request_line) && ('\0' == *request_line));
1432 return request_line;
1438 CHUNK_STATUS_MISSING_DATA,
1439 CHUNK_STATUS_BODY_COMPLETE,
1440 CHUNK_STATUS_PARSE_ERROR
1444 /*********************************************************************
1446 * Function : chunked_body_is_complete
1448 * Description : Figures out whether or not a chunked body is complete.
1450 * Currently it always starts at the beginning of the
1451 * buffer which is somewhat wasteful and prevents Privoxy
1452 * from starting to forward the correctly parsed chunks
1453 * as soon as theoretically possible.
1455 * Should be modified to work with a common buffer,
1456 * and allow the caller to skip already parsed chunks.
1458 * This would allow the function to be used for unbuffered
1459 * response bodies as well.
1462 * 1 : iob = Buffer with the body to check.
1463 * 2 : length = Length of complete body
1465 * Returns : Enum with the result of the check.
1467 *********************************************************************/
1468 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1470 unsigned int chunksize;
1476 * We need at least a single digit, followed by "\r\n",
1477 * followed by an unknown amount of data, followed by "\r\n".
1479 if (p + 5 > iob->eod)
1481 return CHUNK_STATUS_MISSING_DATA;
1483 if (sscanf(p, "%x", &chunksize) != 1)
1485 return CHUNK_STATUS_PARSE_ERROR;
1489 * We want at least a single digit, followed by "\r\n",
1490 * followed by the specified amount of data, followed by "\r\n".
1492 if (p + chunksize + 5 > iob->eod)
1494 return CHUNK_STATUS_MISSING_DATA;
1497 /* Skip chunk-size. */
1498 p = strstr(p, "\r\n");
1501 return CHUNK_STATUS_PARSE_ERROR;
1503 /* Move beyond the chunkdata. */
1506 /* There should be another "\r\n" to skip */
1507 if (memcmp(p, "\r\n", 2))
1509 return CHUNK_STATUS_PARSE_ERROR;
1512 } while (chunksize > 0U);
1514 *length = (size_t)(p - iob->cur);
1515 assert(*length <= (size_t)(iob->eod - iob->cur));
1516 assert(p <= iob->eod);
1518 return CHUNK_STATUS_BODY_COMPLETE;
1523 /*********************************************************************
1525 * Function : receive_chunked_client_request_body
1527 * Description : Read the chunk-encoded client request body.
1528 * Failures are dealt with.
1531 * 1 : csp = Current client state (buffers, headers, etc...)
1533 * Returns : JB_ERR_OK or JB_ERR_PARSE
1535 *********************************************************************/
1536 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1539 enum chunk_status status;
1541 while (CHUNK_STATUS_MISSING_DATA ==
1542 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1544 char buf[BUFFER_SIZE];
1547 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1549 log_error(LOG_LEVEL_ERROR,
1550 "Timeout while waiting for the client body.");
1553 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1556 log_error(LOG_LEVEL_ERROR,
1557 "Reading the client body failed: %E");
1560 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1565 if (status != CHUNK_STATUS_BODY_COMPLETE)
1567 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1568 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1569 log_error(LOG_LEVEL_CLF,
1570 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1571 return JB_ERR_PARSE;
1573 log_error(LOG_LEVEL_CONNECT,
1574 "Chunked client body completely read. Length: %lu", body_length);
1575 csp->expected_client_content_length = body_length;
1583 /*********************************************************************
1585 * Function : fuzz_chunked_transfer_encoding
1587 * Description : Treat the fuzzed input as chunked transfer encoding
1588 * to check and dechunk.
1591 * 1 : csp = Used to store the data.
1592 * 2 : fuzz_input_file = File to read the input from.
1594 * Returns : Result of dechunking
1596 *********************************************************************/
1597 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1600 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1601 enum chunk_status status;
1603 status = chunked_body_is_complete(csp->iob, &length);
1604 if (CHUNK_STATUS_BODY_COMPLETE != status)
1606 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1609 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1614 /*********************************************************************
1616 * Function : fuzz_client_request
1618 * Description : Try to get a client request from the fuzzed input.
1621 * 1 : csp = Current client state (buffers, headers, etc...)
1622 * 2 : fuzz_input_file = File to read the input from.
1624 * Returns : Result of fuzzing.
1626 *********************************************************************/
1627 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1632 csp->ip_addr_str = "fuzzer";
1634 if (strcmp(fuzz_input_file, "-") != 0)
1636 log_error(LOG_LEVEL_FATAL,
1637 "Fuzzed client requests can currently only be read from stdin (-).");
1639 err = receive_client_request(csp);
1640 if (err != JB_ERR_OK)
1644 err = parse_client_request(csp);
1645 if (err != JB_ERR_OK)
1653 #endif /* def FUZZ */
1656 #ifdef FEATURE_FORCE_LOAD
1657 /*********************************************************************
1659 * Function : force_required
1661 * Description : Checks a request line to see if it contains
1662 * the FORCE_PREFIX. If it does, it is removed
1663 * unless enforcing requests has beend disabled.
1666 * 1 : request_line = HTTP request line
1668 * Returns : TRUE if force is required, FALSE otherwise.
1670 *********************************************************************/
1671 static int force_required(const struct client_state *csp, char *request_line)
1675 p = strstr(request_line, "http://");
1679 p += strlen("http://");
1683 /* Intercepted request usually don't specify the protocol. */
1687 /* Go to the beginning of the path */
1692 * If the path is missing the request line is invalid and we
1693 * are done here. The client-visible rejection happens later on.
1698 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1700 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1702 /* XXX: Should clean more carefully */
1703 strclean(request_line, FORCE_PREFIX);
1704 log_error(LOG_LEVEL_FORCE,
1705 "Enforcing request: \"%s\".", request_line);
1709 log_error(LOG_LEVEL_FORCE,
1710 "Ignored force prefix in request: \"%s\".", request_line);
1716 #endif /* def FEATURE_FORCE_LOAD */
1719 /*********************************************************************
1721 * Function : receive_client_request
1723 * Description : Read the client's request (more precisely the
1724 * client headers) and answer it if necessary.
1727 * 1 : csp = Current client state (buffers, headers, etc...)
1729 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1731 *********************************************************************/
1732 static jb_err receive_client_request(struct client_state *csp)
1734 char buf[BUFFER_SIZE];
1737 struct http_request *http;
1741 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1742 struct list header_list;
1743 struct list *headers = &header_list;
1745 /* We don't care if the arriving data is a valid HTTP request or not. */
1746 csp->requests_received_total++;
1750 memset(buf, 0, sizeof(buf));
1752 req = get_request_line(csp);
1755 mark_server_socket_tainted(csp);
1756 return JB_ERR_PARSE;
1758 assert(*req != '\0');
1760 if (client_protocol_is_unsupported(csp, req))
1762 return JB_ERR_PARSE;
1765 #ifdef FEATURE_FORCE_LOAD
1766 if (force_required(csp, req))
1768 csp->flags |= CSP_FLAG_FORCED;
1770 #endif /* def FEATURE_FORCE_LOAD */
1772 err = parse_http_request(req, http);
1774 if (JB_ERR_OK != err)
1776 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1777 get_write_delay(csp));
1778 /* XXX: Use correct size */
1779 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1780 log_error(LOG_LEVEL_ERROR,
1781 "Couldn't parse request line received from %s: %s",
1782 csp->ip_addr_str, jb_err_to_string(err));
1784 free_http_request(http);
1785 return JB_ERR_PARSE;
1788 /* grab the rest of the client's headers */
1792 p = get_header(csp->client_iob);
1796 /* There are no additional headers to read. */
1803 * We didn't receive a complete header
1804 * line yet, get the rest of it.
1806 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1808 log_error(LOG_LEVEL_ERROR,
1809 "Stopped grabbing the client headers.");
1810 destroy_list(headers);
1811 return JB_ERR_PARSE;
1814 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1817 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1818 destroy_list(headers);
1819 return JB_ERR_PARSE;
1822 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1825 * If there is no memory left for buffering the
1826 * request, there is nothing we can do but hang up
1828 destroy_list(headers);
1829 return JB_ERR_MEMORY;
1834 if (!strncmpic(p, "Transfer-Encoding:", 18))
1837 * XXX: should be called through sed()
1838 * but currently can't.
1840 client_transfer_encoding(csp, &p);
1843 * We were able to read a complete
1844 * header and can finally enlist it.
1851 if (http->host == NULL)
1854 * If we still don't know the request destination,
1855 * the request is invalid or the client uses
1856 * Privoxy without its knowledge.
1858 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1861 * Our attempts to get the request destination
1862 * elsewhere failed or Privoxy is configured
1863 * to only accept proxy requests.
1865 * An error response has already been sent
1866 * and we're done here.
1868 return JB_ERR_PARSE;
1872 #ifdef FEATURE_CLIENT_TAGS
1873 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1874 set_client_address(csp, headers);
1875 get_tag_list_for_client(csp->client_tags, csp->client_address);
1879 * Determine the actions for this URL
1881 #ifdef FEATURE_TOGGLE
1882 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1884 /* Most compatible set of actions (i.e. none) */
1885 init_current_action(csp->action);
1888 #endif /* ndef FEATURE_TOGGLE */
1890 get_url_actions(csp, http);
1893 enlist(csp->headers, http->cmd);
1895 /* Append the previously read headers */
1896 err = list_append_list_unique(csp->headers, headers);
1897 destroy_list(headers);
1904 /*********************************************************************
1906 * Function : parse_client_request
1908 * Description : Parses the client's request and decides what to do
1911 * Note that since we're not using select() we could get
1912 * blocked here if a client connected, then didn't say
1916 * 1 : csp = Current client state (buffers, headers, etc...)
1918 * Returns : JB_ERR_OK or JB_ERR_PARSE
1920 *********************************************************************/
1921 static jb_err parse_client_request(struct client_state *csp)
1923 struct http_request *http = csp->http;
1926 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1927 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1928 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1929 && (csp->http->ssl == 0))
1931 /* Assume persistence until further notice */
1932 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1934 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1936 if (csp->http->ssl == 0)
1939 * This whole block belongs to chat() but currently
1940 * has to be executed before sed().
1942 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1944 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1946 return JB_ERR_PARSE;
1951 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1953 verify_request_length(csp);
1955 #ifndef FEATURE_HTTPS_INSPECTION
1958 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1962 err = sed(csp, FILTER_CLIENT_HEADERS);
1963 if (JB_ERR_OK != err)
1965 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1967 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1968 csp->ip_addr_str, csp->http->cmd);
1969 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1970 return JB_ERR_PARSE;
1972 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1974 /* Check request line for rewrites. */
1975 if ((NULL == csp->headers->first->str)
1976 || (strcmp(http->cmd, csp->headers->first->str) &&
1977 (JB_ERR_OK != change_request_destination(csp))))
1980 * A header filter broke the request line - bail out.
1982 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1983 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1984 /* XXX: Use correct size */
1985 log_error(LOG_LEVEL_CLF,
1986 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
1987 log_error(LOG_LEVEL_ERROR,
1988 "Invalid request line after applying header filters.");
1989 free_http_request(http);
1991 return JB_ERR_PARSE;
1994 if (client_has_unsupported_expectations(csp))
1996 return JB_ERR_PARSE;
2004 /*********************************************************************
2006 * Function : read_http_request_body
2008 * Description : Reads remaining request body from the client.
2011 * 1 : csp = Current client state (buffers, headers, etc...)
2013 * Returns : 0 on success, anything else is an error.
2015 *********************************************************************/
2016 static int read_http_request_body(struct client_state *csp)
2018 size_t to_read = csp->expected_client_content_length;
2021 assert(to_read != 0);
2023 /* check if all data has been already read */
2024 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2029 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2030 to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2031 to_read -= (unsigned)len)
2033 char buf[BUFFER_SIZE];
2034 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2036 log_error(LOG_LEVEL_CONNECT,
2037 "Waiting for up to %d bytes of request body from the client.",
2039 len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2042 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2045 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2049 assert(to_read >= len);
2054 log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %d more bytes",
2055 csp->expected_client_content_length);
2058 log_error(LOG_LEVEL_CONNECT, "The last %d bytes of the request body have been read",
2059 csp->expected_client_content_length);
2064 /*********************************************************************
2066 * Function : update_client_headers
2068 * Description : Updates the HTTP headers from the client request.
2071 * 1 : csp = Current client state (buffers, headers, etc...)
2072 * 2 : new_content_length = new content length value to set
2074 * Returns : 0 on success, anything else is an error.
2076 *********************************************************************/
2077 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2079 static const char content_length[] = "Content-Length:";
2081 struct list_entry *p;
2083 #ifndef FEATURE_HTTPS_INSPECTION
2084 for (p = csp->headers->first;
2086 for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2088 !updated && (p != NULL); p = p->next)
2090 /* Header crunch()ed in previous run? -> ignore */
2096 /* Does the current parser handle this header? */
2097 if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2099 updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2111 /*********************************************************************
2113 * Function : can_filter_request_body
2115 * Description : Checks if the current request body can be stored in
2116 * the client_iob without hitting buffer limit.
2119 * 1 : csp = Current client state (buffers, headers, etc...)
2121 * Returns : TRUE if the current request size do not exceed buffer limit
2124 *********************************************************************/
2125 static int can_filter_request_body(const struct client_state *csp)
2127 if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2128 csp->expected_client_content_length))
2130 log_error(LOG_LEVEL_INFO,
2131 "Not filtering request body from %s: buffer limit %d will be exceeded "
2132 "(content length %d)", csp->ip_addr_str, csp->config->buffer_limit,
2133 csp->expected_client_content_length);
2140 /*********************************************************************
2142 * Function : send_http_request
2144 * Description : Sends the HTTP headers from the client request
2145 * and all the body data that has already been received.
2148 * 1 : csp = Current client state (buffers, headers, etc...)
2150 * Returns : 0 on success, anything else is an error.
2152 *********************************************************************/
2153 static int send_http_request(struct client_state *csp)
2157 const char *to_send;
2159 int filter_client_body = csp->expected_client_content_length != 0 &&
2160 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2162 if (filter_client_body)
2164 if (read_http_request_body(csp))
2168 to_send_len = csp->expected_client_content_length;
2169 to_send = execute_client_body_filters(csp, &to_send_len);
2170 if (to_send == NULL)
2172 /* just flush client_iob */
2173 filter_client_body = FALSE;
2175 else if (to_send_len != csp->expected_client_content_length &&
2176 update_client_headers(csp, to_send_len))
2178 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2181 csp->expected_client_content_length = 0;
2184 hdr = list_to_text(csp->headers);
2187 /* FIXME Should handle error properly */
2188 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2190 list_remove_all(csp->headers);
2193 * Write the client's (modified) header to the server
2194 * (along with anything else that may be in the buffer)
2196 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2201 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2202 csp->http->hostport);
2206 if (filter_client_body)
2208 write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2212 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2213 csp->http->hostport);
2218 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2219 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2221 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2222 csp->http->hostport);
2229 #ifdef FEATURE_HTTPS_INSPECTION
2230 /*********************************************************************
2232 * Function : read_https_request_body
2234 * Description : Reads remaining request body from the client.
2237 * 1 : csp = Current client state (buffers, headers, etc...)
2239 * Returns : 0 on success, anything else is an error.
2241 *********************************************************************/
2242 static int read_https_request_body(struct client_state *csp)
2244 size_t to_read = csp->expected_client_content_length;
2247 assert(to_read != 0);
2249 /* check if all data has been already read */
2250 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2255 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2256 to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2257 data_is_available(csp->cfd, csp->config->socket_timeout));
2258 to_read -= (unsigned)len)
2260 unsigned char buf[BUFFER_SIZE];
2261 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2263 log_error(LOG_LEVEL_CONNECT,
2264 "Waiting for up to %d bytes of request body from the client.",
2266 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2267 (unsigned)max_bytes_to_read);
2270 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2273 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2277 assert(to_read >= len);
2282 log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %d more bytes", to_read);
2286 log_error(LOG_LEVEL_CONNECT, "The last %d bytes of the request body have been read",
2287 csp->expected_client_content_length);
2292 /*********************************************************************
2294 * Function : receive_and_send_encrypted_post_data
2296 * Description : Reads remaining request body from the client and sends
2300 * 1 : csp = Current client state (buffers, headers, etc...)
2302 * Returns : 0 on success, anything else is an error.
2304 *********************************************************************/
2305 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2307 int content_length_known = csp->expected_client_content_length != 0;
2309 while (is_ssl_pending(&(csp->ssl_client_attr))
2310 || (content_length_known && csp->expected_client_content_length != 0))
2312 unsigned char buf[BUFFER_SIZE];
2314 int max_bytes_to_read = sizeof(buf);
2316 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2318 max_bytes_to_read = (int)csp->expected_client_content_length;
2320 log_error(LOG_LEVEL_CONNECT,
2321 "Waiting for up to %d bytes of request body from the client.",
2323 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2324 (unsigned)max_bytes_to_read);
2331 /* XXX: Does this actually happen? */
2334 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2336 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2341 if (csp->expected_client_content_length != 0)
2343 if (csp->expected_client_content_length >= len)
2345 csp->expected_client_content_length -= (unsigned)len;
2347 if (csp->expected_client_content_length == 0)
2349 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2355 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2362 /*********************************************************************
2364 * Function : send_https_request
2366 * Description : Sends the HTTP headers from the client request
2367 * and all the body data that has already been received.
2370 * 1 : csp = Current client state (buffers, headers, etc...)
2372 * Returns : 0 on success, anything else is an error.
2374 *********************************************************************/
2375 static int send_https_request(struct client_state *csp)
2380 const char *to_send;
2382 int filter_client_body = csp->expected_client_content_length != 0 &&
2383 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2385 if (filter_client_body)
2387 if (read_https_request_body(csp))
2391 to_send_len = csp->expected_client_content_length;
2392 to_send = execute_client_body_filters(csp, &to_send_len);
2393 if (to_send == NULL)
2395 /* just flush client_iob */
2396 filter_client_body = FALSE;
2398 else if (to_send_len != csp->expected_client_content_length &&
2399 update_client_headers(csp, to_send_len))
2401 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2404 csp->expected_client_content_length = 0;
2407 hdr = list_to_text(csp->https_headers);
2410 /* FIXME Should handle error properly */
2411 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2413 list_remove_all(csp->https_headers);
2416 * Write the client's (modified) header to the server
2417 * (along with anything else that may be in the buffer)
2419 ret = ssl_send_data(&(csp->ssl_server_attr),
2420 (const unsigned char *)hdr, strlen(hdr));
2425 log_error(LOG_LEVEL_CONNECT,
2426 "Failed sending encrypted request headers to: %s: %E",
2427 csp->http->hostport);
2428 mark_server_socket_tainted(csp);
2432 if (filter_client_body)
2434 ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2438 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2439 csp->http->hostport);
2444 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2445 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2446 csp->client_iob)) < 0))
2448 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2449 csp->http->hostport);
2452 if (flushed != 0 || csp->expected_client_content_length != 0)
2454 if (csp->expected_client_content_length != 0)
2456 if (csp->expected_client_content_length < flushed)
2458 log_error(LOG_LEVEL_ERROR,
2459 "Flushed %ld bytes of request body while only expecting %llu",
2460 flushed, csp->expected_client_content_length);
2461 csp->expected_client_content_length = 0;
2465 log_error(LOG_LEVEL_CONNECT,
2466 "Flushed %ld bytes of request body while expecting %llu",
2467 flushed, csp->expected_client_content_length);
2468 csp->expected_client_content_length -= (unsigned)flushed;
2469 if (receive_and_send_encrypted_post_data(csp))
2477 log_error(LOG_LEVEL_CONNECT,
2478 "Flushed %ld bytes of request body", flushed);
2482 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2489 /*********************************************************************
2491 * Function : receive_encrypted_request
2493 * Description : Receives an encrypted request.
2496 * 1 : csp = Current client state (buffers, headers, etc...)
2498 * Returns : JB_ERR_OK on success,
2499 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2501 *********************************************************************/
2502 static jb_err receive_encrypted_request(struct client_state *csp)
2504 char buf[BUFFER_SIZE];
2510 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2511 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2512 !data_is_available(csp->cfd, csp->config->socket_timeout))
2514 log_error(LOG_LEVEL_CONNECT,
2515 "Socket %d timed out while waiting for client headers", csp->cfd);
2516 return JB_ERR_PARSE;
2518 len = ssl_recv_data(&(csp->ssl_client_attr),
2519 (unsigned char *)buf, sizeof(buf));
2522 log_error(LOG_LEVEL_CONNECT,
2523 "Socket %d closed while waiting for client headers", csp->cfd);
2524 return JB_ERR_PARSE;
2528 return JB_ERR_PARSE;
2530 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2532 return JB_ERR_MEMORY;
2534 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2535 } while (p == NULL);
2537 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2543 /*********************************************************************
2545 * Function : change_encrypted_request_destination
2547 * Description : Parse a (rewritten) request line from an encrypted
2548 * request and regenerate the http request data.
2551 * 1 : csp = Current client state (buffers, headers, etc...)
2553 * Returns : Forwards the parse_http_request() return code.
2554 * Terminates in case of memory problems.
2556 *********************************************************************/
2557 static jb_err change_encrypted_request_destination(struct client_state *csp)
2560 char *original_host = csp->http->host;
2561 int original_port = csp->http->port;
2563 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2564 csp->https_headers->first->str);
2565 csp->http->host = NULL;
2566 free_http_request(csp->http);
2567 err = parse_http_request(csp->https_headers->first->str, csp->http);
2568 if (JB_ERR_OK != err)
2570 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2571 jb_err_to_string(err));
2572 freez(original_host);
2576 if (csp->http->host == NULL)
2578 char port_string[10];
2580 * The rewritten request line did not specify a host
2581 * which means we can use the original host specified
2584 csp->http->host = original_host;
2585 csp->http->port = original_port;
2586 log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2589 * If the rewritten request line didn't contain a host
2590 * it also didn't contain a port so we can reuse the host
2593 freez(csp->http->hostport);
2594 csp->http->hostport = strdup_or_die(csp->http->host);
2595 snprintf(port_string, sizeof(port_string), ":%d", original_port);
2596 err = string_append(&csp->http->hostport, port_string);
2597 if (err != JB_ERR_OK)
2599 log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2600 jb_err_to_string(err));
2605 * While the request line didn't mention it,
2606 * we're https-inspecting and want to speak TLS
2609 csp->http->server_ssl = 1;
2614 /* The rewrite filter added a host so we can ditch the original */
2615 freez(original_host);
2616 csp->http->server_ssl = csp->http->ssl;
2619 csp->http->client_ssl = 1;
2621 freez(csp->https_headers->first->str);
2622 build_request_line(csp, NULL, &csp->https_headers->first->str);
2624 if (!server_use_ssl(csp))
2626 log_error(LOG_LEVEL_REDIRECTS,
2627 "Rewritten request line results in downgrade to http");
2629 * Replace the unencryptd headers received with the
2630 * CONNECT request with the ones we received securely.
2632 destroy_list(csp->headers);
2633 csp->headers->first = csp->https_headers->first;
2634 csp->headers->last = csp->https_headers->last;
2635 csp->https_headers->first = NULL;
2636 csp->https_headers->last = NULL;
2644 /*********************************************************************
2646 * Function : process_encrypted_request
2648 * Description : Receives and parses an encrypted request.
2651 * 1 : csp = Current client state (buffers, headers, etc...)
2653 * Returns : JB_ERR_OK on success,
2654 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2656 *********************************************************************/
2657 static jb_err process_encrypted_request(struct client_state *csp)
2662 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2663 struct list header_list;
2664 struct list *headers = &header_list;
2666 assert(csp->ssl_with_client_is_opened);
2668 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2669 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2671 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2674 err = receive_encrypted_request(csp);
2675 if (err != JB_ERR_OK)
2677 if (csp->client_iob->cur == NULL ||
2678 csp->client_iob->cur == csp->client_iob->eod)
2681 * We did not receive any data, most likely because the
2682 * client is done. Don't log this as a parse failure.
2684 return JB_ERR_PARSE;
2686 /* XXX: Also used for JB_ERR_MEMORY */
2687 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2688 jb_err_to_string(err));
2689 ssl_send_data_delayed(&(csp->ssl_client_attr),
2690 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2694 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2695 request_line = get_header(csp->client_iob);
2696 if (request_line == NULL)
2698 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2699 ssl_send_data_delayed(&(csp->ssl_client_attr),
2700 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2701 return JB_ERR_PARSE;
2703 assert(*request_line != '\0');
2705 if (client_protocol_is_unsupported(csp, request_line))
2708 * If the protocol is unsupported we're done here.
2709 * client_protocol_is_unsupported() took care of sending
2710 * the error response and logging the error message.
2712 return JB_ERR_PARSE;
2715 #ifdef FEATURE_FORCE_LOAD
2716 if (force_required(csp, request_line))
2718 csp->flags |= CSP_FLAG_FORCED;
2720 #endif /* def FEATURE_FORCE_LOAD */
2722 free_http_request(csp->http);
2724 err = parse_http_request(request_line, csp->http);
2725 /* XXX: Restore ssl setting. This is ugly */
2726 csp->http->client_ssl = 1;
2727 csp->http->server_ssl = 1;
2729 freez(request_line);
2730 if (JB_ERR_OK != err)
2732 ssl_send_data_delayed(&(csp->ssl_client_attr),
2733 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2734 /* XXX: Use correct size */
2735 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2736 log_error(LOG_LEVEL_ERROR,
2737 "Couldn't parse request line received from %s: %s",
2738 csp->ip_addr_str, jb_err_to_string(err));
2740 free_http_request(csp->http);
2741 return JB_ERR_PARSE;
2744 /* Parse the rest of the client's headers. */
2748 p = get_header(csp->client_iob);
2752 /* There are no additional headers to read. */
2759 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2762 * Our attempts to get the request destination
2765 log_error(LOG_LEVEL_ERROR,
2766 "Failed to get the encrypted request destination");
2767 ssl_send_data_delayed(&(csp->ssl_client_attr),
2768 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2769 return JB_ERR_PARSE;
2772 /* Split the domain we just got for pattern matching */
2773 init_domain_components(csp->http);
2775 #ifdef FEATURE_CLIENT_TAGS
2776 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2777 if (csp->client_address == NULL)
2779 set_client_address(csp, headers);
2780 get_tag_list_for_client(csp->client_tags, csp->client_address);
2784 #ifdef FEATURE_TOGGLE
2785 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2789 * Determine the actions for this request after
2790 * clearing the ones from the previous one.
2792 free_current_action(csp->action);
2793 get_url_actions(csp, csp->http);
2796 enlist(csp->https_headers, csp->http->cmd);
2798 /* Append the previously read headers */
2799 err = list_append_list_unique(csp->https_headers, headers);
2800 destroy_list(headers);
2801 if (JB_ERR_OK != err)
2803 /* XXX: Send error message */
2807 /* XXX: Work around crash */
2808 csp->error_message = NULL;
2810 /* XXX: Why do this here? */
2813 err = sed_https(csp);
2814 if (JB_ERR_OK != err)
2816 ssl_send_data_delayed(&(csp->ssl_client_attr),
2817 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2818 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2820 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2821 csp->ip_addr_str, csp->http->cmd);
2822 return JB_ERR_PARSE;
2825 if ((NULL == csp->https_headers->first->str)
2826 || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2827 (JB_ERR_OK != change_encrypted_request_destination(csp))))
2829 ssl_send_data_delayed(&(csp->ssl_client_attr),
2830 (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2831 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2832 log_error(LOG_LEVEL_ERROR,
2833 "Invalid request line after applying header filters.");
2834 /* XXX: Use correct size */
2835 log_error(LOG_LEVEL_CLF,
2836 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2838 return JB_ERR_PARSE;
2841 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2842 log_applied_actions(csp->action);
2843 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2850 /*********************************************************************
2852 * Function : cgi_page_requested
2854 * Description : Checks if a request is for an internal CGI page.
2857 * 1 : host = The host requested by the client.
2859 * Returns : 1 if a CGI page has been requested, 0 otherwise
2861 *********************************************************************/
2862 static int cgi_page_requested(const char *host)
2864 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2865 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2866 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2867 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2877 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2878 /*********************************************************************
2880 * Function : continue_https_chat
2882 * Description : Behaves similar to chat() but only deals with
2883 * https-inspected requests that arrive on an already
2884 * established connection. The first request is always
2885 * served by chat() which is a lot more complex as it
2886 * has to deal with forwarding settings and connection
2889 * If a connection to the server has already been
2890 * opened it is reused unless the request is blocked
2891 * or the forwarder changed.
2893 * If a connection to the server has not yet been
2894 * opened (because the previous request was crunched),
2895 * or the forwarder changed, the connection is dropped
2896 * so that the client retries on a fresh one.
2899 * 1 : csp = Current client state (buffers, headers, etc...)
2901 * Returns : Nothing.
2903 *********************************************************************/
2904 static void continue_https_chat(struct client_state *csp)
2906 const struct forward_spec *fwd;
2908 if (JB_ERR_OK != process_encrypted_request(csp))
2910 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2914 csp->requests_received_total++;
2917 * We have an encrypted request. Check if one of the crunchers wants it.
2919 if (crunch_response_triggered(csp, crunchers_all))
2922 * Yes. The client got the crunch response and we're done here.
2926 if (csp->ssl_with_server_is_opened == 0)
2928 log_error(LOG_LEVEL_CONNECT,
2929 "Dropping the client connection on socket %d. "
2930 "The server connection has not been established yet.",
2932 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2935 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2937 fwd = forward_url(csp, csp->http);
2938 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2940 log_error(LOG_LEVEL_CONNECT,
2941 "Dropping the client connection on socket %d with "
2942 "server socket %d connected to %s. The forwarder has changed.",
2943 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2944 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2948 log_error(LOG_LEVEL_CONNECT,
2949 "Reusing server socket %d connected to %s. Requests already sent: %u.",
2950 csp->server_connection.sfd, csp->server_connection.host,
2951 csp->server_connection.requests_sent_total);
2953 if (send_https_request(csp))
2956 * Most likely the server connection timed out. We can't easily
2957 * create a new one so simply drop the client connection without a
2958 * error response to let the client retry.
2960 log_error(LOG_LEVEL_CONNECT,
2961 "Dropping client connection on socket %d. "
2962 "Forwarding the encrypted client request failed.",
2966 csp->server_connection.requests_sent_total++;
2967 handle_established_connection(csp);
2968 freez(csp->receive_buffer);
2970 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2974 /*********************************************************************
2976 * Function : handle_established_connection
2978 * Description : Shuffle data between client and server once the
2979 * connection has been established.
2982 * 1 : csp = Current client state (buffers, headers, etc...)
2984 * Returns : Nothing.
2986 *********************************************************************/
2987 static void handle_established_connection(struct client_state *csp)
2993 struct pollfd poll_fds[2];
2997 struct timeval timeout;
3000 int ms_iis5_hack = 0;
3001 unsigned long long byte_count = 0;
3002 struct http_request *http;
3003 long len = 0; /* for buffer sizes (and negative error codes) */
3004 int buffer_and_filter_content = 0;
3005 unsigned int write_delay;
3006 #ifdef FEATURE_HTTPS_INSPECTION
3008 int use_ssl_tunnel = 0;
3009 csp->dont_verify_certificate = 0;
3011 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3013 /* Pass encrypted content without filtering. */
3018 /* Skeleton for HTTP response, if we should intercept the request */
3019 struct http_response *rsp;
3020 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3021 int watch_client_socket;
3024 csp->receive_buffer_size = csp->config->receive_buffer_size;
3025 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3026 if (csp->receive_buffer == NULL)
3028 log_error(LOG_LEVEL_ERROR,
3029 "Out of memory. Failed to allocate the receive buffer.");
3030 rsp = cgi_error_memory();
3031 send_crunch_response(csp, rsp);
3038 maxfd = (csp->cfd > csp->server_connection.sfd) ?
3039 csp->cfd : csp->server_connection.sfd;
3042 /* pass data between the client and server
3043 * until one or the other shuts down the connection.
3048 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3049 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3051 write_delay = get_write_delay(csp);
3057 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3058 if (!watch_client_socket)
3060 maxfd = csp->server_connection.sfd;
3063 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3065 FD_SET(csp->cfd, &rfds);
3068 FD_SET(csp->server_connection.sfd, &rfds);
3069 #endif /* ndef HAVE_POLL */
3071 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3072 if ((csp->flags & CSP_FLAG_CHUNKED)
3073 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3074 && ((csp->iob->eod - csp->iob->cur) >= 5)
3075 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3078 * XXX: This check should be obsolete now,
3079 * but let's wait a while to be sure.
3081 log_error(LOG_LEVEL_CONNECT,
3082 "Looks like we got the last chunk together with "
3083 "the server headers but didn't detect it earlier. "
3084 "We better stop reading.");
3085 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3086 csp->expected_content_length = byte_count;
3087 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3089 if (server_body && server_response_is_complete(csp, byte_count))
3091 if (csp->expected_content_length == byte_count)
3093 log_error(LOG_LEVEL_CONNECT,
3094 "Done reading from server. Content length: %llu as expected. "
3095 "Bytes most recently read: %ld.",
3100 log_error(LOG_LEVEL_CONNECT,
3101 "Done reading from server. Expected content length: %llu. "
3102 "Actual content length: %llu. Bytes most recently read: %ld.",
3103 csp->expected_content_length, byte_count, len);
3107 * XXX: Should not jump around, handle_established_connection()
3108 * is complicated enough already.
3112 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3115 poll_fds[0].fd = csp->cfd;
3116 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3117 if (!watch_client_socket)
3120 * Ignore incoming data, but still watch out
3121 * for disconnects etc. These flags are always
3122 * implied anyway but explicitly setting them
3125 poll_fds[0].events = POLLERR|POLLHUP;
3130 poll_fds[0].events = POLLIN;
3132 poll_fds[1].fd = csp->server_connection.sfd;
3133 poll_fds[1].events = POLLIN;
3134 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3136 timeout.tv_sec = csp->config->socket_timeout;
3137 timeout.tv_usec = 0;
3138 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3139 #endif /* def HAVE_POLL */
3141 /*server or client not responding in timeout */
3144 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3145 csp->config->socket_timeout, http->url);
3146 if ((byte_count == 0) && (http->ssl == 0))
3148 send_crunch_response(csp, error_response(csp, "connection-timeout"));
3150 mark_server_socket_tainted(csp);
3151 #ifdef FEATURE_HTTPS_INSPECTION
3152 close_client_and_server_ssl_connections(csp);
3159 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3161 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3163 mark_server_socket_tainted(csp);
3164 #ifdef FEATURE_HTTPS_INSPECTION
3165 close_client_and_server_ssl_connections(csp);
3171 * This is the body of the browser's request,
3172 * just read and write it.
3174 * Receives data from browser and sends it to server
3176 * XXX: Make sure the client doesn't use pipelining
3177 * behind Privoxy's back.
3180 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3182 log_error(LOG_LEVEL_CONNECT,
3183 "The client socket %d has become unusable while "
3184 "the server socket %d is still open.",
3185 csp->cfd, csp->server_connection.sfd);
3186 mark_server_socket_tainted(csp);
3190 if (poll_fds[0].revents != 0)
3192 if (FD_ISSET(csp->cfd, &rfds))
3193 #endif /* def HAVE_POLL*/
3195 int max_bytes_to_read = (int)csp->receive_buffer_size;
3197 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3198 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3200 if (data_is_available(csp->cfd, 0))
3203 * If the next request is already waiting, we have
3204 * to stop select()ing the client socket. Otherwise
3205 * we would always return right away and get nothing
3208 watch_client_socket = 0;
3209 log_error(LOG_LEVEL_CONNECT,
3210 "Stop watching client socket %d. "
3211 "There's already another request waiting.",
3216 * If the client socket is set, but there's no data
3217 * available on the socket, the client went fishing
3218 * and continuing talking to the server makes no sense.
3220 log_error(LOG_LEVEL_CONNECT,
3221 "The client closed socket %d while "
3222 "the server socket %d is still open.",
3223 csp->cfd, csp->server_connection.sfd);
3224 mark_server_socket_tainted(csp);
3227 if (csp->expected_client_content_length != 0)
3229 if (csp->expected_client_content_length < csp->receive_buffer_size)
3231 max_bytes_to_read = (int)csp->expected_client_content_length;
3233 log_error(LOG_LEVEL_CONNECT,
3234 "Waiting for up to %d bytes from the client.",
3237 assert(max_bytes_to_read <= csp->receive_buffer_size);
3238 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3240 #ifdef FEATURE_HTTPS_INSPECTION
3241 if (client_use_ssl(csp))
3243 if (csp->http->status == 101)
3245 len = ssl_recv_data(&(csp->ssl_client_attr),
3246 (unsigned char *)csp->receive_buffer,
3247 (size_t)max_bytes_to_read);
3250 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3251 "on client socket %d for an upgraded connection",
3257 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3258 "on client socket %d for an upgraded connection",
3262 byte_count += (unsigned long long)len;
3263 len = ssl_send_data(&(csp->ssl_server_attr),
3264 (unsigned char *)csp->receive_buffer, (size_t)len);
3267 log_error(LOG_LEVEL_ERROR, "Failed to send data "
3268 "on server socket %d for an upgraded connection",
3269 csp->server_connection.sfd);
3274 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3278 #endif /* def FEATURE_HTTPS_INSPECTION */
3280 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3284 /* XXX: not sure if this is necessary. */
3285 mark_server_socket_tainted(csp);
3286 break; /* "game over, man" */
3289 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3290 if (csp->expected_client_content_length != 0)
3292 assert(len <= max_bytes_to_read);
3293 csp->expected_client_content_length -= (unsigned)len;
3294 log_error(LOG_LEVEL_CONNECT,
3295 "Expected client content length set to %llu "
3296 "after reading %ld bytes.",
3297 csp->expected_client_content_length, len);
3298 if (csp->expected_client_content_length == 0)
3300 log_error(LOG_LEVEL_CONNECT,
3301 "Done reading from the client.");
3302 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3305 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3307 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3309 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3310 mark_server_socket_tainted(csp);
3318 * The server wants to talk. It could be the header or the body.
3319 * If `hdr' is null, then it's the header otherwise it's the body.
3320 * FIXME: Does `hdr' really mean `host'? No.
3323 if (poll_fds[1].revents != 0)
3325 if (FD_ISSET(csp->server_connection.sfd, &rfds))
3326 #endif /* HAVE_POLL */
3328 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3330 * If we are buffering content, we don't want to eat up to
3331 * buffer-limit bytes if the client no longer cares about them.
3332 * If we aren't buffering, however, a dead client socket will be
3333 * noticed pretty much right away anyway, so we can reduce the
3334 * overhead by skipping the check.
3336 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3339 log_error(LOG_LEVEL_CONNECT,
3340 "The server still wants to talk, but the client may already have hung up on us.");
3342 log_error(LOG_LEVEL_CONNECT,
3343 "The server still wants to talk, but the client hung up on us.");
3344 mark_server_socket_tainted(csp);
3345 #ifdef FEATURE_HTTPS_INSPECTION
3346 close_client_and_server_ssl_connections(csp);
3349 #endif /* def _WIN32 */
3351 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3353 #ifdef FEATURE_HTTPS_INSPECTION
3355 * Reading data from standard or secured connection (HTTP/HTTPS)
3357 if (server_use_ssl(csp))
3359 len = ssl_recv_data(&(csp->ssl_server_attr),
3360 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3365 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3366 (int)csp->receive_buffer_size);
3371 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3373 if ((http->ssl && (csp->fwd == NULL))
3374 #ifdef FEATURE_HTTPS_INSPECTION
3380 * Just hang up. We already confirmed the client's CONNECT
3381 * request with status code 200 and unencrypted content is
3382 * no longer welcome.
3384 log_error(LOG_LEVEL_ERROR,
3385 "CONNECT already confirmed. Unable to tell the client about the problem.");
3388 else if (byte_count)
3391 * Just hang up. We already transmitted the original headers
3392 * and parts of the original content and therefore missed the
3393 * chance to send an error message (without risking data corruption).
3395 * XXX: we could retry with a fancy range request here.
3397 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3398 "Unable to tell the client about the problem.");
3399 mark_server_socket_tainted(csp);
3400 #ifdef FEATURE_HTTPS_INSPECTION
3401 close_client_and_server_ssl_connections(csp);
3406 * XXX: Consider handling the cases above the same.
3408 mark_server_socket_tainted(csp);
3412 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3413 if (csp->flags & CSP_FLAG_CHUNKED)
3415 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3417 /* XXX: this is a temporary hack */
3418 log_error(LOG_LEVEL_CONNECT,
3419 "Looks like we reached the end of the last chunk. "
3420 "We better stop reading.");
3421 csp->expected_content_length = byte_count + (unsigned long long)len;
3422 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3426 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3429 * This is guaranteed by allocating with zalloc_or_die()
3430 * and never (intentionally) writing to the last byte.
3432 * csp->receive_buffer_size is the size of the part of the
3433 * buffer we intentionally write to, but we actually
3434 * allocated csp->receive_buffer_size+1 bytes so the assertion
3435 * stays within the allocated range.
3437 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3440 * Add a trailing zero to let be able to use string operations.
3441 * XXX: do we still need this with filter_popups gone?
3443 assert(len <= csp->receive_buffer_size);
3444 csp->receive_buffer[len] = '\0';
3447 * Normally, this would indicate that we've read
3448 * as much as the server has sent us and we can
3449 * close the client connection. However, Microsoft
3450 * in its wisdom has released IIS/5 with a bug that
3451 * prevents it from sending the trailing \r\n in
3452 * a 302 redirect header (and possibly other headers).
3453 * To work around this if we've haven't parsed
3454 * a full header we'll append a trailing \r\n
3455 * and see if this now generates a valid one.
3457 * This hack shouldn't have any impacts. If we've
3458 * already transmitted the header or if this is a
3459 * SSL connection, then we won't bother with this
3460 * hack. So we only work on partially received
3461 * headers. If we append a \r\n and this still
3462 * doesn't generate a valid header, then we won't
3463 * transmit anything to the client.
3468 if (server_body || (http->ssl
3469 #ifdef FEATURE_HTTPS_INSPECTION
3475 * If we have been buffering up the document,
3476 * now is the time to apply content modification
3477 * and send the result to the client.
3479 if (buffer_and_filter_content)
3481 p = execute_content_filters(csp);
3483 * If content filtering fails, use the original
3484 * buffer and length.
3485 * (see p != NULL ? p : csp->iob->cur below)
3489 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3491 #ifdef FEATURE_COMPRESSION
3492 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3493 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3495 char *compressed_content = compress_buffer(p,
3496 (size_t *)&csp->content_length, csp->config->compression_level);
3497 if (compressed_content != NULL)
3500 p = compressed_content;
3501 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3506 if (JB_ERR_OK != update_server_headers(csp))
3508 log_error(LOG_LEVEL_FATAL,
3509 "Failed to update server headers. after filtering.");
3512 hdr = list_to_text(csp->headers);
3515 /* FIXME Should handle error properly */
3516 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3519 #ifdef FEATURE_HTTPS_INSPECTION
3521 * Sending data with standard or secured connection (HTTP/HTTPS)
3523 if (client_use_ssl(csp))
3525 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3526 (const unsigned char *)hdr, strlen(hdr),
3527 get_write_delay(csp)) < 0)
3528 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3529 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3530 csp->content_length, get_write_delay(csp)) < 0))
3532 log_error(LOG_LEVEL_ERROR, "write modified content to "
3533 "client over TLS/SSL failed");
3536 mark_server_socket_tainted(csp);
3537 close_client_and_server_ssl_connections(csp);
3542 #endif /* def FEATURE_HTTPS_INSPECTION */
3544 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3545 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3546 (size_t)csp->content_length, write_delay))
3548 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3551 mark_server_socket_tainted(csp);
3560 break; /* "game over, man" */
3564 * This is NOT the body, so
3565 * Let's pretend the server just sent us a blank line.
3567 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3568 len = (int)strlen(csp->receive_buffer);
3571 * Now, let the normal header parsing algorithm below do its
3572 * job. If it fails, we'll exit instead of continuing.
3579 * If we're in the body of the server document, just write it to
3580 * the client, unless we need to buffer the body for later
3581 * content-filtering.
3583 if (server_body || (http->ssl
3584 #ifdef FEATURE_HTTPS_INSPECTION
3589 if (buffer_and_filter_content)
3592 * If there is no memory left for buffering the content, or the buffer limit
3593 * has been reached, switch to non-filtering mode, i.e. make & write the
3594 * header, flush the iob and buf, and get out of the way.
3596 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3601 log_error(LOG_LEVEL_INFO,
3602 "Flushing header and buffers. Stepping back from filtering.");
3604 hdr = list_to_text(csp->headers);
3608 * Memory is too tight to even generate the header.
3609 * Send our static "Out-of-memory" page.
3611 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3612 rsp = cgi_error_memory();
3613 send_crunch_response(csp, rsp);
3614 mark_server_socket_tainted(csp);
3615 #ifdef FEATURE_HTTPS_INSPECTION
3616 close_client_and_server_ssl_connections(csp);
3620 hdrlen = strlen(hdr);
3622 #ifdef FEATURE_HTTPS_INSPECTION
3624 * Sending data with standard or secured connection (HTTP/HTTPS)
3626 if (client_use_ssl(csp))
3628 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3629 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3630 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3632 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3633 (const unsigned char *)csp->receive_buffer, (size_t)len,
3634 get_write_delay(csp)) < 0))
3636 log_error(LOG_LEVEL_CONNECT,
3637 "Flush header and buffers to client failed");
3639 mark_server_socket_tainted(csp);
3640 close_client_and_server_ssl_connections(csp);
3645 #endif /* def FEATURE_HTTPS_INSPECTION */
3647 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3648 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3649 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3652 log_error(LOG_LEVEL_CONNECT,
3653 "Flush header and buffers to client failed: %E");
3655 mark_server_socket_tainted(csp);
3661 * Reset the byte_count to the amount of bytes
3662 * we just flushed. len will be added a few lines below,
3663 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3665 byte_count = (unsigned long long)flushed;
3667 buffer_and_filter_content = 0;
3673 #ifdef FEATURE_HTTPS_INSPECTION
3675 * Sending data with standard or secured connection (HTTP/HTTPS)
3677 if (client_use_ssl(csp))
3679 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3680 (const unsigned char *)csp->receive_buffer, (size_t)len,
3681 get_write_delay(csp));
3684 log_error(LOG_LEVEL_ERROR,
3685 "Sending data to client failed");
3686 mark_server_socket_tainted(csp);
3687 close_client_and_server_ssl_connections(csp);
3692 #endif /* def FEATURE_HTTPS_INSPECTION */
3694 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3695 (size_t)len, write_delay))
3697 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3698 mark_server_socket_tainted(csp);
3703 byte_count += (unsigned long long)len;
3709 * We're still looking for the end of the server's header.
3710 * Buffer up the data we just read. If that fails, there's
3711 * little we can do but send our static out-of-memory page.
3713 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3715 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3716 rsp = cgi_error_memory();
3717 send_crunch_response(csp, rsp);
3718 mark_server_socket_tainted(csp);
3719 #ifdef FEATURE_HTTPS_INSPECTION
3720 close_client_and_server_ssl_connections(csp);
3725 /* Convert iob into something sed() can digest */
3726 if (JB_ERR_PARSE == get_server_headers(csp))
3731 * Well, we tried our MS IIS/5 hack and it didn't work.
3732 * The header is incomplete and there isn't anything
3733 * we can do about it.
3735 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3736 "Applying the MS IIS5 hack didn't help.");
3737 log_error(LOG_LEVEL_CLF,
3738 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3739 #ifdef FEATURE_HTTPS_INSPECTION
3741 * Sending data with standard or secured connection (HTTP/HTTPS)
3743 if (client_use_ssl(csp))
3745 ssl_send_data_delayed(&(csp->ssl_client_attr),
3746 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3747 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3750 #endif /* def FEATURE_HTTPS_INSPECTION */
3752 write_socket_delayed(csp->cfd,
3753 INVALID_SERVER_HEADERS_RESPONSE,
3754 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3756 mark_server_socket_tainted(csp);
3757 #ifdef FEATURE_HTTPS_INSPECTION
3758 close_client_and_server_ssl_connections(csp);
3765 * Since we have to wait for more from the server before
3766 * we can parse the headers we just continue here.
3768 log_error(LOG_LEVEL_CONNECT,
3769 "Continuing buffering server headers from socket %d. "
3770 "Bytes most recently read: %ld.", csp->cfd, len);
3777 * Account for the content bytes we
3778 * might have gotten with the headers.
3780 assert(csp->iob->eod >= csp->iob->cur);
3781 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3784 /* Did we actually get anything? */
3785 if (NULL == csp->headers->first)
3787 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3789 log_error(LOG_LEVEL_ERROR,
3790 "No server or forwarder response received on socket %d. "
3791 "Closing client socket %d without sending data.",
3792 csp->server_connection.sfd, csp->cfd);
3793 log_error(LOG_LEVEL_CLF,
3794 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3798 log_error(LOG_LEVEL_ERROR,
3799 "No server or forwarder response received on socket %d.",
3800 csp->server_connection.sfd);
3801 send_crunch_response(csp, error_response(csp, "no-server-data"));
3803 free_http_request(http);
3804 mark_server_socket_tainted(csp);
3805 #ifdef FEATURE_HTTPS_INSPECTION
3806 close_client_and_server_ssl_connections(csp);
3811 if (!csp->headers->first->str)
3813 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3815 assert(csp->headers->first->str);
3817 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3818 strncmpic(csp->headers->first->str, "ICY", 3))
3821 * It doesn't look like a HTTP (or Shoutcast) response:
3822 * tell the client and log the problem.
3824 if (strlen(csp->headers->first->str) > 30)
3826 csp->headers->first->str[30] = '\0';
3828 log_error(LOG_LEVEL_ERROR,
3829 "Invalid server or forwarder response. Starts with: %s",
3830 csp->headers->first->str);
3831 log_error(LOG_LEVEL_CLF,
3832 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3833 #ifdef FEATURE_HTTPS_INSPECTION
3835 * Sending data with standard or secured connection (HTTP/HTTPS)
3837 if (client_use_ssl(csp))
3839 ssl_send_data_delayed(&(csp->ssl_client_attr),
3840 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3841 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3842 get_write_delay(csp));
3845 #endif /* def FEATURE_HTTPS_INSPECTION */
3847 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3848 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3850 free_http_request(http);
3851 mark_server_socket_tainted(csp);
3852 #ifdef FEATURE_HTTPS_INSPECTION
3853 close_client_and_server_ssl_connections(csp);
3859 * We have now received the entire server header,
3860 * filter it and send the result to the client
3862 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3864 log_error(LOG_LEVEL_CLF,
3865 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3866 #ifdef FEATURE_HTTPS_INSPECTION
3868 * Sending data with standard or secured connection (HTTP/HTTPS)
3870 if (client_use_ssl(csp))
3872 ssl_send_data_delayed(&(csp->ssl_client_attr),
3873 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3874 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3875 get_write_delay(csp));
3880 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3881 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3883 free_http_request(http);
3884 mark_server_socket_tainted(csp);
3885 #ifdef FEATURE_HTTPS_INSPECTION
3886 close_client_and_server_ssl_connections(csp);
3890 hdr = list_to_text(csp->headers);
3893 /* FIXME Should handle error properly */
3894 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3897 if ((csp->flags & CSP_FLAG_CHUNKED)
3898 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3899 && ((csp->iob->eod - csp->iob->cur) >= 5)
3900 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3902 log_error(LOG_LEVEL_CONNECT,
3903 "Looks like we got the last chunk together with "
3904 "the server headers. We better stop reading.");
3905 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3906 csp->expected_content_length = byte_count;
3907 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3910 csp->server_connection.response_received = time(NULL);
3912 if (crunch_response_triggered(csp, crunchers_light))
3915 * One of the tags created by a server-header
3916 * tagger triggered a crunch. We already
3917 * delivered the crunch response to the client
3918 * and are done here after cleaning up.
3921 mark_server_socket_tainted(csp);
3922 #ifdef FEATURE_HTTPS_INSPECTION
3923 close_client_and_server_ssl_connections(csp);
3928 /* Buffer and pcrs filter this if appropriate. */
3929 buffer_and_filter_content = content_requires_filtering(csp);
3931 if (!buffer_and_filter_content)
3934 * Write the server's (modified) header to
3935 * the client (along with anything else that
3936 * may be in the buffer). Use standard or secured
3939 #ifdef FEATURE_HTTPS_INSPECTION
3940 if (client_use_ssl(csp))
3942 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3943 (const unsigned char *)hdr, strlen(hdr),
3944 get_write_delay(csp)) < 0)
3945 || ((len = ssl_flush_socket(&(csp->ssl_client_attr),
3948 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3951 * The write failed, so don't bother mentioning it
3952 * to the client... it probably can't hear us anyway.
3955 mark_server_socket_tainted(csp);
3956 #ifdef FEATURE_HTTPS_INSPECTION
3957 close_client_and_server_ssl_connections(csp);
3963 #endif /* def FEATURE_HTTPS_INSPECTION */
3965 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3966 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3968 log_error(LOG_LEVEL_ERROR,
3969 "write header to client failed");
3971 * The write failed, so don't bother mentioning it
3972 * to the client... it probably can't hear us anyway.
3975 mark_server_socket_tainted(csp);
3981 /* we're finished with the server's header */
3987 * If this was a MS IIS/5 hack then it means the server
3988 * has already closed the connection. Nothing more to read.
3993 log_error(LOG_LEVEL_ERROR,
3994 "Closed server connection detected. "
3995 "Applying the MS IIS5 hack didn't help.");
3996 log_error(LOG_LEVEL_CLF,
3997 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3998 #ifdef FEATURE_HTTPS_INSPECTION
4000 * Sending data with standard or secured connection (HTTP/HTTPS)
4002 if (client_use_ssl(csp))
4004 ssl_send_data_delayed(&(csp->ssl_client_attr),
4005 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4006 strlen(INVALID_SERVER_HEADERS_RESPONSE),
4007 get_write_delay(csp));
4010 #endif /* def FEATURE_HTTPS_INSPECTION */
4012 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4013 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4015 mark_server_socket_tainted(csp);
4016 #ifdef FEATURE_HTTPS_INSPECTION
4017 close_client_and_server_ssl_connections(csp);
4024 mark_server_socket_tainted(csp);
4025 #ifdef FEATURE_HTTPS_INSPECTION
4026 close_client_and_server_ssl_connections(csp);
4028 return; /* huh? we should never get here */
4031 if (csp->content_length == 0)
4034 * If Privoxy didn't recalculate the Content-Length,
4035 * byte_count is still correct.
4037 csp->content_length = byte_count;
4040 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4041 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4042 && (csp->expected_content_length != byte_count))
4044 log_error(LOG_LEVEL_CONNECT,
4045 "Received %llu bytes while expecting %llu.",
4046 byte_count, csp->expected_content_length);
4047 mark_server_socket_tainted(csp);
4051 #ifdef FEATURE_HTTPS_INSPECTION
4052 if (client_use_ssl(csp))
4054 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4055 csp->ip_addr_str, http->gpc, http->hostport, http->path,
4056 http->version, csp->content_length);
4061 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4062 csp->ip_addr_str, http->ocmd, csp->content_length);
4064 csp->server_connection.timestamp = time(NULL);
4068 /*********************************************************************
4072 * Description : Once a connection from the client has been accepted,
4073 * this function is called (via serve()) to handle the
4074 * main business of the communication. This function
4075 * returns after dealing with a single request. It can
4076 * be called multiple times with the same client socket
4077 * if the client is keeping the connection alive.
4079 * The decision whether or not a client connection will
4080 * be kept alive is up to the caller which also must
4081 * close the client socket when done.
4083 * FIXME: chat is nearly thousand lines long.
4087 * 1 : csp = Current client state (buffers, headers, etc...)
4089 * Returns : Nothing.
4091 *********************************************************************/
4092 static void chat(struct client_state *csp)
4094 const struct forward_spec *fwd;
4095 struct http_request *http;
4096 /* Skeleton for HTTP response, if we should intercept the request */
4097 struct http_response *rsp;
4098 #ifdef FEATURE_HTTPS_INSPECTION
4099 int use_ssl_tunnel = 0;
4104 if (receive_client_request(csp) != JB_ERR_OK)
4108 if (parse_client_request(csp) != JB_ERR_OK)
4113 /* decide how to route the HTTP request */
4114 fwd = forward_url(csp, http);
4116 #ifdef FEATURE_HTTPS_INSPECTION
4118 * Setting flags to use old solution with SSL tunnel and to disable
4119 * certificate verification.
4121 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4122 && !cgi_page_requested(csp->http->host))
4127 if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4129 csp->dont_verify_certificate = 1;
4134 * build the http request to send to the server
4135 * we have to do one of the following:
4137 * create = use the original HTTP request to create a new
4138 * HTTP request that has either the path component
4139 * without the http://domainspec (w/path) or the
4140 * full orininal URL (w/url)
4141 * Note that the path and/or the HTTP version may
4142 * have been altered by now.
4144 * SSL proxy = Open a socket to the host:port of the server
4145 * and create TLS/SSL connection with server and
4146 * with client. Then behave like mediator between
4147 * client and server over TLS/SSL.
4149 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4150 * with request to a parent proxy. Note that we'll be sending
4151 * forwarding the CFAIL message ourselves if connecting to the parent
4152 * fails, but we won't send a CSUCCEED message if it works,
4153 * since that would result in a double message (ours and the
4154 * parent's). After sending the request to the parent, we
4155 * must parse answer and send it to client. If connection
4156 * with server is established, we do TLS/SSL proxy. Otherwise
4157 * we send parent response to client and close connections.
4159 * here's the matrix:
4162 * +--------+--------+
4164 * 0 | create | SSL |
4165 * | w/path | proxy |
4166 * Forwarding +--------+--------+
4168 * 1 | create | proxy |
4169 * | w/url |+forward|
4170 * +--------+--------+
4174 #ifdef FEATURE_HTTPS_INSPECTION
4176 * Presetting SSL client and server flags
4178 if (http->ssl && !use_ssl_tunnel)
4180 http->client_ssl = 1;
4181 http->server_ssl = 1;
4185 http->client_ssl = 0;
4186 http->server_ssl = 0;
4190 #ifdef FEATURE_HTTPS_INSPECTION
4192 * Log the request unless we're https inspecting
4193 * in which case we don't have the path yet and
4194 * will log the request later.
4196 if (!client_use_ssl(csp))
4199 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4202 if (http->ssl && connect_port_is_forbidden(csp))
4204 const char *acceptable_connect_ports =
4205 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4206 assert(NULL != acceptable_connect_ports);
4207 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4208 "limit-connect{%s} doesn't allow CONNECT requests to %s",
4209 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4210 csp->action->flags |= ACTION_BLOCK;
4212 #ifdef FEATURE_HTTPS_INSPECTION
4213 http->client_ssl = 0;
4214 http->server_ssl = 0;
4219 freez(csp->headers->first->str);
4220 build_request_line(csp, fwd, &csp->headers->first->str);
4223 * We have a request. Check if one of the crunchers wants it
4224 * unless the client wants to use TLS/SSL in which case we
4225 * haven't setup the TLS context yet and will send the crunch
4229 #ifdef FEATURE_HTTPS_INSPECTION
4230 !client_use_ssl(csp) &&
4232 crunch_response_triggered(csp, crunchers_all))
4235 * Yes. The client got the crunch response and we're done here.
4240 log_applied_actions(csp->action);
4241 if (fwd->forward_host)
4243 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4244 fwd->forward_host, fwd->forward_port, http->hostport);
4248 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4251 /* here we connect to the server, gateway, or the forwarder */
4253 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4254 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4255 && socket_is_still_alive(csp->server_connection.sfd)
4256 && connection_destination_matches(&csp->server_connection, http, fwd))
4258 log_error(LOG_LEVEL_CONNECT,
4259 "Reusing server socket %d connected to %s. Total requests: %u.",
4260 csp->server_connection.sfd, csp->server_connection.host,
4261 csp->server_connection.requests_sent_total);
4265 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4267 #ifdef FEATURE_CONNECTION_SHARING
4268 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4269 #ifdef FEATURE_HTTPS_INSPECTION
4270 && !server_use_ssl(csp)
4274 remember_connection(&csp->server_connection);
4277 #endif /* def FEATURE_CONNECTION_SHARING */
4279 log_error(LOG_LEVEL_CONNECT,
4280 "Closing server socket %d connected to %s. Total requests: %u.",
4281 csp->server_connection.sfd, csp->server_connection.host,
4282 csp->server_connection.requests_sent_total);
4283 close_socket(csp->server_connection.sfd);
4285 mark_connection_closed(&csp->server_connection);
4287 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4288 #ifdef FEATURE_HTTPS_INSPECTION
4289 if (client_use_ssl(csp) && !use_ssl_tunnel)
4293 * Creating a SSL proxy.
4295 * By sending the CSUCCEED message we're lying to the client as
4296 * the connection hasn't actually been established yet. We don't
4297 * establish the connection until we have seen and parsed the
4298 * encrypted client headers.
4300 if (write_socket_delayed(csp->cfd, CSUCCEED,
4301 strlen(CSUCCEED), get_write_delay(csp)) != 0)
4303 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4307 ret = create_client_ssl_connection(csp);
4310 log_error(LOG_LEVEL_ERROR,
4311 "Failed to open a secure connection with the client");
4314 if (JB_ERR_OK != process_encrypted_request(csp))
4316 close_client_ssl_connection(csp);
4320 * We have an encrypted request. Check if one of the crunchers now
4321 * wants it (for example because the previously invisible path was
4322 * required to match).
4324 if (crunch_response_triggered(csp, crunchers_all))
4327 * Yes. The client got the crunch response and we're done here.
4334 * Connecting to destination server
4336 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4338 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4340 if (fwd->type != SOCKS_NONE)
4343 rsp = error_response(csp, "forwarding-failed");
4345 else if (errno == EINVAL)
4347 rsp = error_response(csp, "no-such-domain");
4351 rsp = error_response(csp, "connect-failed");
4354 /* Write the answer to the client */
4357 send_crunch_response(csp, rsp);
4361 * Temporary workaround to prevent already-read client
4362 * bodies from being parsed as new requests. For now we
4363 * err on the safe side and throw all the following
4364 * requests under the bus, even if no client body has been
4365 * buffered. A compliant client will repeat the dropped
4366 * requests on an untainted connection.
4368 * The proper fix is to discard the no longer needed
4369 * client body in the buffer (if there is one) and to
4370 * continue parsing the bytes that follow.
4372 #ifdef FEATURE_HTTPS_INSPECTION
4373 close_client_ssl_connection(csp);
4375 drain_and_close_socket(csp->cfd);
4376 csp->cfd = JB_INVALID_SOCKET;
4381 #ifdef FEATURE_HTTPS_INSPECTION
4383 * Creating TLS/SSL connections with destination server or parent
4384 * proxy. If forwarding is enabled, we must send client request to
4385 * parent proxy and receive, parse and resend parent proxy answer.
4387 if (http->ssl && !use_ssl_tunnel)
4389 if (fwd->forward_host != NULL)
4391 char server_response[BUFFER_SIZE];
4394 char *hdr = list_to_text(csp->headers);
4395 memset(server_response, 0, sizeof(server_response));
4399 log_error(LOG_LEVEL_FATAL,
4400 "Out of memory parsing client header");
4402 list_remove_all(csp->headers);
4405 * Sending client's CONNECT request to the parent proxy
4407 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4413 log_error(LOG_LEVEL_CONNECT,
4414 "Sending request headers to: %s failed", http->hostport);
4415 mark_server_socket_tainted(csp);
4416 close_client_ssl_connection(csp);
4420 /* Waiting for parent proxy server response */
4421 len = read_socket(csp->server_connection.sfd, server_response,
4422 sizeof(server_response)-1);
4426 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4427 "server on socket %d.", csp->server_connection.sfd);
4429 rsp = error_response(csp, "no-server-data");
4432 send_crunch_response(csp, rsp);
4434 mark_server_socket_tainted(csp);
4435 close_client_ssl_connection(csp);
4440 * Test if the connection to the destination server was
4441 * established successfully by the parent proxy.
4443 if (!tunnel_established_successfully(server_response, (unsigned int)len))
4445 log_error(LOG_LEVEL_ERROR,
4446 "The forwarder %s failed to establish a connection with %s",
4447 fwd->forward_host, http->host);
4448 rsp = error_response(csp, "connect-failed");
4451 send_crunch_response(csp, rsp);
4453 mark_server_socket_tainted(csp);
4454 close_client_ssl_connection(csp);
4457 } /* -END- if (fwd->forward_host != NULL) */
4460 * We can now create the TLS/SSL connection with the destination server.
4462 int ret = create_server_ssl_connection(csp);
4465 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4466 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4469 * If the server certificate is invalid, we must inform
4470 * the client and then close connection to the client.
4472 ssl_send_certificate_error(csp);
4473 close_client_and_server_ssl_connections(csp);
4476 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4477 || csp->server_cert_verification_result == SSL_CERT_VALID)
4480 * The TLS/SSL connection wasn't created but an invalid
4481 * certificate wasn't detected. Report it as connection
4484 rsp = error_response(csp, "connect-failed");
4487 send_crunch_response(csp, rsp);
4489 close_client_and_server_ssl_connections(csp);
4493 }/* -END- if (http->ssl) */
4494 #endif /* def FEATURE_HTTPS_INSPECTION */
4496 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4497 save_connection_destination(csp->server_connection.sfd,
4498 http, fwd, &csp->server_connection);
4499 csp->server_connection.keep_alive_timeout =
4500 (unsigned)csp->config->keep_alive_timeout;
4502 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4504 csp->server_connection.requests_sent_total++;
4506 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4508 /* Client headers have been sent optimistically */
4509 assert(csp->headers->last == NULL);
4511 else if (http->ssl == 0 || (fwd->forward_host
4512 #ifdef FEATURE_HTTPS_INSPECTION
4517 if (send_http_request(csp))
4519 rsp = error_response(csp, "connect-failed");
4522 send_crunch_response(csp, rsp);
4530 * Using old solution with SSL tunnel or new solution with SSL proxy
4532 list_remove_all(csp->headers);
4533 #ifdef FEATURE_HTTPS_INSPECTION
4538 * We're running an SSL tunnel and we're not forwarding,
4539 * so just ditch the client headers, send the "connect succeeded"
4540 * message to the client, flush the rest, and get out of the way.
4542 if (write_socket_delayed(csp->cfd, CSUCCEED,
4543 strlen(CSUCCEED), get_write_delay(csp)))
4548 #ifdef FEATURE_HTTPS_INSPECTION
4552 * If server certificate has been verified and is invalid,
4553 * we must inform the client and then close the connection
4554 * with client and server.
4556 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4557 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4559 ssl_send_certificate_error(csp);
4560 close_client_and_server_ssl_connections(csp);
4563 if (send_https_request(csp))
4565 rsp = error_response(csp, "connect-failed");
4568 send_crunch_response(csp, rsp);
4570 close_client_and_server_ssl_connections(csp);
4574 #endif /* def FEATURE_HTTPS_INSPECTION */
4575 clear_iob(csp->client_iob);
4576 }/* -END- else ... if (http->ssl == 1) */
4578 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4580 /* XXX: should the time start earlier for optimistically sent data? */
4581 csp->server_connection.request_sent = time(NULL);
4583 handle_established_connection(csp);
4584 freez(csp->receive_buffer);
4589 /*********************************************************************
4591 * Function : fuzz_server_response
4593 * Description : Treat the input as a whole server response.
4596 * 1 : csp = Current client state (buffers, headers, etc...)
4597 * 2 : fuzz_input_file = File to read the input from.
4601 *********************************************************************/
4602 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4604 static struct forward_spec fwd; /* Zero'd due to being static */
4607 if (strcmp(fuzz_input_file, "-") == 0)
4609 /* XXX: Doesn't work yet. */
4610 csp->server_connection.sfd = 0;
4614 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4615 if (csp->server_connection.sfd == -1)
4617 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4622 csp->content_type |= CT_GIF;
4623 csp->action->flags |= ACTION_DEANIMATE;
4624 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4626 csp->http->path = strdup_or_die("/");
4627 csp->http->host = strdup_or_die("fuzz.example.org");
4628 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4629 /* Prevent client socket monitoring */
4630 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4631 csp->flags |= CSP_FLAG_CHUNKED;
4633 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4634 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4636 csp->content_type |= CT_DECLARED|CT_GIF;
4638 csp->config->socket_timeout = 0;
4640 cgi_init_error_messages();
4642 handle_established_connection(csp);
4643 freez(csp->receive_buffer);
4650 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4651 /*********************************************************************
4653 * Function : prepare_csp_for_next_request
4655 * Description : Put the csp in a mostly vergin state.
4658 * 1 : csp = Current client state (buffers, headers, etc...)
4662 *********************************************************************/
4663 static void prepare_csp_for_next_request(struct client_state *csp)
4665 csp->content_type = 0;
4666 csp->content_length = 0;
4667 csp->expected_content_length = 0;
4668 csp->expected_client_content_length = 0;
4669 list_remove_all(csp->headers);
4670 clear_iob(csp->iob);
4671 freez(csp->error_message);
4672 free_http_request(csp->http);
4673 destroy_list(csp->headers);
4674 #ifdef FEATURE_HTTPS_INSPECTION
4675 destroy_list(csp->https_headers);
4677 destroy_list(csp->tags);
4678 #ifdef FEATURE_CLIENT_TAGS
4679 destroy_list(csp->client_tags);
4680 freez(csp->client_address);
4682 free_current_action(csp->action);
4683 if (NULL != csp->fwd)
4685 unload_forward_spec(csp->fwd);
4688 /* XXX: Store per-connection flags someplace else. */
4689 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4690 #ifdef FEATURE_TOGGLE
4691 if (global_toggle_state)
4692 #endif /* def FEATURE_TOGGLE */
4694 csp->flags |= CSP_FLAG_TOGGLED_ON;
4697 if (csp->client_iob->eod > csp->client_iob->cur)
4699 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4700 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4702 assert(bytes_to_shift > 0);
4703 assert(data_length > 0);
4705 log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4706 data_length, bytes_to_shift);
4707 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4708 csp->client_iob->cur = csp->client_iob->buf;
4709 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4710 csp->client_iob->eod = csp->client_iob->buf + data_length;
4711 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4713 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4718 * We mainly care about resetting client_iob->cur so we don't
4719 * waste buffer space at the beginning and don't mess up the
4720 * request restoration done by cgi_show_request().
4722 * Freeing the buffer itself isn't technically necessary,
4723 * but makes debugging more convenient.
4725 clear_iob(csp->client_iob);
4728 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4731 /*********************************************************************
4735 * Description : This is little more than chat. We only "serve" to
4736 * to close (or remember) any socket that chat may have
4740 * 1 : csp = Current client state (buffers, headers, etc...)
4744 *********************************************************************/
4745 static void serve(struct client_state *csp)
4747 int config_file_change_detected = 0; /* Only used for debugging */
4748 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4749 #ifdef FEATURE_CONNECTION_SHARING
4750 static int monitor_thread_running = 0;
4751 #endif /* def FEATURE_CONNECTION_SHARING */
4752 int continue_chatting = 0;
4754 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4755 csp->ip_addr_str, csp->cfd);
4759 unsigned int latency;
4761 #ifdef FEATURE_HTTPS_INSPECTION
4762 if (continue_chatting && client_use_ssl(csp))
4764 continue_https_chat(csp);
4773 * If the request has been crunched,
4774 * the calculated latency is zero.
4776 latency = (unsigned)(csp->server_connection.response_received -
4777 csp->server_connection.request_sent) / 2;
4779 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4780 && (csp->flags & CSP_FLAG_CRUNCHED)
4781 && (csp->expected_client_content_length != 0))
4783 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4784 log_error(LOG_LEVEL_CONNECT,
4785 "Tainting client socket %d due to unread data.", csp->cfd);
4788 continue_chatting = (csp->config->feature_flags
4789 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4790 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4791 && (csp->cfd != JB_INVALID_SOCKET)
4792 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4793 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4794 || (csp->flags & CSP_FLAG_CHUNKED));
4796 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4797 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4799 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4801 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4803 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4804 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4805 || !socket_is_still_alive(csp->server_connection.sfd)
4806 || !(latency < csp->server_connection.keep_alive_timeout))
4808 log_error(LOG_LEVEL_CONNECT,
4809 "Closing server socket %d connected to %s. "
4810 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4811 csp->server_connection.sfd, csp->server_connection.host,
4812 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4813 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4814 socket_is_still_alive(csp->server_connection.sfd),
4815 csp->server_connection.keep_alive_timeout);
4816 #ifdef FEATURE_CONNECTION_SHARING
4817 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4819 forget_connection(csp->server_connection.sfd);
4821 #endif /* def FEATURE_CONNECTION_SHARING */
4822 #ifdef FEATURE_HTTPS_INSPECTION
4823 close_server_ssl_connection(csp);
4825 close_socket(csp->server_connection.sfd);
4826 mark_connection_closed(&csp->server_connection);
4830 if (continue_chatting && any_loaded_file_changed(csp))
4832 continue_chatting = 0;
4833 config_file_change_detected = 1;
4835 #ifdef FEATURE_HTTPS_INSPECTION
4836 if (continue_chatting && client_use_ssl(csp) &&
4837 csp->ssl_with_client_is_opened == 0)
4839 continue_chatting = 0;
4840 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4841 "The TLS session has been terminated.", csp->cfd);
4845 if (continue_chatting)
4847 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4848 && socket_is_still_alive(csp->cfd))
4850 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4851 "pipelined on socket %d and the socket is still alive.",
4852 csp->requests_received_total+1, csp->cfd);
4853 prepare_csp_for_next_request(csp);
4857 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4859 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4861 log_error(LOG_LEVEL_CONNECT,
4862 "Waiting for the next client request on socket %d. "
4863 "Keeping the server socket %d to %s open.",
4864 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4868 log_error(LOG_LEVEL_CONNECT,
4869 "Waiting for the next client request on socket %d. "
4870 "No server socket to keep open.", csp->cfd);
4874 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4875 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4876 && socket_is_still_alive(csp->cfd))
4878 log_error(LOG_LEVEL_CONNECT,
4879 "Data arrived in time on client socket %d. Requests so far: %u",
4880 csp->cfd, csp->requests_received_total);
4881 prepare_csp_for_next_request(csp);
4885 #ifdef FEATURE_CONNECTION_SHARING
4886 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4887 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4888 && (socket_is_still_alive(csp->server_connection.sfd))
4889 #ifdef FEATURE_HTTPS_INSPECTION
4890 && !server_use_ssl(csp)
4894 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4896 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4901 remember_connection(&csp->server_connection);
4902 csp->server_connection.sfd = JB_INVALID_SOCKET;
4903 drain_and_close_socket(csp->cfd);
4904 csp->cfd = JB_INVALID_SOCKET;
4905 privoxy_mutex_lock(&connection_reuse_mutex);
4906 if (!monitor_thread_running)
4908 monitor_thread_running = 1;
4909 privoxy_mutex_unlock(&connection_reuse_mutex);
4910 wait_for_alive_connections();
4911 privoxy_mutex_lock(&connection_reuse_mutex);
4912 monitor_thread_running = 0;
4914 privoxy_mutex_unlock(&connection_reuse_mutex);
4916 #endif /* def FEATURE_CONNECTION_SHARING */
4920 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4922 log_error(LOG_LEVEL_CONNECT,
4923 "Closing server socket %d connected to %s. Keep-alive: %u. "
4924 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4925 "Configuration file change detected: %u",
4926 csp->server_connection.sfd, csp->server_connection.host,
4927 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4928 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4929 socket_is_still_alive(csp->server_connection.sfd),
4930 csp->server_connection.keep_alive_timeout,
4931 config_file_change_detected);
4933 } while (continue_chatting);
4937 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4939 if (csp->cfd != JB_INVALID_SOCKET)
4941 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4942 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4943 "Configuration file change detected: %u. Requests received: %u.",
4944 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4945 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4946 config_file_change_detected, csp->requests_received_total);
4947 #ifdef FEATURE_HTTPS_INSPECTION
4948 close_client_ssl_connection(csp);
4950 drain_and_close_socket(csp->cfd);
4953 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4955 #ifdef FEATURE_CONNECTION_SHARING
4956 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4958 forget_connection(csp->server_connection.sfd);
4960 #endif /* def FEATURE_CONNECTION_SHARING */
4962 #ifdef FEATURE_HTTPS_INSPECTION
4963 close_server_ssl_connection(csp);
4964 #endif /* def FEATURE_HTTPS_INSPECTION */
4966 close_socket(csp->server_connection.sfd);
4969 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4970 mark_connection_closed(&csp->server_connection);
4973 free_csp_resources(csp);
4975 csp->flags &= ~CSP_FLAG_ACTIVE;
4981 /*********************************************************************
4983 * Function : server_thread
4985 * Description : We only exist to call `serve' in a threaded environment.
4988 * 1 : data = Current client state (buffers, headers, etc...)
4990 * Returns : Always 0.
4992 *********************************************************************/
4993 static int32 server_thread(void *data)
4995 serve((struct client_state *) data);
5002 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5003 /*********************************************************************
5007 * Description : Print usage info & exit.
5009 * Parameters : Pointer to argv[0] for identifying ourselves
5013 *********************************************************************/
5014 static void usage(const char *name)
5016 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
5017 "Usage: %s [--config-test] "
5020 #endif /* defined(unix) */
5023 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
5024 #endif /* defined(unix) */
5025 "[--version] [configfile]\n",
5029 show_fuzz_usage(name);
5032 printf("Aborting\n");
5037 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5040 #ifdef MUTEX_LOCKS_AVAILABLE
5041 /*********************************************************************
5043 * Function : privoxy_mutex_lock
5045 * Description : Locks a mutex.
5048 * 1 : mutex = The mutex to lock.
5050 * Returns : Void. May exit in case of errors.
5052 *********************************************************************/
5053 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5055 #ifdef FEATURE_PTHREAD
5056 int err = pthread_mutex_lock(mutex);
5059 if (mutex != &log_mutex)
5061 log_error(LOG_LEVEL_FATAL,
5062 "Mutex locking failed: %s.\n", strerror(err));
5067 EnterCriticalSection(mutex);
5068 #endif /* def FEATURE_PTHREAD */
5072 /*********************************************************************
5074 * Function : privoxy_mutex_unlock
5076 * Description : Unlocks a mutex.
5079 * 1 : mutex = The mutex to unlock.
5081 * Returns : Void. May exit in case of errors.
5083 *********************************************************************/
5084 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5086 #ifdef FEATURE_PTHREAD
5087 int err = pthread_mutex_unlock(mutex);
5090 if (mutex != &log_mutex)
5092 log_error(LOG_LEVEL_FATAL,
5093 "Mutex unlocking failed: %s.\n", strerror(err));
5098 LeaveCriticalSection(mutex);
5099 #endif /* def FEATURE_PTHREAD */
5103 /*********************************************************************
5105 * Function : privoxy_mutex_init
5107 * Description : Prepares a mutex.
5110 * 1 : mutex = The mutex to initialize.
5112 * Returns : Void. May exit in case of errors.
5114 *********************************************************************/
5115 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5117 #ifdef FEATURE_PTHREAD
5118 int err = pthread_mutex_init(mutex, 0);
5121 printf("Fatal error. Mutex initialization failed: %s.\n",
5126 InitializeCriticalSection(mutex);
5127 #endif /* def FEATURE_PTHREAD */
5129 #endif /* def MUTEX_LOCKS_AVAILABLE */
5131 /*********************************************************************
5133 * Function : initialize_mutexes
5135 * Description : Prepares mutexes if mutex support is available.
5139 * Returns : Void, exits in case of errors.
5141 *********************************************************************/
5142 static void initialize_mutexes(void)
5144 #ifdef MUTEX_LOCKS_AVAILABLE
5146 * Prepare global mutex semaphores
5149 #ifdef FEATURE_HTTPS_INSPECTION
5150 privoxy_mutex_init(&certificate_mutex);
5151 privoxy_mutex_init(&ssl_init_mutex);
5154 privoxy_mutex_init(&log_mutex);
5155 privoxy_mutex_init(&log_init_mutex);
5156 privoxy_mutex_init(&connection_reuse_mutex);
5157 #ifdef FEATURE_EXTERNAL_FILTERS
5158 privoxy_mutex_init(&external_filter_mutex);
5160 #ifdef FEATURE_CLIENT_TAGS
5161 privoxy_mutex_init(&client_tags_mutex);
5163 #ifdef FEATURE_EXTENDED_STATISTICS
5164 privoxy_mutex_init(&filter_statistics_mutex);
5165 privoxy_mutex_init(&block_statistics_mutex);
5169 * XXX: The assumptions below are a bit naive
5170 * and can cause locks that aren't necessary.
5172 * For example older FreeBSD versions (< 6.x?)
5173 * have no gethostbyname_r, but gethostbyname is
5176 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5177 privoxy_mutex_init(&resolver_mutex);
5178 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5180 * XXX: should we use a single mutex for
5181 * localtime() and gmtime() as well?
5183 #ifndef HAVE_GMTIME_R
5184 privoxy_mutex_init(&gmtime_mutex);
5185 #endif /* ndef HAVE_GMTIME_R */
5187 #ifndef HAVE_LOCALTIME_R
5188 privoxy_mutex_init(&localtime_mutex);
5189 #endif /* ndef HAVE_GMTIME_R */
5191 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5192 privoxy_mutex_init(&rand_mutex);
5193 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5195 #endif /* def MUTEX_LOCKS_AVAILABLE */
5198 /*********************************************************************
5202 * Description : Load the config file and start the listen loop.
5203 * This function is a lot more *sane* with the `load_config'
5204 * and `listen_loop' functions; although it stills does
5205 * a *little* too much for my taste.
5208 * 1 : argc = Number of parameters (including $0).
5209 * 2 : argv = Array of (char *)'s to the parameters.
5211 * Returns : 1 if : can't open config file, unrecognized directive,
5212 * stats requested in multi-thread mode, can't open the
5213 * log file, can't open the jar file, listen port is invalid,
5214 * any load fails, and can't bind port.
5216 * Else main never returns, the process must be signaled
5217 * to terminate execution. Or, on Windows, use the
5218 * "File", "Exit" menu option.
5220 *********************************************************************/
5222 int real_main(int argc, char **argv)
5224 int main(int argc, char **argv)
5228 int do_config_test = 0;
5229 #ifndef HAVE_ARC4RANDOM
5230 unsigned int random_seed;
5233 struct passwd *pw = NULL;
5234 struct group *grp = NULL;
5236 char *pre_chroot_nslookup_to_load_resolver = NULL;
5239 char *fuzz_input_type = NULL;
5240 char *fuzz_input_file = NULL;
5247 #if !defined(_WIN32)
5254 /* Prepare mutexes if supported and necessary. */
5255 initialize_mutexes();
5257 /* Enable logging until further notice. */
5261 * Parse the command line arguments
5263 * XXX: simply printing usage information in case of
5264 * invalid arguments isn't particularly user friendly.
5266 while (++argc_pos < argc)
5269 /* Check to see if the service must be installed or uninstalled */
5270 if (strncmp(argv[argc_pos], "--install", 9) == 0)
5272 const char *pName = argv[argc_pos] + 9;
5275 exit((install_service(pName)) ? 0 : 1);
5277 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5279 const char *pName = argv[argc_pos] + 11;
5282 exit((uninstall_service(pName)) ? 0 : 1);
5284 else if (strcmp(argv[argc_pos], "--service") == 0)
5286 bRunAsService = TRUE;
5287 w32_set_service_cwd();
5288 atexit(w32_service_exit_notify);
5291 #endif /* defined(_WIN32) */
5294 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5296 if (strcmp(argv[argc_pos], "--help") == 0)
5301 else if (strcmp(argv[argc_pos], "--version") == 0)
5303 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5309 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5311 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5315 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5317 if (++argc_pos == argc) usage(argv[0]);
5318 pidfile = strdup_or_die(argv[argc_pos]);
5321 else if (strcmp(argv[argc_pos], "--user") == 0)
5326 if (++argc_pos == argc) usage(argv[argc_pos]);
5328 user_arg = strdup_or_die(argv[argc_pos]);
5329 group_name = strchr(user_arg, '.');
5330 if (NULL != group_name)
5332 /* Nul-terminate the user name */
5335 /* Skip the former delimiter to actually reach the group name */
5338 grp = getgrnam(group_name);
5341 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5344 pw = getpwnam(user_arg);
5347 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5353 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5355 if (++argc_pos == argc) usage(argv[0]);
5356 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5359 else if (strcmp(argv[argc_pos], "--chroot") == 0)
5363 #endif /* defined(unix) */
5365 else if (strcmp(argv[argc_pos], "--config-test") == 0)
5370 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5373 if (argc < argc_pos + 2) usage(argv[0]);
5374 fuzz_input_type = argv[argc_pos];
5376 fuzz_input_file = argv[argc_pos];
5378 else if (strcmp(argv[argc_pos], "--stfu") == 0)
5380 set_debug_level(LOG_LEVEL_STFU);
5383 else if (argc_pos + 1 != argc)
5386 * This is neither the last command line
5387 * option, nor was it recognized before,
5388 * therefore it must be invalid.
5394 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5396 configfile = argv[argc_pos];
5399 } /* -END- while (more arguments) */
5401 show_version(Argv[0]);
5404 if (*configfile != '/')
5406 char cwd[BUFFER_SIZE];
5408 size_t abs_file_size;
5410 /* make config-filename absolute here */
5411 if (NULL == getcwd(cwd, sizeof(cwd)))
5413 perror("failed to get current working directory");
5417 basedir = strdup_or_die(cwd);
5419 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5420 abs_file = malloc_or_die(abs_file_size);
5421 strlcpy(abs_file, basedir, abs_file_size);
5422 strlcat(abs_file, "/", abs_file_size);
5423 strlcat(abs_file, configfile, abs_file_size);
5424 configfile = abs_file;
5426 #endif /* defined unix */
5430 clients->next = NULL;
5432 /* XXX: factor out initialising after the next stable release. */
5437 #ifndef HAVE_ARC4RANDOM
5438 random_seed = (unsigned int)time(NULL);
5440 srandom(random_seed);
5443 #endif /* ifdef HAVE_RANDOM */
5444 #endif /* ifndef HAVE_ARC4RANDOM */
5447 * Unix signal handling
5449 * Catch the abort, interrupt and terminate signals for a graceful exit
5450 * Catch the hangup signal so the errlog can be reopened.
5452 * Ignore the broken pipe signal as connection failures
5453 * are handled when and where they occur without relying
5456 #if !defined(_WIN32)
5459 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5461 for (idx = 0; idx < SZ(catched_signals); idx++)
5463 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5464 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5466 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5467 #endif /* ifdef sun */
5469 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5473 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5475 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5479 #else /* ifdef _WIN32 */
5480 # ifdef _WIN_CONSOLE
5482 * We *are* in a windows console app.
5483 * Print a verbose messages about FAQ's and such
5485 printf("%s", win32_blurb);
5486 # endif /* def _WIN_CONSOLE */
5487 #endif /* def _WIN32 */
5490 if (fuzz_input_type != NULL)
5492 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5494 log_error(LOG_LEVEL_FATAL,
5495 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5496 "Various data structures are static which is unsafe when using threads.");
5501 exit(NULL == load_config());
5504 /* Initialize the CGI subsystem */
5505 cgi_init_error_messages();
5508 * If running on unix and without the --no-daemon
5509 * option, become a daemon. I.e. fork, detach
5510 * from tty and get process group leadership
5519 if (pid < 0) /* error */
5524 else if (pid != 0) /* parent */
5529 * must check for errors
5530 * child died due to missing files aso
5533 wpid = waitpid(pid, &status, WNOHANG);
5545 * stderr (fd 2) will be closed later on,
5546 * when the config file has been parsed.
5552 * Reserve fd 0 and 1 to prevent abort() and friends
5553 * from sending stuff to the clients or servers.
5555 fd = open("/dev/null", O_RDONLY);
5558 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5562 if (dup2(fd, 0) == -1)
5564 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5568 fd = open("/dev/null", O_WRONLY);
5571 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5575 if (dup2(fd, 1) == -1)
5577 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5582 #ifdef FEATURE_EXTERNAL_FILTERS
5583 for (fd = 0; fd < 3; fd++)
5585 mark_socket_for_close_on_execute(fd);
5589 if (chdir("/") != 0)
5591 log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5594 } /* -END- if (daemon_mode) */
5597 * As soon as we have written the PID file, we can switch
5598 * to the user and group ID indicated by the --user option
5600 if (pidfile != NULL)
5602 write_pid_file(pidfile);
5606 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5608 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5612 if (setgroups(1, &grp->gr_gid))
5614 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5617 else if (initgroups(pw->pw_name, pw->pw_gid))
5619 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5625 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5627 /* Read the time zone file from /etc before doing chroot. */
5629 if (NULL != pre_chroot_nslookup_to_load_resolver
5630 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5632 /* Initialize resolver library. */
5633 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5635 if (chroot(pw->pw_dir) < 0)
5637 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5641 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5644 if (setuid(pw->pw_uid))
5646 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5650 char putenv_dummy[64];
5652 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5653 if (putenv(putenv_dummy) != 0)
5655 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5658 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5659 if (putenv(putenv_dummy) != 0)
5661 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5667 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5670 #endif /* defined unix */
5673 /* This will be FALSE unless the command line specified --service
5677 /* Yup, so now we must attempt to establish a connection
5678 * with the service dispatcher. This will only work if this
5679 * process was launched by the service control manager to
5680 * actually run as a service. If this isn't the case, i've
5681 * known it take around 30 seconds or so for the call to return.
5684 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5685 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5687 /* Service has run, and at this point is now being stopped, so just return */
5692 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5694 /* An error occurred. Usually it's because --service was wrongly specified
5695 * and we were unable to connect to the Service Control Dispatcher because
5696 * it wasn't expecting us and is therefore not listening.
5698 * For now, just continue below to call the listen_loop function.
5701 #endif /* def _WIN32 */
5711 /*********************************************************************
5713 * Function : bind_port_helper
5715 * Description : Bind the listen port. Handles logging, and aborts
5719 * 1 : haddr = Host address to bind to. Use NULL to bind to
5721 * 2 : hport = Specifies port to bind to.
5722 * 3 : backlog = Listen backlog.
5724 * Returns : Port that was opened.
5726 *********************************************************************/
5727 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5732 result = bind_port(haddr, hport, backlog, &bfd);
5736 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5740 log_error(LOG_LEVEL_FATAL,
5741 "can't bind to %s:%d: There may be another Privoxy "
5742 "or some other proxy running on port %d",
5743 bind_address, hport, hport);
5746 log_error(LOG_LEVEL_FATAL,
5747 "can't bind to %s:%d: The hostname is not resolvable",
5748 bind_address, hport);
5751 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5752 bind_address, hport);
5755 /* shouldn't get here */
5756 return JB_INVALID_SOCKET;
5761 if (bfd >= FD_SETSIZE)
5763 log_error(LOG_LEVEL_FATAL,
5764 "Bind socket number too high to use select(): %d >= %d",
5772 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5777 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5785 /*********************************************************************
5787 * Function : bind_ports_helper
5789 * Description : Bind the listen ports. Handles logging, and aborts
5793 * 1 : config = Privoxy configuration. Specifies ports
5795 * 2 : sockets = Preallocated array of opened sockets
5796 * corresponding to specification in config.
5797 * All non-opened sockets will be set to
5798 * JB_INVALID_SOCKET.
5800 * Returns : Nothing. Inspect sockets argument.
5802 *********************************************************************/
5803 static void bind_ports_helper(struct configuration_spec * config,
5804 jb_socket sockets[])
5808 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5810 if (config->hport[i])
5812 sockets[i] = bind_port_helper(config->haddr[i],
5813 config->hport[i], config->listen_backlog);
5814 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5815 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5817 struct accept_filter_arg af_options;
5818 bzero(&af_options, sizeof(af_options));
5819 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5820 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5821 sizeof(af_options)))
5823 log_error(LOG_LEVEL_ERROR,
5824 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5831 sockets[i] = JB_INVALID_SOCKET;
5834 config->need_bind = 0;
5838 /*********************************************************************
5840 * Function : close_ports_helper
5842 * Description : Close listenings ports.
5845 * 1 : sockets = Array of opened and non-opened sockets to
5846 * close. All sockets will be set to
5847 * JB_INVALID_SOCKET.
5849 * Returns : Nothing.
5851 *********************************************************************/
5852 static void close_ports_helper(jb_socket sockets[])
5856 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5858 if (JB_INVALID_SOCKET != sockets[i])
5860 close_socket(sockets[i]);
5862 sockets[i] = JB_INVALID_SOCKET;
5868 /* Without this simple workaround we get this compiler warning from _beginthread
5869 * warning C4028: formal parameter 1 different from declaration
5871 void w32_service_listen_loop(void *p)
5875 #endif /* def _WIN32 */
5878 /*********************************************************************
5880 * Function : listen_loop
5882 * Description : bind the listen port and enter a "FOREVER" listening loop.
5888 *********************************************************************/
5889 static void listen_loop(void)
5891 struct client_states *csp_list = NULL;
5892 struct client_state *csp = NULL;
5893 jb_socket bfds[MAX_LISTENING_SOCKETS];
5894 struct configuration_spec *config;
5895 unsigned int active_threads = 0;
5896 #if defined(FEATURE_PTHREAD)
5897 pthread_attr_t attrs;
5899 pthread_attr_init(&attrs);
5900 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5903 config = load_config();
5905 #ifdef FEATURE_CONNECTION_SHARING
5907 * XXX: Should be relocated once it no
5908 * longer needs to emit log messages.
5910 initialize_reusable_connections();
5911 #endif /* def FEATURE_CONNECTION_SHARING */
5913 bind_ports_helper(config, bfds);
5915 #ifdef FEATURE_GRACEFUL_TERMINATION
5916 while (!g_terminate)
5921 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
5922 while (waitpid(-1, NULL, WNOHANG) > 0)
5924 /* zombie children */
5926 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5929 * Free data that was used by died threads
5931 active_threads = sweep();
5935 * Re-open the errlog after HUP signal
5937 if (received_hup_signal)
5939 if (NULL != config->logfile)
5941 init_error_log(Argv[0], config->logfile);
5943 received_hup_signal = 0;
5947 csp_list = zalloc_or_die(sizeof(*csp_list));
5948 csp = &csp_list->csp;
5950 log_error(LOG_LEVEL_CONNECT,
5951 "Waiting for the next client connection. Currently active threads: %u",
5955 * This config may be outdated, but for accept_connection()
5956 * it's fresh enough.
5958 csp->config = config;
5960 if (!accept_connection(csp, bfds))
5962 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5967 csp->flags |= CSP_FLAG_ACTIVE;
5968 csp->server_connection.sfd = JB_INVALID_SOCKET;
5970 csp->config = config = load_config();
5972 if (config->need_bind)
5975 * Since we were listening to the "old port", we will not see
5976 * a "listen" param change until the next request. So, at
5977 * least 1 more request must be made for us to find the new
5978 * setting. I am simply closing the old socket and binding the
5981 * Which-ever is correct, we will serve 1 more page via the
5982 * old settings. This should probably be a "show-status"
5983 * request. This should not be a so common of an operation
5984 * that this will hurt people's feelings.
5987 close_ports_helper(bfds);
5989 bind_ports_helper(config, bfds);
5992 #ifdef FEATURE_TOGGLE
5993 if (global_toggle_state)
5994 #endif /* def FEATURE_TOGGLE */
5996 csp->flags |= CSP_FLAG_TOGGLED_ON;
5999 if (run_loader(csp))
6001 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
6002 /* Never get here - LOG_LEVEL_FATAL causes program exit */
6006 if (block_acl(NULL,csp))
6008 log_error(LOG_LEVEL_CONNECT,
6009 "Connection from %s on %s (socket %d) dropped due to ACL",
6010 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
6011 close_socket(csp->cfd);
6012 freez(csp->ip_addr_str);
6013 freez(csp->listen_addr_str);
6017 #endif /* def FEATURE_ACL */
6019 if ((0 != config->max_client_connections)
6020 && (active_threads >= config->max_client_connections))
6022 log_error(LOG_LEVEL_CONNECT,
6023 "Rejecting connection from %s. Maximum number of connections reached.",
6025 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6026 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6027 close_socket(csp->cfd);
6028 freez(csp->ip_addr_str);
6029 freez(csp->listen_addr_str);
6034 /* add it to the list of clients */
6035 csp_list->next = clients->next;
6036 clients->next = csp_list;
6038 if (config->multi_threaded)
6042 /* this is a switch () statement in the C preprocessor - ugh */
6043 #undef SELECTED_ONE_OPTION
6045 /* Use Pthreads in preference to native code */
6046 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6047 #define SELECTED_ONE_OPTION
6049 pthread_t the_thread;
6052 ret = pthread_create(&the_thread, &attrs,
6053 (void * (*)(void *))serve, csp);
6054 child_id = ret ? -1 : 0;
6058 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
6059 #define SELECTED_ONE_OPTION
6060 child_id = _beginthread(
6061 (void (*)(void *))serve,
6066 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6067 #define SELECTED_ONE_OPTION
6069 thread_id tid = spawn_thread
6070 (server_thread, "server", B_NORMAL_PRIORITY, csp);
6072 if ((tid >= 0) && (resume_thread(tid) == B_OK))
6074 child_id = (int) tid;
6083 #if !defined(SELECTED_ONE_OPTION)
6086 /* This block is only needed when using fork().
6087 * When using threads, the server thread was
6088 * created and run by the call to _beginthread().
6090 if (child_id == 0) /* child */
6093 #ifdef FEATURE_TOGGLE
6094 int inherited_toggle_state = global_toggle_state;
6095 #endif /* def FEATURE_TOGGLE */
6100 * If we've been toggled or we've blocked the request, tell Mom
6103 #ifdef FEATURE_TOGGLE
6104 if (inherited_toggle_state != global_toggle_state)
6106 rc |= RC_FLAG_TOGGLED;
6108 #endif /* def FEATURE_TOGGLE */
6110 #ifdef FEATURE_STATISTICS
6111 if (csp->flags & CSP_FLAG_REJECTED)
6113 rc |= RC_FLAG_BLOCKED;
6115 #endif /* ndef FEATURE_STATISTICS */
6119 else if (child_id > 0) /* parent */
6121 /* in a fork()'d environment, the parent's
6122 * copy of the client socket and the CSP
6126 #if !defined(_WIN32) && !defined(__CYGWIN__)
6128 wait(&child_status);
6131 * Evaluate child's return code: If the child has
6132 * - been toggled, toggle ourselves
6133 * - blocked its request, bump up the stats counter
6136 #ifdef FEATURE_TOGGLE
6137 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6139 global_toggle_state = !global_toggle_state;
6141 #endif /* def FEATURE_TOGGLE */
6143 #ifdef FEATURE_STATISTICS
6145 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6149 #endif /* def FEATURE_STATISTICS */
6151 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6152 close_socket(csp->cfd);
6153 csp->flags &= ~CSP_FLAG_ACTIVE;
6157 #undef SELECTED_ONE_OPTION
6158 /* end of cpp switch () */
6163 * Spawning the child failed, assume it's because
6164 * there are too many children running already.
6165 * XXX: If you assume ...
6167 log_error(LOG_LEVEL_ERROR,
6168 "Unable to take any additional connections: %E. Active threads: %u",
6170 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6171 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6172 close_socket(csp->cfd);
6173 csp->flags &= ~CSP_FLAG_ACTIVE;
6182 #if defined(FEATURE_PTHREAD)
6183 pthread_attr_destroy(&attrs);
6186 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6188 #ifdef FEATURE_GRACEFUL_TERMINATION
6190 log_error(LOG_LEVEL_INFO, "Graceful termination requested.");
6192 unload_current_config_file();
6193 unload_current_actions_file();
6194 unload_current_re_filterfile();
6195 #ifdef FEATURE_TRUST
6196 unload_current_trust_file();
6199 if (config->multi_threaded)
6206 } while ((clients->next != NULL) && (--i > 0));
6210 log_error(LOG_LEVEL_ERROR, "Graceful termination failed "
6211 "- still some live clients after 1 minute wait.");
6221 #ifdef FEATURE_HTTPS_INSPECTION
6223 * Only release TLS backed resources if there
6224 * are no active connections left.
6226 if (clients->next == NULL)
6232 log_error(LOG_LEVEL_INFO, "Exiting gracefully.");
6234 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6235 /* Cleanup - remove taskbar icon etc. */
6240 #endif /* FEATURE_GRACEFUL_TERMINATION */