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.\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.\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.\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.\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.\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.\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.\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.\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.\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.\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 static 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 /* Make sure we're still within the buffer and have two bytes left */
1507 if (p + 2 > iob->eod)
1509 return CHUNK_STATUS_MISSING_DATA;
1512 /* There should be another "\r\n" to skip */
1513 if (memcmp(p, "\r\n", 2))
1515 return CHUNK_STATUS_PARSE_ERROR;
1518 } while (chunksize > 0U);
1520 *length = (size_t)(p - iob->cur);
1521 assert(*length <= (size_t)(iob->eod - iob->cur));
1522 assert(p <= iob->eod);
1524 return CHUNK_STATUS_BODY_COMPLETE;
1529 /*********************************************************************
1531 * Function : receive_chunked_client_request_body
1533 * Description : Read the chunk-encoded client request body.
1534 * Failures are dealt with.
1537 * 1 : csp = Current client state (buffers, headers, etc...)
1539 * Returns : JB_ERR_OK or JB_ERR_PARSE
1541 *********************************************************************/
1542 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1545 enum chunk_status status;
1547 while (CHUNK_STATUS_MISSING_DATA ==
1548 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1550 char buf[BUFFER_SIZE];
1553 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1555 log_error(LOG_LEVEL_ERROR,
1556 "Timeout while waiting for the client body.");
1559 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1562 log_error(LOG_LEVEL_ERROR,
1563 "Reading the client body failed: %E");
1566 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1571 if (status != CHUNK_STATUS_BODY_COMPLETE)
1573 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1574 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1575 log_error(LOG_LEVEL_CLF,
1576 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1577 return JB_ERR_PARSE;
1579 log_error(LOG_LEVEL_CONNECT,
1580 "Chunked client body completely read. Length: %lu", body_length);
1581 csp->expected_client_content_length = body_length;
1589 /*********************************************************************
1591 * Function : fuzz_chunked_transfer_encoding
1593 * Description : Treat the fuzzed input as chunked transfer encoding
1594 * to check and dechunk.
1597 * 1 : csp = Used to store the data.
1598 * 2 : fuzz_input_file = File to read the input from.
1600 * Returns : Result of dechunking
1602 *********************************************************************/
1603 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1606 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1607 enum chunk_status status;
1609 status = chunked_body_is_complete(csp->iob, &length);
1610 if (CHUNK_STATUS_BODY_COMPLETE != status)
1612 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1615 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1620 /*********************************************************************
1622 * Function : fuzz_client_request
1624 * Description : Try to get a client request from the fuzzed input.
1627 * 1 : csp = Current client state (buffers, headers, etc...)
1628 * 2 : fuzz_input_file = File to read the input from.
1630 * Returns : Result of fuzzing.
1632 *********************************************************************/
1633 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1638 csp->ip_addr_str = "fuzzer";
1640 if (strcmp(fuzz_input_file, "-") != 0)
1642 log_error(LOG_LEVEL_FATAL,
1643 "Fuzzed client requests can currently only be read from stdin (-).");
1645 err = receive_client_request(csp);
1646 if (err != JB_ERR_OK)
1650 err = parse_client_request(csp);
1651 if (err != JB_ERR_OK)
1659 #endif /* def FUZZ */
1662 #ifdef FEATURE_FORCE_LOAD
1663 /*********************************************************************
1665 * Function : force_required
1667 * Description : Checks a request line to see if it contains
1668 * the FORCE_PREFIX. If it does, it is removed
1669 * unless enforcing requests has beend disabled.
1672 * 1 : request_line = HTTP request line
1674 * Returns : TRUE if force is required, FALSE otherwise.
1676 *********************************************************************/
1677 static int force_required(const struct client_state *csp, char *request_line)
1681 p = strstr(request_line, "http://");
1685 p += strlen("http://");
1689 /* Intercepted request usually don't specify the protocol. */
1693 /* Go to the beginning of the path */
1698 * If the path is missing the request line is invalid and we
1699 * are done here. The client-visible rejection happens later on.
1704 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1706 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1708 /* XXX: Should clean more carefully */
1709 strclean(request_line, FORCE_PREFIX);
1710 log_error(LOG_LEVEL_FORCE,
1711 "Enforcing request: \"%s\".", request_line);
1715 log_error(LOG_LEVEL_FORCE,
1716 "Ignored force prefix in request: \"%s\".", request_line);
1722 #endif /* def FEATURE_FORCE_LOAD */
1725 /*********************************************************************
1727 * Function : receive_client_request
1729 * Description : Read the client's request (more precisely the
1730 * client headers) and answer it if necessary.
1733 * 1 : csp = Current client state (buffers, headers, etc...)
1735 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1737 *********************************************************************/
1738 static jb_err receive_client_request(struct client_state *csp)
1740 char buf[BUFFER_SIZE];
1743 struct http_request *http;
1747 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1748 struct list header_list;
1749 struct list *headers = &header_list;
1751 /* We don't care if the arriving data is a valid HTTP request or not. */
1752 csp->requests_received_total++;
1756 memset(buf, 0, sizeof(buf));
1758 req = get_request_line(csp);
1761 mark_server_socket_tainted(csp);
1762 return JB_ERR_PARSE;
1764 assert(*req != '\0');
1766 if (client_protocol_is_unsupported(csp, req))
1768 return JB_ERR_PARSE;
1771 #ifdef FEATURE_FORCE_LOAD
1772 if (force_required(csp, req))
1774 csp->flags |= CSP_FLAG_FORCED;
1776 #endif /* def FEATURE_FORCE_LOAD */
1778 err = parse_http_request(req, http);
1780 if (JB_ERR_OK != err)
1782 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1783 get_write_delay(csp));
1784 /* XXX: Use correct size */
1785 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1786 log_error(LOG_LEVEL_ERROR,
1787 "Couldn't parse request line received from %s: %s",
1788 csp->ip_addr_str, jb_err_to_string(err));
1790 free_http_request(http);
1791 return JB_ERR_PARSE;
1794 /* grab the rest of the client's headers */
1798 p = get_header(csp->client_iob);
1802 /* There are no additional headers to read. */
1809 * We didn't receive a complete header
1810 * line yet, get the rest of it.
1812 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1814 log_error(LOG_LEVEL_ERROR,
1815 "Stopped grabbing the client headers.");
1816 destroy_list(headers);
1817 return JB_ERR_PARSE;
1820 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1823 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1824 destroy_list(headers);
1825 return JB_ERR_PARSE;
1828 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1831 * If there is no memory left for buffering the
1832 * request, there is nothing we can do but hang up
1834 destroy_list(headers);
1835 return JB_ERR_MEMORY;
1840 if (!strncmpic(p, "Transfer-Encoding:", 18))
1843 * XXX: should be called through sed()
1844 * but currently can't.
1846 client_transfer_encoding(csp, &p);
1849 * We were able to read a complete
1850 * header and can finally enlist it.
1857 if (http->host == NULL)
1860 * If we still don't know the request destination,
1861 * the request is invalid or the client uses
1862 * Privoxy without its knowledge.
1864 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1867 * Our attempts to get the request destination
1868 * elsewhere failed or Privoxy is configured
1869 * to only accept proxy requests.
1871 * An error response has already been sent
1872 * and we're done here.
1874 return JB_ERR_PARSE;
1878 #ifdef FEATURE_CLIENT_TAGS
1879 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1880 set_client_address(csp, headers);
1881 get_tag_list_for_client(csp->client_tags, csp->client_address);
1885 * Determine the actions for this URL
1887 #ifdef FEATURE_TOGGLE
1888 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1890 /* Most compatible set of actions (i.e. none) */
1891 init_current_action(csp->action);
1894 #endif /* ndef FEATURE_TOGGLE */
1896 get_url_actions(csp, http);
1899 enlist(csp->headers, http->cmd);
1901 /* Append the previously read headers */
1902 err = list_append_list_unique(csp->headers, headers);
1903 destroy_list(headers);
1910 /*********************************************************************
1912 * Function : parse_client_request
1914 * Description : Parses the client's request and decides what to do
1917 * Note that since we're not using select() we could get
1918 * blocked here if a client connected, then didn't say
1922 * 1 : csp = Current client state (buffers, headers, etc...)
1924 * Returns : JB_ERR_OK or JB_ERR_PARSE
1926 *********************************************************************/
1927 static jb_err parse_client_request(struct client_state *csp)
1929 struct http_request *http = csp->http;
1932 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1933 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1934 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1935 && (csp->http->ssl == 0))
1937 /* Assume persistence until further notice */
1938 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1940 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1942 if (csp->http->ssl == 0)
1945 * This whole block belongs to chat() but currently
1946 * has to be executed before sed().
1948 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1950 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1952 return JB_ERR_PARSE;
1957 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1959 verify_request_length(csp);
1961 #ifndef FEATURE_HTTPS_INSPECTION
1964 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1968 err = sed(csp, FILTER_CLIENT_HEADERS);
1969 if (JB_ERR_OK != err)
1971 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1973 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1974 csp->ip_addr_str, csp->http->cmd);
1975 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1976 return JB_ERR_PARSE;
1978 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1980 /* Check request line for rewrites. */
1981 if ((NULL == csp->headers->first->str)
1982 || (strcmp(http->cmd, csp->headers->first->str) &&
1983 (JB_ERR_OK != change_request_destination(csp))))
1986 * A header filter broke the request line - bail out.
1988 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1989 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1990 /* XXX: Use correct size */
1991 log_error(LOG_LEVEL_CLF,
1992 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
1993 log_error(LOG_LEVEL_ERROR,
1994 "Invalid request line after applying header filters.");
1995 free_http_request(http);
1997 return JB_ERR_PARSE;
2000 if (client_has_unsupported_expectations(csp))
2002 return JB_ERR_PARSE;
2010 /*********************************************************************
2012 * Function : read_http_request_body
2014 * Description : Reads remaining request body from the client.
2017 * 1 : csp = Current client state (buffers, headers, etc...)
2019 * Returns : 0 on success, anything else is an error.
2021 *********************************************************************/
2022 static int read_http_request_body(struct client_state *csp)
2024 size_t to_read = csp->expected_client_content_length;
2027 assert(to_read != 0);
2029 /* check if all data has been already read */
2030 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2035 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2036 to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2037 to_read -= (unsigned)len)
2039 char buf[BUFFER_SIZE];
2040 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2042 log_error(LOG_LEVEL_CONNECT,
2043 "Waiting for up to %lu bytes of request body from the client.",
2045 len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2048 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2051 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2055 assert(to_read >= len);
2060 log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %llu more bytes",
2061 csp->expected_client_content_length);
2064 log_error(LOG_LEVEL_CONNECT, "The last %llu bytes of the request body have been read",
2065 csp->expected_client_content_length);
2070 /*********************************************************************
2072 * Function : update_client_headers
2074 * Description : Updates the HTTP headers from the client request.
2077 * 1 : csp = Current client state (buffers, headers, etc...)
2078 * 2 : new_content_length = new content length value to set
2080 * Returns : 0 on success, anything else is an error.
2082 *********************************************************************/
2083 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2085 static const char content_length[] = "Content-Length:";
2087 struct list_entry *p;
2089 #ifndef FEATURE_HTTPS_INSPECTION
2090 for (p = csp->headers->first;
2092 for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2094 !updated && (p != NULL); p = p->next)
2096 /* Header crunch()ed in previous run? -> ignore */
2102 /* Does the current parser handle this header? */
2103 if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2105 updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2117 /*********************************************************************
2119 * Function : can_filter_request_body
2121 * Description : Checks if the current request body can be stored in
2122 * the client_iob without hitting buffer limit.
2125 * 1 : csp = Current client state (buffers, headers, etc...)
2127 * Returns : TRUE if the current request size do not exceed buffer limit
2130 *********************************************************************/
2131 static int can_filter_request_body(const struct client_state *csp)
2133 if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2134 csp->expected_client_content_length))
2136 log_error(LOG_LEVEL_INFO,
2137 "Not filtering request body from %s: buffer limit %lu will be exceeded "
2138 "(content length %lluu)", csp->ip_addr_str, csp->config->buffer_limit,
2139 csp->expected_client_content_length);
2146 /*********************************************************************
2148 * Function : send_http_request
2150 * Description : Sends the HTTP headers from the client request
2151 * and all the body data that has already been received.
2154 * 1 : csp = Current client state (buffers, headers, etc...)
2156 * Returns : 0 on success, anything else is an error.
2158 *********************************************************************/
2159 static int send_http_request(struct client_state *csp)
2163 const char *to_send;
2165 int filter_client_body = csp->expected_client_content_length != 0 &&
2166 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2168 if (filter_client_body)
2170 if (read_http_request_body(csp))
2174 to_send_len = csp->expected_client_content_length;
2175 to_send = execute_client_body_filters(csp, &to_send_len);
2176 if (to_send == NULL)
2178 /* just flush client_iob */
2179 filter_client_body = FALSE;
2181 else if (to_send_len != csp->expected_client_content_length &&
2182 update_client_headers(csp, to_send_len))
2184 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2187 csp->expected_client_content_length = 0;
2190 hdr = list_to_text(csp->headers);
2193 /* FIXME Should handle error properly */
2194 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2196 list_remove_all(csp->headers);
2199 * Write the client's (modified) header to the server
2200 * (along with anything else that may be in the buffer)
2202 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2207 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2208 csp->http->hostport);
2212 if (filter_client_body)
2214 write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2218 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2219 csp->http->hostport);
2224 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2225 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2227 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2228 csp->http->hostport);
2235 #ifdef FEATURE_HTTPS_INSPECTION
2236 /*********************************************************************
2238 * Function : read_https_request_body
2240 * Description : Reads remaining request body from the client.
2243 * 1 : csp = Current client state (buffers, headers, etc...)
2245 * Returns : 0 on success, anything else is an error.
2247 *********************************************************************/
2248 static int read_https_request_body(struct client_state *csp)
2250 size_t to_read = csp->expected_client_content_length;
2253 assert(to_read != 0);
2255 /* check if all data has been already read */
2256 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2261 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2262 to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2263 data_is_available(csp->cfd, csp->config->socket_timeout));
2264 to_read -= (unsigned)len)
2266 unsigned char buf[BUFFER_SIZE];
2267 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2269 log_error(LOG_LEVEL_CONNECT,
2270 "Waiting for up to %lu bytes of request body from the client.",
2272 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2273 (unsigned)max_bytes_to_read);
2276 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2279 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2283 assert(to_read >= len);
2288 log_error(LOG_LEVEL_CONNECT,
2289 "Not enough request body has been read: expected %lu more bytes",
2294 log_error(LOG_LEVEL_CONNECT,
2295 "The last %llu bytes of the request body have been read",
2296 csp->expected_client_content_length);
2301 /*********************************************************************
2303 * Function : receive_and_send_encrypted_post_data
2305 * Description : Reads remaining request body from the client and sends
2309 * 1 : csp = Current client state (buffers, headers, etc...)
2311 * Returns : 0 on success, anything else is an error.
2313 *********************************************************************/
2314 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2316 int content_length_known = csp->expected_client_content_length != 0;
2318 while (is_ssl_pending(&(csp->ssl_client_attr))
2319 || (content_length_known && csp->expected_client_content_length != 0))
2321 unsigned char buf[BUFFER_SIZE];
2323 int max_bytes_to_read = sizeof(buf);
2325 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2327 max_bytes_to_read = (int)csp->expected_client_content_length;
2329 log_error(LOG_LEVEL_CONNECT,
2330 "Waiting for up to %d bytes of request body from the client.",
2332 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2333 (unsigned)max_bytes_to_read);
2340 /* XXX: Does this actually happen? */
2343 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2345 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2350 if (csp->expected_client_content_length != 0)
2352 if (csp->expected_client_content_length >= len)
2354 csp->expected_client_content_length -= (unsigned)len;
2356 if (csp->expected_client_content_length == 0)
2358 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2364 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2371 /*********************************************************************
2373 * Function : send_https_request
2375 * Description : Sends the HTTP headers from the client request
2376 * and all the body data that has already been received.
2379 * 1 : csp = Current client state (buffers, headers, etc...)
2381 * Returns : 0 on success, anything else is an error.
2383 *********************************************************************/
2384 static int send_https_request(struct client_state *csp)
2389 const char *to_send;
2391 int filter_client_body = csp->expected_client_content_length != 0 &&
2392 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2394 if (filter_client_body)
2396 if (read_https_request_body(csp))
2400 to_send_len = csp->expected_client_content_length;
2401 to_send = execute_client_body_filters(csp, &to_send_len);
2402 if (to_send == NULL)
2404 /* just flush client_iob */
2405 filter_client_body = FALSE;
2407 else if (to_send_len != csp->expected_client_content_length &&
2408 update_client_headers(csp, to_send_len))
2410 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2413 csp->expected_client_content_length = 0;
2416 hdr = list_to_text(csp->https_headers);
2419 /* FIXME Should handle error properly */
2420 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2422 list_remove_all(csp->https_headers);
2425 * Write the client's (modified) header to the server
2426 * (along with anything else that may be in the buffer)
2428 ret = ssl_send_data(&(csp->ssl_server_attr),
2429 (const unsigned char *)hdr, strlen(hdr));
2434 log_error(LOG_LEVEL_CONNECT,
2435 "Failed sending encrypted request headers to: %s: %E",
2436 csp->http->hostport);
2437 mark_server_socket_tainted(csp);
2441 if (filter_client_body)
2443 ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2447 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2448 csp->http->hostport);
2453 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2454 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2455 csp->client_iob)) < 0))
2457 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2458 csp->http->hostport);
2461 if (flushed != 0 || csp->expected_client_content_length != 0)
2463 if (csp->expected_client_content_length != 0)
2465 if (csp->expected_client_content_length < flushed)
2467 log_error(LOG_LEVEL_ERROR,
2468 "Flushed %ld bytes of request body while only expecting %llu",
2469 flushed, csp->expected_client_content_length);
2470 csp->expected_client_content_length = 0;
2474 log_error(LOG_LEVEL_CONNECT,
2475 "Flushed %ld bytes of request body while expecting %llu",
2476 flushed, csp->expected_client_content_length);
2477 csp->expected_client_content_length -= (unsigned)flushed;
2478 if (receive_and_send_encrypted_post_data(csp))
2486 log_error(LOG_LEVEL_CONNECT,
2487 "Flushed %ld bytes of request body", flushed);
2491 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2498 /*********************************************************************
2500 * Function : receive_encrypted_request
2502 * Description : Receives an encrypted request.
2505 * 1 : csp = Current client state (buffers, headers, etc...)
2507 * Returns : JB_ERR_OK on success,
2508 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2510 *********************************************************************/
2511 static jb_err receive_encrypted_request(struct client_state *csp)
2513 char buf[BUFFER_SIZE];
2519 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2520 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2521 !data_is_available(csp->cfd, csp->config->socket_timeout))
2523 log_error(LOG_LEVEL_CONNECT,
2524 "Socket %d timed out while waiting for client headers", csp->cfd);
2525 return JB_ERR_PARSE;
2527 len = ssl_recv_data(&(csp->ssl_client_attr),
2528 (unsigned char *)buf, sizeof(buf));
2531 log_error(LOG_LEVEL_CONNECT,
2532 "Socket %d closed while waiting for client headers", csp->cfd);
2533 return JB_ERR_PARSE;
2537 return JB_ERR_PARSE;
2539 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2541 return JB_ERR_MEMORY;
2543 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2544 } while (p == NULL);
2546 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2552 /*********************************************************************
2554 * Function : change_encrypted_request_destination
2556 * Description : Parse a (rewritten) request line from an encrypted
2557 * request and regenerate the http request data.
2560 * 1 : csp = Current client state (buffers, headers, etc...)
2562 * Returns : Forwards the parse_http_request() return code.
2563 * Terminates in case of memory problems.
2565 *********************************************************************/
2566 static jb_err change_encrypted_request_destination(struct client_state *csp)
2569 char *original_host = csp->http->host;
2570 int original_port = csp->http->port;
2572 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2573 csp->https_headers->first->str);
2574 csp->http->host = NULL;
2575 free_http_request(csp->http);
2576 err = parse_http_request(csp->https_headers->first->str, csp->http);
2577 if (JB_ERR_OK != err)
2579 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2580 jb_err_to_string(err));
2581 freez(original_host);
2585 if (csp->http->host == NULL)
2587 char port_string[10];
2589 * The rewritten request line did not specify a host
2590 * which means we can use the original host specified
2593 csp->http->host = original_host;
2594 csp->http->port = original_port;
2595 log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2598 * If the rewritten request line didn't contain a host
2599 * it also didn't contain a port so we can reuse the host
2602 freez(csp->http->hostport);
2603 csp->http->hostport = strdup_or_die(csp->http->host);
2604 snprintf(port_string, sizeof(port_string), ":%d", original_port);
2605 err = string_append(&csp->http->hostport, port_string);
2606 if (err != JB_ERR_OK)
2608 log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2609 jb_err_to_string(err));
2614 * While the request line didn't mention it,
2615 * we're https-inspecting and want to speak TLS
2618 csp->http->server_ssl = 1;
2623 /* The rewrite filter added a host so we can ditch the original */
2624 freez(original_host);
2625 csp->http->server_ssl = csp->http->ssl;
2628 csp->http->client_ssl = 1;
2630 freez(csp->https_headers->first->str);
2631 build_request_line(csp, NULL, &csp->https_headers->first->str);
2633 if (!server_use_ssl(csp))
2635 log_error(LOG_LEVEL_REDIRECTS,
2636 "Rewritten request line results in downgrade to http");
2638 * Replace the unencryptd headers received with the
2639 * CONNECT request with the ones we received securely.
2641 destroy_list(csp->headers);
2642 csp->headers->first = csp->https_headers->first;
2643 csp->headers->last = csp->https_headers->last;
2644 csp->https_headers->first = NULL;
2645 csp->https_headers->last = NULL;
2653 /*********************************************************************
2655 * Function : process_encrypted_request
2657 * Description : Receives and parses an encrypted request.
2660 * 1 : csp = Current client state (buffers, headers, etc...)
2662 * Returns : JB_ERR_OK on success,
2663 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2665 *********************************************************************/
2666 static jb_err process_encrypted_request(struct client_state *csp)
2671 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2672 struct list header_list;
2673 struct list *headers = &header_list;
2675 assert(csp->ssl_with_client_is_opened);
2677 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2678 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2680 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2683 err = receive_encrypted_request(csp);
2684 if (err != JB_ERR_OK)
2686 if (csp->client_iob->cur == NULL ||
2687 csp->client_iob->cur == csp->client_iob->eod)
2690 * We did not receive any data, most likely because the
2691 * client is done. Don't log this as a parse failure.
2693 return JB_ERR_PARSE;
2695 /* XXX: Also used for JB_ERR_MEMORY */
2696 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2697 jb_err_to_string(err));
2698 ssl_send_data_delayed(&(csp->ssl_client_attr),
2699 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2703 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2704 request_line = get_header(csp->client_iob);
2705 if (request_line == NULL)
2707 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2708 ssl_send_data_delayed(&(csp->ssl_client_attr),
2709 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2710 return JB_ERR_PARSE;
2712 assert(*request_line != '\0');
2714 if (client_protocol_is_unsupported(csp, request_line))
2717 * If the protocol is unsupported we're done here.
2718 * client_protocol_is_unsupported() took care of sending
2719 * the error response and logging the error message.
2721 return JB_ERR_PARSE;
2724 #ifdef FEATURE_FORCE_LOAD
2725 if (force_required(csp, request_line))
2727 csp->flags |= CSP_FLAG_FORCED;
2729 #endif /* def FEATURE_FORCE_LOAD */
2731 free_http_request(csp->http);
2733 err = parse_http_request(request_line, csp->http);
2734 /* XXX: Restore ssl setting. This is ugly */
2735 csp->http->client_ssl = 1;
2736 csp->http->server_ssl = 1;
2738 freez(request_line);
2739 if (JB_ERR_OK != err)
2741 ssl_send_data_delayed(&(csp->ssl_client_attr),
2742 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2743 /* XXX: Use correct size */
2744 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2745 log_error(LOG_LEVEL_ERROR,
2746 "Couldn't parse request line received from %s: %s",
2747 csp->ip_addr_str, jb_err_to_string(err));
2749 free_http_request(csp->http);
2750 return JB_ERR_PARSE;
2753 /* Parse the rest of the client's headers. */
2757 p = get_header(csp->client_iob);
2761 /* There are no additional headers to read. */
2768 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2771 * Our attempts to get the request destination
2774 log_error(LOG_LEVEL_ERROR,
2775 "Failed to get the encrypted request destination");
2776 ssl_send_data_delayed(&(csp->ssl_client_attr),
2777 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2778 return JB_ERR_PARSE;
2781 /* Split the domain we just got for pattern matching */
2782 init_domain_components(csp->http);
2784 #ifdef FEATURE_CLIENT_TAGS
2785 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2786 if (csp->client_address == NULL)
2788 set_client_address(csp, headers);
2789 get_tag_list_for_client(csp->client_tags, csp->client_address);
2793 #ifdef FEATURE_TOGGLE
2794 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2798 * Determine the actions for this request after
2799 * clearing the ones from the previous one.
2801 free_current_action(csp->action);
2802 get_url_actions(csp, csp->http);
2805 enlist(csp->https_headers, csp->http->cmd);
2807 /* Append the previously read headers */
2808 err = list_append_list_unique(csp->https_headers, headers);
2809 destroy_list(headers);
2810 if (JB_ERR_OK != err)
2812 /* XXX: Send error message */
2816 /* XXX: Work around crash */
2817 csp->error_message = NULL;
2819 /* XXX: Why do this here? */
2822 err = sed_https(csp);
2823 if (JB_ERR_OK != err)
2825 ssl_send_data_delayed(&(csp->ssl_client_attr),
2826 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2827 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2829 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2830 csp->ip_addr_str, csp->http->cmd);
2831 return JB_ERR_PARSE;
2834 if ((NULL == csp->https_headers->first->str)
2835 || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2836 (JB_ERR_OK != change_encrypted_request_destination(csp))))
2838 ssl_send_data_delayed(&(csp->ssl_client_attr),
2839 (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2840 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2841 log_error(LOG_LEVEL_ERROR,
2842 "Invalid request line after applying header filters.");
2843 /* XXX: Use correct size */
2844 log_error(LOG_LEVEL_CLF,
2845 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2847 return JB_ERR_PARSE;
2850 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2851 log_applied_actions(csp->action);
2852 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2859 /*********************************************************************
2861 * Function : cgi_page_requested
2863 * Description : Checks if a request is for an internal CGI page.
2866 * 1 : host = The host requested by the client.
2868 * Returns : 1 if a CGI page has been requested, 0 otherwise
2870 *********************************************************************/
2871 static int cgi_page_requested(const char *host)
2873 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2874 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2875 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2876 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2886 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2887 /*********************************************************************
2889 * Function : continue_https_chat
2891 * Description : Behaves similar to chat() but only deals with
2892 * https-inspected requests that arrive on an already
2893 * established connection. The first request is always
2894 * served by chat() which is a lot more complex as it
2895 * has to deal with forwarding settings and connection
2898 * If a connection to the server has already been
2899 * opened it is reused unless the request is blocked
2900 * or the forwarder changed.
2902 * If a connection to the server has not yet been
2903 * opened (because the previous request was crunched),
2904 * or the forwarder changed, the connection is dropped
2905 * so that the client retries on a fresh one.
2908 * 1 : csp = Current client state (buffers, headers, etc...)
2910 * Returns : Nothing.
2912 *********************************************************************/
2913 static void continue_https_chat(struct client_state *csp)
2915 const struct forward_spec *fwd;
2917 if (JB_ERR_OK != process_encrypted_request(csp))
2919 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2923 csp->requests_received_total++;
2926 * We have an encrypted request. Check if one of the crunchers wants it.
2928 if (crunch_response_triggered(csp, crunchers_all))
2931 * Yes. The client got the crunch response and we're done here.
2935 if (csp->ssl_with_server_is_opened == 0)
2937 log_error(LOG_LEVEL_CONNECT,
2938 "Dropping the client connection on socket %d. "
2939 "The server connection has not been established yet.",
2941 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2944 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2946 fwd = forward_url(csp, csp->http);
2947 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2949 log_error(LOG_LEVEL_CONNECT,
2950 "Dropping the client connection on socket %d with "
2951 "server socket %d connected to %s. The forwarder has changed.",
2952 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2953 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2957 log_error(LOG_LEVEL_CONNECT,
2958 "Reusing server socket %d connected to %s. Requests already sent: %u.",
2959 csp->server_connection.sfd, csp->server_connection.host,
2960 csp->server_connection.requests_sent_total);
2962 if (send_https_request(csp))
2965 * Most likely the server connection timed out. We can't easily
2966 * create a new one so simply drop the client connection without a
2967 * error response to let the client retry.
2969 log_error(LOG_LEVEL_CONNECT,
2970 "Dropping client connection on socket %d. "
2971 "Forwarding the encrypted client request failed.",
2975 csp->server_connection.requests_sent_total++;
2976 handle_established_connection(csp);
2977 freez(csp->receive_buffer);
2979 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2983 /*********************************************************************
2985 * Function : handle_established_connection
2987 * Description : Shuffle data between client and server once the
2988 * connection has been established.
2991 * 1 : csp = Current client state (buffers, headers, etc...)
2993 * Returns : Nothing.
2995 *********************************************************************/
2996 static void handle_established_connection(struct client_state *csp)
3002 struct pollfd poll_fds[2];
3006 struct timeval timeout;
3009 int ms_iis5_hack = 0;
3010 unsigned long long byte_count = 0;
3011 struct http_request *http;
3012 long len = 0; /* for buffer sizes (and negative error codes) */
3013 int buffer_and_filter_content = 0;
3014 unsigned int write_delay;
3015 #ifdef FEATURE_HTTPS_INSPECTION
3017 int use_ssl_tunnel = 0;
3018 csp->dont_verify_certificate = 0;
3020 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3022 /* Pass encrypted content without filtering. */
3027 /* Skeleton for HTTP response, if we should intercept the request */
3028 struct http_response *rsp;
3029 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3030 int watch_client_socket;
3033 csp->receive_buffer_size = csp->config->receive_buffer_size;
3034 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3035 if (csp->receive_buffer == NULL)
3037 log_error(LOG_LEVEL_ERROR,
3038 "Out of memory. Failed to allocate the receive buffer.");
3039 rsp = cgi_error_memory();
3040 send_crunch_response(csp, rsp);
3047 maxfd = (csp->cfd > csp->server_connection.sfd) ?
3048 csp->cfd : csp->server_connection.sfd;
3051 /* pass data between the client and server
3052 * until one or the other shuts down the connection.
3057 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3058 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3060 write_delay = get_write_delay(csp);
3066 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3067 if (!watch_client_socket)
3069 maxfd = csp->server_connection.sfd;
3072 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3074 FD_SET(csp->cfd, &rfds);
3077 FD_SET(csp->server_connection.sfd, &rfds);
3078 #endif /* ndef HAVE_POLL */
3080 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3081 if ((csp->flags & CSP_FLAG_CHUNKED)
3082 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3083 && ((csp->iob->eod - csp->iob->cur) >= 5)
3084 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3087 * XXX: This check should be obsolete now,
3088 * but let's wait a while to be sure.
3090 log_error(LOG_LEVEL_CONNECT,
3091 "Looks like we got the last chunk together with "
3092 "the server headers but didn't detect it earlier. "
3093 "We better stop reading.");
3094 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3095 csp->expected_content_length = byte_count;
3096 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3098 if (server_body && server_response_is_complete(csp, byte_count))
3100 if (csp->expected_content_length == byte_count)
3102 log_error(LOG_LEVEL_CONNECT,
3103 "Done reading from server. Content length: %llu as expected. "
3104 "Bytes most recently read: %ld.",
3109 log_error(LOG_LEVEL_CONNECT,
3110 "Done reading from server. Expected content length: %llu. "
3111 "Actual content length: %llu. Bytes most recently read: %ld.",
3112 csp->expected_content_length, byte_count, len);
3116 * XXX: Should not jump around, handle_established_connection()
3117 * is complicated enough already.
3121 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3124 poll_fds[0].fd = csp->cfd;
3125 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3126 if (!watch_client_socket)
3129 * Ignore incoming data, but still watch out
3130 * for disconnects etc. These flags are always
3131 * implied anyway but explicitly setting them
3134 poll_fds[0].events = POLLERR|POLLHUP;
3139 poll_fds[0].events = POLLIN;
3141 poll_fds[1].fd = csp->server_connection.sfd;
3142 poll_fds[1].events = POLLIN;
3143 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3145 timeout.tv_sec = csp->config->socket_timeout;
3146 timeout.tv_usec = 0;
3147 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3148 #endif /* def HAVE_POLL */
3150 /*server or client not responding in timeout */
3153 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3154 csp->config->socket_timeout, http->url);
3155 if ((byte_count == 0) && (http->ssl == 0))
3157 send_crunch_response(csp, error_response(csp, "connection-timeout"));
3159 mark_server_socket_tainted(csp);
3160 #ifdef FEATURE_HTTPS_INSPECTION
3161 close_client_and_server_ssl_connections(csp);
3168 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3170 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3172 mark_server_socket_tainted(csp);
3173 #ifdef FEATURE_HTTPS_INSPECTION
3174 close_client_and_server_ssl_connections(csp);
3180 * This is the body of the browser's request,
3181 * just read and write it.
3183 * Receives data from browser and sends it to server
3185 * XXX: Make sure the client doesn't use pipelining
3186 * behind Privoxy's back.
3189 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3191 log_error(LOG_LEVEL_CONNECT,
3192 "The client socket %d has become unusable while "
3193 "the server socket %d is still open.",
3194 csp->cfd, csp->server_connection.sfd);
3195 mark_server_socket_tainted(csp);
3199 if (poll_fds[0].revents != 0)
3201 if (FD_ISSET(csp->cfd, &rfds))
3202 #endif /* def HAVE_POLL*/
3204 int max_bytes_to_read = (int)csp->receive_buffer_size;
3206 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3207 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3209 if (data_is_available(csp->cfd, 0))
3212 * If the next request is already waiting, we have
3213 * to stop select()ing the client socket. Otherwise
3214 * we would always return right away and get nothing
3217 watch_client_socket = 0;
3218 log_error(LOG_LEVEL_CONNECT,
3219 "Stop watching client socket %d. "
3220 "There's already another request waiting.",
3225 * If the client socket is set, but there's no data
3226 * available on the socket, the client went fishing
3227 * and continuing talking to the server makes no sense.
3229 log_error(LOG_LEVEL_CONNECT,
3230 "The client closed socket %d while "
3231 "the server socket %d is still open.",
3232 csp->cfd, csp->server_connection.sfd);
3233 mark_server_socket_tainted(csp);
3236 if (csp->expected_client_content_length != 0)
3238 if (csp->expected_client_content_length < csp->receive_buffer_size)
3240 max_bytes_to_read = (int)csp->expected_client_content_length;
3242 log_error(LOG_LEVEL_CONNECT,
3243 "Waiting for up to %d bytes from the client.",
3246 assert(max_bytes_to_read <= csp->receive_buffer_size);
3247 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3249 #ifdef FEATURE_HTTPS_INSPECTION
3250 if (client_use_ssl(csp))
3252 if (csp->http->status == 101)
3254 len = ssl_recv_data(&(csp->ssl_client_attr),
3255 (unsigned char *)csp->receive_buffer,
3256 (size_t)max_bytes_to_read);
3259 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3260 "on client socket %d for an upgraded connection",
3266 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3267 "on client socket %d for an upgraded connection",
3271 byte_count += (unsigned long long)len;
3272 len = ssl_send_data(&(csp->ssl_server_attr),
3273 (unsigned char *)csp->receive_buffer, (size_t)len);
3276 log_error(LOG_LEVEL_ERROR, "Failed to send data "
3277 "on server socket %d for an upgraded connection",
3278 csp->server_connection.sfd);
3283 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3287 #endif /* def FEATURE_HTTPS_INSPECTION */
3289 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3293 /* XXX: not sure if this is necessary. */
3294 mark_server_socket_tainted(csp);
3295 break; /* "game over, man" */
3298 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3299 if (csp->expected_client_content_length != 0)
3301 assert(len <= max_bytes_to_read);
3302 csp->expected_client_content_length -= (unsigned)len;
3303 log_error(LOG_LEVEL_CONNECT,
3304 "Expected client content length set to %llu "
3305 "after reading %ld bytes.",
3306 csp->expected_client_content_length, len);
3307 if (csp->expected_client_content_length == 0)
3309 log_error(LOG_LEVEL_CONNECT,
3310 "Done reading from the client.");
3311 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3314 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3316 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3318 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3319 mark_server_socket_tainted(csp);
3327 * The server wants to talk. It could be the header or the body.
3328 * If `hdr' is null, then it's the header otherwise it's the body.
3329 * FIXME: Does `hdr' really mean `host'? No.
3332 if (poll_fds[1].revents != 0)
3334 if (FD_ISSET(csp->server_connection.sfd, &rfds))
3335 #endif /* HAVE_POLL */
3337 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3339 * If we are buffering content, we don't want to eat up to
3340 * buffer-limit bytes if the client no longer cares about them.
3341 * If we aren't buffering, however, a dead client socket will be
3342 * noticed pretty much right away anyway, so we can reduce the
3343 * overhead by skipping the check.
3345 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3348 log_error(LOG_LEVEL_CONNECT,
3349 "The server still wants to talk, but the client may already have hung up on us.");
3351 log_error(LOG_LEVEL_CONNECT,
3352 "The server still wants to talk, but the client hung up on us.");
3353 mark_server_socket_tainted(csp);
3354 #ifdef FEATURE_HTTPS_INSPECTION
3355 close_client_and_server_ssl_connections(csp);
3358 #endif /* def _WIN32 */
3360 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3362 #ifdef FEATURE_HTTPS_INSPECTION
3364 * Reading data from standard or secured connection (HTTP/HTTPS)
3366 if (server_use_ssl(csp))
3368 len = ssl_recv_data(&(csp->ssl_server_attr),
3369 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3374 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3375 (int)csp->receive_buffer_size);
3380 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3382 if ((http->ssl && (csp->fwd == NULL))
3383 #ifdef FEATURE_HTTPS_INSPECTION
3389 * Just hang up. We already confirmed the client's CONNECT
3390 * request with status code 200 and unencrypted content is
3391 * no longer welcome.
3393 log_error(LOG_LEVEL_ERROR,
3394 "CONNECT already confirmed. Unable to tell the client about the problem.");
3397 else if (byte_count)
3400 * Just hang up. We already transmitted the original headers
3401 * and parts of the original content and therefore missed the
3402 * chance to send an error message (without risking data corruption).
3404 * XXX: we could retry with a fancy range request here.
3406 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3407 "Unable to tell the client about the problem.");
3408 mark_server_socket_tainted(csp);
3409 #ifdef FEATURE_HTTPS_INSPECTION
3410 close_client_and_server_ssl_connections(csp);
3415 * XXX: Consider handling the cases above the same.
3417 mark_server_socket_tainted(csp);
3421 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3422 if (csp->flags & CSP_FLAG_CHUNKED)
3424 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3426 /* XXX: this is a temporary hack */
3427 log_error(LOG_LEVEL_CONNECT,
3428 "Looks like we reached the end of the last chunk. "
3429 "We better stop reading.");
3430 csp->expected_content_length = byte_count + (unsigned long long)len;
3431 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3435 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3438 * This is guaranteed by allocating with zalloc_or_die()
3439 * and never (intentionally) writing to the last byte.
3441 * csp->receive_buffer_size is the size of the part of the
3442 * buffer we intentionally write to, but we actually
3443 * allocated csp->receive_buffer_size+1 bytes so the assertion
3444 * stays within the allocated range.
3446 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3449 * Add a trailing zero to let be able to use string operations.
3450 * XXX: do we still need this with filter_popups gone?
3452 assert(len <= csp->receive_buffer_size);
3453 csp->receive_buffer[len] = '\0';
3456 * Normally, this would indicate that we've read
3457 * as much as the server has sent us and we can
3458 * close the client connection. However, Microsoft
3459 * in its wisdom has released IIS/5 with a bug that
3460 * prevents it from sending the trailing \r\n in
3461 * a 302 redirect header (and possibly other headers).
3462 * To work around this if we've haven't parsed
3463 * a full header we'll append a trailing \r\n
3464 * and see if this now generates a valid one.
3466 * This hack shouldn't have any impacts. If we've
3467 * already transmitted the header or if this is a
3468 * SSL connection, then we won't bother with this
3469 * hack. So we only work on partially received
3470 * headers. If we append a \r\n and this still
3471 * doesn't generate a valid header, then we won't
3472 * transmit anything to the client.
3477 if (server_body || (http->ssl
3478 #ifdef FEATURE_HTTPS_INSPECTION
3484 * If we have been buffering up the document,
3485 * now is the time to apply content modification
3486 * and send the result to the client.
3488 if (buffer_and_filter_content)
3490 p = execute_content_filters(csp);
3492 * If content filtering fails, use the original
3493 * buffer and length.
3494 * (see p != NULL ? p : csp->iob->cur below)
3498 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3500 #ifdef FEATURE_COMPRESSION
3501 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3502 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3504 char *compressed_content = compress_buffer(p,
3505 (size_t *)&csp->content_length, csp->config->compression_level);
3506 if (compressed_content != NULL)
3509 p = compressed_content;
3510 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3515 if (JB_ERR_OK != update_server_headers(csp))
3517 log_error(LOG_LEVEL_FATAL,
3518 "Failed to update server headers. after filtering.");
3521 hdr = list_to_text(csp->headers);
3524 /* FIXME Should handle error properly */
3525 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3528 #ifdef FEATURE_HTTPS_INSPECTION
3530 * Sending data with standard or secured connection (HTTP/HTTPS)
3532 if (client_use_ssl(csp))
3534 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3535 (const unsigned char *)hdr, strlen(hdr),
3536 get_write_delay(csp)) < 0)
3537 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3538 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3539 csp->content_length, get_write_delay(csp)) < 0))
3541 log_error(LOG_LEVEL_ERROR, "write modified content to "
3542 "client over TLS/SSL failed");
3545 mark_server_socket_tainted(csp);
3546 close_client_and_server_ssl_connections(csp);
3551 #endif /* def FEATURE_HTTPS_INSPECTION */
3553 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3554 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3555 (size_t)csp->content_length, write_delay))
3557 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3560 mark_server_socket_tainted(csp);
3569 break; /* "game over, man" */
3573 * This is NOT the body, so
3574 * Let's pretend the server just sent us a blank line.
3576 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3577 len = (int)strlen(csp->receive_buffer);
3580 * Now, let the normal header parsing algorithm below do its
3581 * job. If it fails, we'll exit instead of continuing.
3588 * If we're in the body of the server document, just write it to
3589 * the client, unless we need to buffer the body for later
3590 * content-filtering.
3592 if (server_body || (http->ssl
3593 #ifdef FEATURE_HTTPS_INSPECTION
3598 if (buffer_and_filter_content)
3601 * If there is no memory left for buffering the content, or the buffer limit
3602 * has been reached, switch to non-filtering mode, i.e. make & write the
3603 * header, flush the iob and buf, and get out of the way.
3605 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3610 log_error(LOG_LEVEL_INFO,
3611 "Flushing header and buffers. Stepping back from filtering.");
3613 hdr = list_to_text(csp->headers);
3617 * Memory is too tight to even generate the header.
3618 * Send our static "Out-of-memory" page.
3620 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3621 rsp = cgi_error_memory();
3622 send_crunch_response(csp, rsp);
3623 mark_server_socket_tainted(csp);
3624 #ifdef FEATURE_HTTPS_INSPECTION
3625 close_client_and_server_ssl_connections(csp);
3629 hdrlen = strlen(hdr);
3631 #ifdef FEATURE_HTTPS_INSPECTION
3633 * Sending data with standard or secured connection (HTTP/HTTPS)
3635 if (client_use_ssl(csp))
3637 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3638 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3639 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3641 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3642 (const unsigned char *)csp->receive_buffer, (size_t)len,
3643 get_write_delay(csp)) < 0))
3645 log_error(LOG_LEVEL_CONNECT,
3646 "Flush header and buffers to client failed");
3648 mark_server_socket_tainted(csp);
3649 close_client_and_server_ssl_connections(csp);
3654 #endif /* def FEATURE_HTTPS_INSPECTION */
3656 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3657 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3658 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3661 log_error(LOG_LEVEL_CONNECT,
3662 "Flush header and buffers to client failed: %E");
3664 mark_server_socket_tainted(csp);
3670 * Reset the byte_count to the amount of bytes
3671 * we just flushed. len will be added a few lines below,
3672 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3674 byte_count = (unsigned long long)flushed;
3676 buffer_and_filter_content = 0;
3682 #ifdef FEATURE_HTTPS_INSPECTION
3684 * Sending data with standard or secured connection (HTTP/HTTPS)
3686 if (client_use_ssl(csp))
3688 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3689 (const unsigned char *)csp->receive_buffer, (size_t)len,
3690 get_write_delay(csp));
3693 log_error(LOG_LEVEL_ERROR,
3694 "Sending data to client failed");
3695 mark_server_socket_tainted(csp);
3696 close_client_and_server_ssl_connections(csp);
3701 #endif /* def FEATURE_HTTPS_INSPECTION */
3703 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3704 (size_t)len, write_delay))
3706 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3707 mark_server_socket_tainted(csp);
3712 byte_count += (unsigned long long)len;
3718 * We're still looking for the end of the server's header.
3719 * Buffer up the data we just read. If that fails, there's
3720 * little we can do but send our static out-of-memory page.
3722 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3724 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3725 rsp = cgi_error_memory();
3726 send_crunch_response(csp, rsp);
3727 mark_server_socket_tainted(csp);
3728 #ifdef FEATURE_HTTPS_INSPECTION
3729 close_client_and_server_ssl_connections(csp);
3734 /* Convert iob into something sed() can digest */
3735 if (JB_ERR_PARSE == get_server_headers(csp))
3740 * Well, we tried our MS IIS/5 hack and it didn't work.
3741 * The header is incomplete and there isn't anything
3742 * we can do about it.
3744 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3745 "Applying the MS IIS5 hack didn't help.");
3746 log_error(LOG_LEVEL_CLF,
3747 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3748 #ifdef FEATURE_HTTPS_INSPECTION
3750 * Sending data with standard or secured connection (HTTP/HTTPS)
3752 if (client_use_ssl(csp))
3754 ssl_send_data_delayed(&(csp->ssl_client_attr),
3755 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3756 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3759 #endif /* def FEATURE_HTTPS_INSPECTION */
3761 write_socket_delayed(csp->cfd,
3762 INVALID_SERVER_HEADERS_RESPONSE,
3763 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3765 mark_server_socket_tainted(csp);
3766 #ifdef FEATURE_HTTPS_INSPECTION
3767 close_client_and_server_ssl_connections(csp);
3774 * Since we have to wait for more from the server before
3775 * we can parse the headers we just continue here.
3777 log_error(LOG_LEVEL_CONNECT,
3778 "Continuing buffering server headers from socket %d. "
3779 "Bytes most recently read: %ld.", csp->cfd, len);
3786 * Account for the content bytes we
3787 * might have gotten with the headers.
3789 assert(csp->iob->eod >= csp->iob->cur);
3790 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3793 /* Did we actually get anything? */
3794 if (NULL == csp->headers->first)
3796 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3798 log_error(LOG_LEVEL_ERROR,
3799 "No server or forwarder response received on socket %d. "
3800 "Closing client socket %d without sending data.",
3801 csp->server_connection.sfd, csp->cfd);
3802 log_error(LOG_LEVEL_CLF,
3803 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3807 log_error(LOG_LEVEL_ERROR,
3808 "No server or forwarder response received on socket %d.",
3809 csp->server_connection.sfd);
3810 send_crunch_response(csp, error_response(csp, "no-server-data"));
3812 free_http_request(http);
3813 mark_server_socket_tainted(csp);
3814 #ifdef FEATURE_HTTPS_INSPECTION
3815 close_client_and_server_ssl_connections(csp);
3820 if (!csp->headers->first->str)
3822 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3824 assert(csp->headers->first->str);
3826 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3827 strncmpic(csp->headers->first->str, "ICY", 3))
3830 * It doesn't look like a HTTP (or Shoutcast) response:
3831 * tell the client and log the problem.
3833 if (strlen(csp->headers->first->str) > 30)
3835 csp->headers->first->str[30] = '\0';
3837 log_error(LOG_LEVEL_ERROR,
3838 "Invalid server or forwarder response. Starts with: %s",
3839 csp->headers->first->str);
3840 log_error(LOG_LEVEL_CLF,
3841 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3842 #ifdef FEATURE_HTTPS_INSPECTION
3844 * Sending data with standard or secured connection (HTTP/HTTPS)
3846 if (client_use_ssl(csp))
3848 ssl_send_data_delayed(&(csp->ssl_client_attr),
3849 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3850 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3851 get_write_delay(csp));
3854 #endif /* def FEATURE_HTTPS_INSPECTION */
3856 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3857 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3859 free_http_request(http);
3860 mark_server_socket_tainted(csp);
3861 #ifdef FEATURE_HTTPS_INSPECTION
3862 close_client_and_server_ssl_connections(csp);
3868 * We have now received the entire server header,
3869 * filter it and send the result to the client
3871 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3873 log_error(LOG_LEVEL_CLF,
3874 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3875 #ifdef FEATURE_HTTPS_INSPECTION
3877 * Sending data with standard or secured connection (HTTP/HTTPS)
3879 if (client_use_ssl(csp))
3881 ssl_send_data_delayed(&(csp->ssl_client_attr),
3882 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3883 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3884 get_write_delay(csp));
3889 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3890 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3892 free_http_request(http);
3893 mark_server_socket_tainted(csp);
3894 #ifdef FEATURE_HTTPS_INSPECTION
3895 close_client_and_server_ssl_connections(csp);
3899 hdr = list_to_text(csp->headers);
3902 /* FIXME Should handle error properly */
3903 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3906 if ((csp->flags & CSP_FLAG_CHUNKED)
3907 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3908 && ((csp->iob->eod - csp->iob->cur) >= 5)
3909 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3911 log_error(LOG_LEVEL_CONNECT,
3912 "Looks like we got the last chunk together with "
3913 "the server headers. We better stop reading.");
3914 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3915 csp->expected_content_length = byte_count;
3916 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3919 csp->server_connection.response_received = time(NULL);
3921 if (crunch_response_triggered(csp, crunchers_light))
3924 * One of the tags created by a server-header
3925 * tagger triggered a crunch. We already
3926 * delivered the crunch response to the client
3927 * and are done here after cleaning up.
3930 mark_server_socket_tainted(csp);
3931 #ifdef FEATURE_HTTPS_INSPECTION
3932 close_client_and_server_ssl_connections(csp);
3937 /* Buffer and pcrs filter this if appropriate. */
3938 buffer_and_filter_content = content_requires_filtering(csp);
3940 if (!buffer_and_filter_content)
3943 * Write the server's (modified) header to
3944 * the client (along with anything else that
3945 * may be in the buffer). Use standard or secured
3948 #ifdef FEATURE_HTTPS_INSPECTION
3949 if (client_use_ssl(csp))
3951 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3952 (const unsigned char *)hdr, strlen(hdr),
3953 get_write_delay(csp)) < 0)
3954 || ((len = ssl_flush_socket(&(csp->ssl_client_attr),
3957 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3960 * The write failed, so don't bother mentioning it
3961 * to the client... it probably can't hear us anyway.
3964 mark_server_socket_tainted(csp);
3965 #ifdef FEATURE_HTTPS_INSPECTION
3966 close_client_and_server_ssl_connections(csp);
3972 #endif /* def FEATURE_HTTPS_INSPECTION */
3974 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3975 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3977 log_error(LOG_LEVEL_ERROR,
3978 "write header to client failed");
3980 * The write failed, so don't bother mentioning it
3981 * to the client... it probably can't hear us anyway.
3984 mark_server_socket_tainted(csp);
3990 /* we're finished with the server's header */
3996 * If this was a MS IIS/5 hack then it means the server
3997 * has already closed the connection. Nothing more to read.
4002 log_error(LOG_LEVEL_ERROR,
4003 "Closed server connection detected. "
4004 "Applying the MS IIS5 hack didn't help.");
4005 log_error(LOG_LEVEL_CLF,
4006 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4007 #ifdef FEATURE_HTTPS_INSPECTION
4009 * Sending data with standard or secured connection (HTTP/HTTPS)
4011 if (client_use_ssl(csp))
4013 ssl_send_data_delayed(&(csp->ssl_client_attr),
4014 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4015 strlen(INVALID_SERVER_HEADERS_RESPONSE),
4016 get_write_delay(csp));
4019 #endif /* def FEATURE_HTTPS_INSPECTION */
4021 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4022 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4024 mark_server_socket_tainted(csp);
4025 #ifdef FEATURE_HTTPS_INSPECTION
4026 close_client_and_server_ssl_connections(csp);
4033 mark_server_socket_tainted(csp);
4034 #ifdef FEATURE_HTTPS_INSPECTION
4035 close_client_and_server_ssl_connections(csp);
4037 return; /* huh? we should never get here */
4040 if (csp->content_length == 0)
4043 * If Privoxy didn't recalculate the Content-Length,
4044 * byte_count is still correct.
4046 csp->content_length = byte_count;
4049 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4050 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4051 && (csp->expected_content_length != byte_count))
4053 log_error(LOG_LEVEL_CONNECT,
4054 "Received %llu bytes while expecting %llu.",
4055 byte_count, csp->expected_content_length);
4056 mark_server_socket_tainted(csp);
4060 #ifdef FEATURE_HTTPS_INSPECTION
4061 if (client_use_ssl(csp))
4063 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4064 csp->ip_addr_str, http->gpc, http->hostport, http->path,
4065 http->version, csp->content_length);
4070 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4071 csp->ip_addr_str, http->ocmd, csp->content_length);
4073 csp->server_connection.timestamp = time(NULL);
4077 /*********************************************************************
4081 * Description : Once a connection from the client has been accepted,
4082 * this function is called (via serve()) to handle the
4083 * main business of the communication. This function
4084 * returns after dealing with a single request. It can
4085 * be called multiple times with the same client socket
4086 * if the client is keeping the connection alive.
4088 * The decision whether or not a client connection will
4089 * be kept alive is up to the caller which also must
4090 * close the client socket when done.
4092 * FIXME: chat is nearly thousand lines long.
4096 * 1 : csp = Current client state (buffers, headers, etc...)
4098 * Returns : Nothing.
4100 *********************************************************************/
4101 static void chat(struct client_state *csp)
4103 const struct forward_spec *fwd;
4104 struct http_request *http;
4105 /* Skeleton for HTTP response, if we should intercept the request */
4106 struct http_response *rsp;
4107 #ifdef FEATURE_HTTPS_INSPECTION
4108 int use_ssl_tunnel = 0;
4113 if (receive_client_request(csp) != JB_ERR_OK)
4117 if (parse_client_request(csp) != JB_ERR_OK)
4122 /* decide how to route the HTTP request */
4123 fwd = forward_url(csp, http);
4125 #ifdef FEATURE_HTTPS_INSPECTION
4127 * Setting flags to use old solution with SSL tunnel and to disable
4128 * certificate verification.
4130 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4131 && !cgi_page_requested(csp->http->host))
4136 if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4138 csp->dont_verify_certificate = 1;
4143 * build the http request to send to the server
4144 * we have to do one of the following:
4146 * create = use the original HTTP request to create a new
4147 * HTTP request that has either the path component
4148 * without the http://domainspec (w/path) or the
4149 * full orininal URL (w/url)
4150 * Note that the path and/or the HTTP version may
4151 * have been altered by now.
4153 * SSL proxy = Open a socket to the host:port of the server
4154 * and create TLS/SSL connection with server and
4155 * with client. Then behave like mediator between
4156 * client and server over TLS/SSL.
4158 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4159 * with request to a parent proxy. Note that we'll be sending
4160 * forwarding the CFAIL message ourselves if connecting to the parent
4161 * fails, but we won't send a CSUCCEED message if it works,
4162 * since that would result in a double message (ours and the
4163 * parent's). After sending the request to the parent, we
4164 * must parse answer and send it to client. If connection
4165 * with server is established, we do TLS/SSL proxy. Otherwise
4166 * we send parent response to client and close connections.
4168 * here's the matrix:
4171 * +--------+--------+
4173 * 0 | create | SSL |
4174 * | w/path | proxy |
4175 * Forwarding +--------+--------+
4177 * 1 | create | proxy |
4178 * | w/url |+forward|
4179 * +--------+--------+
4183 #ifdef FEATURE_HTTPS_INSPECTION
4185 * Presetting SSL client and server flags
4187 if (http->ssl && !use_ssl_tunnel)
4189 http->client_ssl = 1;
4190 http->server_ssl = 1;
4194 http->client_ssl = 0;
4195 http->server_ssl = 0;
4199 #ifdef FEATURE_HTTPS_INSPECTION
4201 * Log the request unless we're https inspecting
4202 * in which case we don't have the path yet and
4203 * will log the request later.
4205 if (!client_use_ssl(csp))
4208 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4211 if (http->ssl && connect_port_is_forbidden(csp))
4213 const char *acceptable_connect_ports =
4214 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4215 assert(NULL != acceptable_connect_ports);
4216 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4217 "limit-connect{%s} doesn't allow CONNECT requests to %s",
4218 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4219 csp->action->flags |= ACTION_BLOCK;
4221 #ifdef FEATURE_HTTPS_INSPECTION
4222 http->client_ssl = 0;
4223 http->server_ssl = 0;
4228 freez(csp->headers->first->str);
4229 build_request_line(csp, fwd, &csp->headers->first->str);
4232 * We have a request. Check if one of the crunchers wants it
4233 * unless the client wants to use TLS/SSL in which case we
4234 * haven't setup the TLS context yet and will send the crunch
4238 #ifdef FEATURE_HTTPS_INSPECTION
4239 !client_use_ssl(csp) &&
4241 crunch_response_triggered(csp, crunchers_all))
4244 * Yes. The client got the crunch response and we're done here.
4249 log_applied_actions(csp->action);
4250 if (fwd->forward_host)
4252 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4253 fwd->forward_host, fwd->forward_port, http->hostport);
4257 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4260 /* here we connect to the server, gateway, or the forwarder */
4262 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4263 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4264 && socket_is_still_alive(csp->server_connection.sfd)
4265 && connection_destination_matches(&csp->server_connection, http, fwd))
4267 log_error(LOG_LEVEL_CONNECT,
4268 "Reusing server socket %d connected to %s. Total requests: %u.",
4269 csp->server_connection.sfd, csp->server_connection.host,
4270 csp->server_connection.requests_sent_total);
4274 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4276 #ifdef FEATURE_CONNECTION_SHARING
4277 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4278 #ifdef FEATURE_HTTPS_INSPECTION
4279 && !server_use_ssl(csp)
4283 remember_connection(&csp->server_connection);
4286 #endif /* def FEATURE_CONNECTION_SHARING */
4288 log_error(LOG_LEVEL_CONNECT,
4289 "Closing server socket %d connected to %s. Total requests: %u.",
4290 csp->server_connection.sfd, csp->server_connection.host,
4291 csp->server_connection.requests_sent_total);
4292 close_socket(csp->server_connection.sfd);
4294 mark_connection_closed(&csp->server_connection);
4296 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4297 #ifdef FEATURE_HTTPS_INSPECTION
4298 if (client_use_ssl(csp) && !use_ssl_tunnel)
4302 * Creating a SSL proxy.
4304 * By sending the CSUCCEED message we're lying to the client as
4305 * the connection hasn't actually been established yet. We don't
4306 * establish the connection until we have seen and parsed the
4307 * encrypted client headers.
4309 if (write_socket_delayed(csp->cfd, CSUCCEED,
4310 strlen(CSUCCEED), get_write_delay(csp)) != 0)
4312 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4316 ret = create_client_ssl_connection(csp);
4319 log_error(LOG_LEVEL_ERROR,
4320 "Failed to open a secure connection with the client");
4323 if (JB_ERR_OK != process_encrypted_request(csp))
4325 close_client_ssl_connection(csp);
4329 * We have an encrypted request. Check if one of the crunchers now
4330 * wants it (for example because the previously invisible path was
4331 * required to match).
4333 if (crunch_response_triggered(csp, crunchers_all))
4336 * Yes. The client got the crunch response and we're done here.
4343 * Connecting to destination server
4345 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4347 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4349 if (fwd->type != SOCKS_NONE)
4352 rsp = error_response(csp, "forwarding-failed");
4354 else if (errno == EINVAL)
4356 rsp = error_response(csp, "no-such-domain");
4360 rsp = error_response(csp, "connect-failed");
4363 /* Write the answer to the client */
4366 send_crunch_response(csp, rsp);
4370 * Temporary workaround to prevent already-read client
4371 * bodies from being parsed as new requests. For now we
4372 * err on the safe side and throw all the following
4373 * requests under the bus, even if no client body has been
4374 * buffered. A compliant client will repeat the dropped
4375 * requests on an untainted connection.
4377 * The proper fix is to discard the no longer needed
4378 * client body in the buffer (if there is one) and to
4379 * continue parsing the bytes that follow.
4381 #ifdef FEATURE_HTTPS_INSPECTION
4382 close_client_ssl_connection(csp);
4384 drain_and_close_socket(csp->cfd);
4385 csp->cfd = JB_INVALID_SOCKET;
4390 #ifdef FEATURE_HTTPS_INSPECTION
4392 * Creating TLS/SSL connections with destination server or parent
4393 * proxy. If forwarding is enabled, we must send client request to
4394 * parent proxy and receive, parse and resend parent proxy answer.
4396 if (http->ssl && !use_ssl_tunnel)
4398 if (fwd->forward_host != NULL)
4400 char server_response[BUFFER_SIZE];
4403 char *hdr = list_to_text(csp->headers);
4404 memset(server_response, 0, sizeof(server_response));
4408 log_error(LOG_LEVEL_FATAL,
4409 "Out of memory parsing client header");
4411 list_remove_all(csp->headers);
4414 * Sending client's CONNECT request to the parent proxy
4416 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4422 log_error(LOG_LEVEL_CONNECT,
4423 "Sending request headers to: %s failed", http->hostport);
4424 mark_server_socket_tainted(csp);
4425 close_client_ssl_connection(csp);
4429 /* Waiting for parent proxy server response */
4430 len = read_socket(csp->server_connection.sfd, server_response,
4431 sizeof(server_response)-1);
4435 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4436 "server on socket %d.", csp->server_connection.sfd);
4438 rsp = error_response(csp, "no-server-data");
4441 send_crunch_response(csp, rsp);
4443 mark_server_socket_tainted(csp);
4444 close_client_ssl_connection(csp);
4449 * Test if the connection to the destination server was
4450 * established successfully by the parent proxy.
4452 if (!tunnel_established_successfully(server_response, (unsigned int)len))
4454 log_error(LOG_LEVEL_ERROR,
4455 "The forwarder %s failed to establish a connection with %s",
4456 fwd->forward_host, http->host);
4457 rsp = error_response(csp, "connect-failed");
4460 send_crunch_response(csp, rsp);
4462 mark_server_socket_tainted(csp);
4463 close_client_ssl_connection(csp);
4466 } /* -END- if (fwd->forward_host != NULL) */
4469 * We can now create the TLS/SSL connection with the destination server.
4471 int ret = create_server_ssl_connection(csp);
4474 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4475 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4478 * If the server certificate is invalid, we must inform
4479 * the client and then close connection to the client.
4481 ssl_send_certificate_error(csp);
4482 close_client_and_server_ssl_connections(csp);
4485 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4486 || csp->server_cert_verification_result == SSL_CERT_VALID)
4489 * The TLS/SSL connection wasn't created but an invalid
4490 * certificate wasn't detected. Report it as connection
4493 rsp = error_response(csp, "connect-failed");
4496 send_crunch_response(csp, rsp);
4498 close_client_and_server_ssl_connections(csp);
4502 }/* -END- if (http->ssl) */
4503 #endif /* def FEATURE_HTTPS_INSPECTION */
4505 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4506 save_connection_destination(csp->server_connection.sfd,
4507 http, fwd, &csp->server_connection);
4508 csp->server_connection.keep_alive_timeout =
4509 (unsigned)csp->config->keep_alive_timeout;
4511 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4513 csp->server_connection.requests_sent_total++;
4515 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4517 /* Client headers have been sent optimistically */
4518 assert(csp->headers->last == NULL);
4520 else if (http->ssl == 0 || (fwd->forward_host
4521 #ifdef FEATURE_HTTPS_INSPECTION
4526 if (send_http_request(csp))
4528 rsp = error_response(csp, "connect-failed");
4531 send_crunch_response(csp, rsp);
4539 * Using old solution with SSL tunnel or new solution with SSL proxy
4541 list_remove_all(csp->headers);
4542 #ifdef FEATURE_HTTPS_INSPECTION
4547 * We're running an SSL tunnel and we're not forwarding,
4548 * so just ditch the client headers, send the "connect succeeded"
4549 * message to the client, flush the rest, and get out of the way.
4551 if (write_socket_delayed(csp->cfd, CSUCCEED,
4552 strlen(CSUCCEED), get_write_delay(csp)))
4557 #ifdef FEATURE_HTTPS_INSPECTION
4561 * If server certificate has been verified and is invalid,
4562 * we must inform the client and then close the connection
4563 * with client and server.
4565 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4566 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4568 ssl_send_certificate_error(csp);
4569 close_client_and_server_ssl_connections(csp);
4572 if (send_https_request(csp))
4574 rsp = error_response(csp, "connect-failed");
4577 send_crunch_response(csp, rsp);
4579 close_client_and_server_ssl_connections(csp);
4583 #endif /* def FEATURE_HTTPS_INSPECTION */
4584 clear_iob(csp->client_iob);
4585 }/* -END- else ... if (http->ssl == 1) */
4587 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4589 /* XXX: should the time start earlier for optimistically sent data? */
4590 csp->server_connection.request_sent = time(NULL);
4592 handle_established_connection(csp);
4593 freez(csp->receive_buffer);
4598 /*********************************************************************
4600 * Function : fuzz_server_response
4602 * Description : Treat the input as a whole server response.
4605 * 1 : csp = Current client state (buffers, headers, etc...)
4606 * 2 : fuzz_input_file = File to read the input from.
4610 *********************************************************************/
4611 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4613 static struct forward_spec fwd; /* Zero'd due to being static */
4616 if (strcmp(fuzz_input_file, "-") == 0)
4618 /* XXX: Doesn't work yet. */
4619 csp->server_connection.sfd = 0;
4623 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4624 if (csp->server_connection.sfd == -1)
4626 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4631 csp->content_type |= CT_GIF;
4632 csp->action->flags |= ACTION_DEANIMATE;
4633 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4635 csp->http->path = strdup_or_die("/");
4636 csp->http->host = strdup_or_die("fuzz.example.org");
4637 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4638 /* Prevent client socket monitoring */
4639 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4640 csp->flags |= CSP_FLAG_CHUNKED;
4642 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4643 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4645 csp->content_type |= CT_DECLARED|CT_GIF;
4647 csp->config->socket_timeout = 0;
4649 cgi_init_error_messages();
4651 handle_established_connection(csp);
4652 freez(csp->receive_buffer);
4659 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4660 /*********************************************************************
4662 * Function : prepare_csp_for_next_request
4664 * Description : Put the csp in a mostly vergin state.
4667 * 1 : csp = Current client state (buffers, headers, etc...)
4671 *********************************************************************/
4672 static void prepare_csp_for_next_request(struct client_state *csp)
4674 csp->content_type = 0;
4675 csp->content_length = 0;
4676 csp->expected_content_length = 0;
4677 csp->expected_client_content_length = 0;
4678 list_remove_all(csp->headers);
4679 clear_iob(csp->iob);
4680 freez(csp->error_message);
4681 free_http_request(csp->http);
4682 destroy_list(csp->headers);
4683 #ifdef FEATURE_HTTPS_INSPECTION
4684 destroy_list(csp->https_headers);
4686 destroy_list(csp->tags);
4687 #ifdef FEATURE_CLIENT_TAGS
4688 destroy_list(csp->client_tags);
4689 freez(csp->client_address);
4691 free_current_action(csp->action);
4692 if (NULL != csp->fwd)
4694 unload_forward_spec(csp->fwd);
4697 /* XXX: Store per-connection flags someplace else. */
4698 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4699 #ifdef FEATURE_TOGGLE
4700 if (global_toggle_state)
4701 #endif /* def FEATURE_TOGGLE */
4703 csp->flags |= CSP_FLAG_TOGGLED_ON;
4706 if (csp->client_iob->eod > csp->client_iob->cur)
4708 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4709 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4711 assert(bytes_to_shift > 0);
4712 assert(data_length > 0);
4714 log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4715 data_length, bytes_to_shift);
4716 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4717 csp->client_iob->cur = csp->client_iob->buf;
4718 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4719 csp->client_iob->eod = csp->client_iob->buf + data_length;
4720 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4722 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4727 * We mainly care about resetting client_iob->cur so we don't
4728 * waste buffer space at the beginning and don't mess up the
4729 * request restoration done by cgi_show_request().
4731 * Freeing the buffer itself isn't technically necessary,
4732 * but makes debugging more convenient.
4734 clear_iob(csp->client_iob);
4737 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4740 /*********************************************************************
4744 * Description : This is little more than chat. We only "serve" to
4745 * to close (or remember) any socket that chat may have
4749 * 1 : csp = Current client state (buffers, headers, etc...)
4753 *********************************************************************/
4754 static void serve(struct client_state *csp)
4756 int config_file_change_detected = 0; /* Only used for debugging */
4757 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4758 #ifdef FEATURE_CONNECTION_SHARING
4759 static int monitor_thread_running = 0;
4760 #endif /* def FEATURE_CONNECTION_SHARING */
4761 int continue_chatting = 0;
4763 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4764 csp->ip_addr_str, csp->cfd);
4768 unsigned int latency;
4770 #ifdef FEATURE_HTTPS_INSPECTION
4771 if (continue_chatting && client_use_ssl(csp))
4773 continue_https_chat(csp);
4782 * If the request has been crunched,
4783 * the calculated latency is zero.
4785 latency = (unsigned)(csp->server_connection.response_received -
4786 csp->server_connection.request_sent) / 2;
4788 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4789 && (csp->flags & CSP_FLAG_CRUNCHED)
4790 && (csp->expected_client_content_length != 0))
4792 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4793 log_error(LOG_LEVEL_CONNECT,
4794 "Tainting client socket %d due to unread data.", csp->cfd);
4797 continue_chatting = (csp->config->feature_flags
4798 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4799 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4800 && (csp->cfd != JB_INVALID_SOCKET)
4801 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4802 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4803 || (csp->flags & CSP_FLAG_CHUNKED));
4805 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4806 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4808 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4810 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4812 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4813 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4814 || !socket_is_still_alive(csp->server_connection.sfd)
4815 || !(latency < csp->server_connection.keep_alive_timeout))
4817 log_error(LOG_LEVEL_CONNECT,
4818 "Closing server socket %d connected to %s. "
4819 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4820 csp->server_connection.sfd, (csp->server_connection.host != NULL) ?
4821 csp->server_connection.host : csp->http->host,
4822 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4823 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4824 socket_is_still_alive(csp->server_connection.sfd),
4825 csp->server_connection.keep_alive_timeout);
4826 #ifdef FEATURE_CONNECTION_SHARING
4827 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4829 forget_connection(csp->server_connection.sfd);
4831 #endif /* def FEATURE_CONNECTION_SHARING */
4832 #ifdef FEATURE_HTTPS_INSPECTION
4833 close_server_ssl_connection(csp);
4835 close_socket(csp->server_connection.sfd);
4836 mark_connection_closed(&csp->server_connection);
4840 if (continue_chatting && any_loaded_file_changed(csp))
4842 continue_chatting = 0;
4843 config_file_change_detected = 1;
4845 #ifdef FEATURE_HTTPS_INSPECTION
4846 if (continue_chatting && client_use_ssl(csp) &&
4847 csp->ssl_with_client_is_opened == 0)
4849 continue_chatting = 0;
4850 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4851 "The TLS session has been terminated.", csp->cfd);
4855 if (continue_chatting)
4857 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4858 && socket_is_still_alive(csp->cfd))
4860 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4861 "pipelined on socket %d and the socket is still alive.",
4862 csp->requests_received_total+1, csp->cfd);
4863 prepare_csp_for_next_request(csp);
4867 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4869 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4871 log_error(LOG_LEVEL_CONNECT,
4872 "Waiting for the next client request on socket %d. "
4873 "Keeping the server socket %d to %s open.",
4874 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4878 log_error(LOG_LEVEL_CONNECT,
4879 "Waiting for the next client request on socket %d. "
4880 "No server socket to keep open.", csp->cfd);
4884 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4885 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4886 && socket_is_still_alive(csp->cfd))
4888 log_error(LOG_LEVEL_CONNECT,
4889 "Data arrived in time on client socket %d. Requests so far: %u",
4890 csp->cfd, csp->requests_received_total);
4891 prepare_csp_for_next_request(csp);
4895 #ifdef FEATURE_CONNECTION_SHARING
4896 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4897 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4898 && (socket_is_still_alive(csp->server_connection.sfd))
4899 #ifdef FEATURE_HTTPS_INSPECTION
4900 && !server_use_ssl(csp)
4904 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4906 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4911 remember_connection(&csp->server_connection);
4912 csp->server_connection.sfd = JB_INVALID_SOCKET;
4913 drain_and_close_socket(csp->cfd);
4914 csp->cfd = JB_INVALID_SOCKET;
4915 privoxy_mutex_lock(&connection_reuse_mutex);
4916 if (!monitor_thread_running)
4918 monitor_thread_running = 1;
4919 privoxy_mutex_unlock(&connection_reuse_mutex);
4920 wait_for_alive_connections();
4921 privoxy_mutex_lock(&connection_reuse_mutex);
4922 monitor_thread_running = 0;
4924 privoxy_mutex_unlock(&connection_reuse_mutex);
4926 #endif /* def FEATURE_CONNECTION_SHARING */
4930 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4932 log_error(LOG_LEVEL_CONNECT,
4933 "Closing server socket %d connected to %s. Keep-alive: %u. "
4934 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4935 "Configuration file change detected: %u",
4936 csp->server_connection.sfd, csp->server_connection.host,
4937 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4938 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4939 socket_is_still_alive(csp->server_connection.sfd),
4940 csp->server_connection.keep_alive_timeout,
4941 config_file_change_detected);
4943 } while (continue_chatting);
4947 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4949 if (csp->cfd != JB_INVALID_SOCKET)
4951 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4952 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4953 "Configuration file change detected: %u. Requests received: %u.",
4954 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4955 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4956 config_file_change_detected, csp->requests_received_total);
4957 #ifdef FEATURE_HTTPS_INSPECTION
4958 close_client_ssl_connection(csp);
4960 drain_and_close_socket(csp->cfd);
4963 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4965 #ifdef FEATURE_CONNECTION_SHARING
4966 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4968 forget_connection(csp->server_connection.sfd);
4970 #endif /* def FEATURE_CONNECTION_SHARING */
4972 #ifdef FEATURE_HTTPS_INSPECTION
4973 close_server_ssl_connection(csp);
4974 #endif /* def FEATURE_HTTPS_INSPECTION */
4976 close_socket(csp->server_connection.sfd);
4979 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4980 mark_connection_closed(&csp->server_connection);
4983 free_csp_resources(csp);
4985 csp->flags &= ~CSP_FLAG_ACTIVE;
4991 /*********************************************************************
4993 * Function : server_thread
4995 * Description : We only exist to call `serve' in a threaded environment.
4998 * 1 : data = Current client state (buffers, headers, etc...)
5000 * Returns : Always 0.
5002 *********************************************************************/
5003 static int32 server_thread(void *data)
5005 serve((struct client_state *) data);
5012 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5013 /*********************************************************************
5017 * Description : Print usage info & exit.
5019 * Parameters : Pointer to argv[0] for identifying ourselves
5023 *********************************************************************/
5024 static void usage(const char *name)
5026 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
5027 "Usage: %s [--config-test] "
5030 #endif /* defined(unix) */
5033 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
5034 #endif /* defined(unix) */
5035 "[--version] [configfile]\n",
5039 show_fuzz_usage(name);
5042 printf("Aborting\n");
5047 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5050 #ifdef MUTEX_LOCKS_AVAILABLE
5051 /*********************************************************************
5053 * Function : privoxy_mutex_lock
5055 * Description : Locks a mutex.
5058 * 1 : mutex = The mutex to lock.
5060 * Returns : Void. May exit in case of errors.
5062 *********************************************************************/
5063 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5065 #ifdef FEATURE_PTHREAD
5066 int err = pthread_mutex_lock(mutex);
5069 if (mutex != &log_mutex)
5071 log_error(LOG_LEVEL_FATAL,
5072 "Mutex locking failed: %s.\n", strerror(err));
5077 EnterCriticalSection(mutex);
5078 #endif /* def FEATURE_PTHREAD */
5082 /*********************************************************************
5084 * Function : privoxy_mutex_unlock
5086 * Description : Unlocks a mutex.
5089 * 1 : mutex = The mutex to unlock.
5091 * Returns : Void. May exit in case of errors.
5093 *********************************************************************/
5094 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5096 #ifdef FEATURE_PTHREAD
5097 int err = pthread_mutex_unlock(mutex);
5100 if (mutex != &log_mutex)
5102 log_error(LOG_LEVEL_FATAL,
5103 "Mutex unlocking failed: %s.\n", strerror(err));
5108 LeaveCriticalSection(mutex);
5109 #endif /* def FEATURE_PTHREAD */
5113 /*********************************************************************
5115 * Function : privoxy_mutex_init
5117 * Description : Prepares a mutex.
5120 * 1 : mutex = The mutex to initialize.
5122 * Returns : Void. May exit in case of errors.
5124 *********************************************************************/
5125 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5127 #ifdef FEATURE_PTHREAD
5128 int err = pthread_mutex_init(mutex, 0);
5131 printf("Fatal error. Mutex initialization failed: %s.\n",
5136 InitializeCriticalSection(mutex);
5137 #endif /* def FEATURE_PTHREAD */
5139 #endif /* def MUTEX_LOCKS_AVAILABLE */
5141 /*********************************************************************
5143 * Function : initialize_mutexes
5145 * Description : Prepares mutexes if mutex support is available.
5149 * Returns : Void, exits in case of errors.
5151 *********************************************************************/
5152 static void initialize_mutexes(void)
5154 #ifdef MUTEX_LOCKS_AVAILABLE
5156 * Prepare global mutex semaphores
5159 #ifdef FEATURE_HTTPS_INSPECTION
5160 privoxy_mutex_init(&certificate_mutex);
5161 privoxy_mutex_init(&ssl_init_mutex);
5164 privoxy_mutex_init(&log_mutex);
5165 privoxy_mutex_init(&log_init_mutex);
5166 privoxy_mutex_init(&connection_reuse_mutex);
5167 #ifdef FEATURE_EXTERNAL_FILTERS
5168 privoxy_mutex_init(&external_filter_mutex);
5170 #ifdef FEATURE_CLIENT_TAGS
5171 privoxy_mutex_init(&client_tags_mutex);
5173 #ifdef FEATURE_EXTENDED_STATISTICS
5174 privoxy_mutex_init(&filter_statistics_mutex);
5175 privoxy_mutex_init(&block_statistics_mutex);
5179 * XXX: The assumptions below are a bit naive
5180 * and can cause locks that aren't necessary.
5182 * For example older FreeBSD versions (< 6.x?)
5183 * have no gethostbyname_r, but gethostbyname is
5186 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5187 privoxy_mutex_init(&resolver_mutex);
5188 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5190 * XXX: should we use a single mutex for
5191 * localtime() and gmtime() as well?
5193 #ifndef HAVE_GMTIME_R
5194 privoxy_mutex_init(&gmtime_mutex);
5195 #endif /* ndef HAVE_GMTIME_R */
5197 #ifndef HAVE_LOCALTIME_R
5198 privoxy_mutex_init(&localtime_mutex);
5199 #endif /* ndef HAVE_GMTIME_R */
5201 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5202 privoxy_mutex_init(&rand_mutex);
5203 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5205 #endif /* def MUTEX_LOCKS_AVAILABLE */
5208 /*********************************************************************
5212 * Description : Load the config file and start the listen loop.
5213 * This function is a lot more *sane* with the `load_config'
5214 * and `listen_loop' functions; although it stills does
5215 * a *little* too much for my taste.
5218 * 1 : argc = Number of parameters (including $0).
5219 * 2 : argv = Array of (char *)'s to the parameters.
5221 * Returns : 1 if : can't open config file, unrecognized directive,
5222 * stats requested in multi-thread mode, can't open the
5223 * log file, can't open the jar file, listen port is invalid,
5224 * any load fails, and can't bind port.
5226 * Else main never returns, the process must be signaled
5227 * to terminate execution. Or, on Windows, use the
5228 * "File", "Exit" menu option.
5230 *********************************************************************/
5232 int real_main(int argc, char **argv)
5234 int main(int argc, char **argv)
5238 int do_config_test = 0;
5239 #ifndef HAVE_ARC4RANDOM
5240 unsigned int random_seed;
5243 struct passwd *pw = NULL;
5244 struct group *grp = NULL;
5246 char *pre_chroot_nslookup_to_load_resolver = NULL;
5249 char *fuzz_input_type = NULL;
5250 char *fuzz_input_file = NULL;
5257 #if !defined(_WIN32)
5264 /* Prepare mutexes if supported and necessary. */
5265 initialize_mutexes();
5267 /* Enable logging until further notice. */
5271 * Parse the command line arguments
5273 * XXX: simply printing usage information in case of
5274 * invalid arguments isn't particularly user friendly.
5276 while (++argc_pos < argc)
5279 /* Check to see if the service must be installed or uninstalled */
5280 if (strncmp(argv[argc_pos], "--install", 9) == 0)
5282 const char *pName = argv[argc_pos] + 9;
5285 exit((install_service(pName)) ? 0 : 1);
5287 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5289 const char *pName = argv[argc_pos] + 11;
5292 exit((uninstall_service(pName)) ? 0 : 1);
5294 else if (strcmp(argv[argc_pos], "--service") == 0)
5296 bRunAsService = TRUE;
5297 w32_set_service_cwd();
5298 atexit(w32_service_exit_notify);
5301 #endif /* defined(_WIN32) */
5304 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5306 if (strcmp(argv[argc_pos], "--help") == 0)
5311 else if (strcmp(argv[argc_pos], "--version") == 0)
5313 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5319 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5321 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5325 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5327 if (++argc_pos == argc) usage(argv[0]);
5328 pidfile = strdup_or_die(argv[argc_pos]);
5331 else if (strcmp(argv[argc_pos], "--user") == 0)
5336 if (++argc_pos == argc) usage(argv[argc_pos]);
5338 user_arg = strdup_or_die(argv[argc_pos]);
5339 group_name = strchr(user_arg, '.');
5340 if (NULL != group_name)
5342 /* Nul-terminate the user name */
5345 /* Skip the former delimiter to actually reach the group name */
5348 grp = getgrnam(group_name);
5351 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5354 pw = getpwnam(user_arg);
5357 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5363 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5365 if (++argc_pos == argc) usage(argv[0]);
5366 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5369 else if (strcmp(argv[argc_pos], "--chroot") == 0)
5373 #endif /* defined(unix) */
5375 else if (strcmp(argv[argc_pos], "--config-test") == 0)
5380 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5383 if (argc < argc_pos + 2) usage(argv[0]);
5384 fuzz_input_type = argv[argc_pos];
5386 fuzz_input_file = argv[argc_pos];
5388 else if (strcmp(argv[argc_pos], "--stfu") == 0)
5390 set_debug_level(LOG_LEVEL_STFU);
5393 else if (argc_pos + 1 != argc)
5396 * This is neither the last command line
5397 * option, nor was it recognized before,
5398 * therefore it must be invalid.
5404 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5406 configfile = argv[argc_pos];
5409 } /* -END- while (more arguments) */
5411 show_version(Argv[0]);
5414 if (*configfile != '/')
5416 char cwd[BUFFER_SIZE];
5418 size_t abs_file_size;
5420 /* make config-filename absolute here */
5421 if (NULL == getcwd(cwd, sizeof(cwd)))
5423 perror("failed to get current working directory");
5427 basedir = strdup_or_die(cwd);
5429 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5430 abs_file = malloc_or_die(abs_file_size);
5431 strlcpy(abs_file, basedir, abs_file_size);
5432 strlcat(abs_file, "/", abs_file_size);
5433 strlcat(abs_file, configfile, abs_file_size);
5434 configfile = abs_file;
5436 #endif /* defined unix */
5440 clients->next = NULL;
5442 /* XXX: factor out initialising after the next stable release. */
5447 #ifndef HAVE_ARC4RANDOM
5448 random_seed = (unsigned int)time(NULL);
5450 srandom(random_seed);
5453 #endif /* ifdef HAVE_RANDOM */
5454 #endif /* ifndef HAVE_ARC4RANDOM */
5457 * Unix signal handling
5459 * Catch the abort, interrupt and terminate signals for a graceful exit
5460 * Catch the hangup signal so the errlog can be reopened.
5462 * Ignore the broken pipe signal as connection failures
5463 * are handled when and where they occur without relying
5466 #if !defined(_WIN32)
5469 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5471 for (idx = 0; idx < SZ(catched_signals); idx++)
5473 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5474 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5476 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5477 #endif /* ifdef sun */
5479 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5483 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5485 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5489 #else /* ifdef _WIN32 */
5490 # ifdef _WIN_CONSOLE
5492 * We *are* in a windows console app.
5493 * Print a verbose messages about FAQ's and such
5495 printf("%s", win32_blurb);
5496 # endif /* def _WIN_CONSOLE */
5497 #endif /* def _WIN32 */
5500 if (fuzz_input_type != NULL)
5502 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5504 log_error(LOG_LEVEL_FATAL,
5505 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5506 "Various data structures are static which is unsafe when using threads.");
5511 exit(NULL == load_config());
5514 /* Initialize the CGI subsystem */
5515 cgi_init_error_messages();
5518 * If running on unix and without the --no-daemon
5519 * option, become a daemon. I.e. fork, detach
5520 * from tty and get process group leadership
5529 if (pid < 0) /* error */
5534 else if (pid != 0) /* parent */
5539 * must check for errors
5540 * child died due to missing files aso
5543 wpid = waitpid(pid, &status, WNOHANG);
5555 * stderr (fd 2) will be closed later on,
5556 * when the config file has been parsed.
5562 * Reserve fd 0 and 1 to prevent abort() and friends
5563 * from sending stuff to the clients or servers.
5565 fd = open("/dev/null", O_RDONLY);
5568 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5572 if (dup2(fd, 0) == -1)
5574 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5578 fd = open("/dev/null", O_WRONLY);
5581 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5585 if (dup2(fd, 1) == -1)
5587 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5592 #ifdef FEATURE_EXTERNAL_FILTERS
5593 for (fd = 0; fd < 3; fd++)
5595 mark_socket_for_close_on_execute(fd);
5599 if (chdir("/") != 0)
5601 log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5604 } /* -END- if (daemon_mode) */
5607 * As soon as we have written the PID file, we can switch
5608 * to the user and group ID indicated by the --user option
5610 if (pidfile != NULL)
5612 write_pid_file(pidfile);
5616 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5618 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5622 if (setgroups(1, &grp->gr_gid))
5624 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5627 else if (initgroups(pw->pw_name, pw->pw_gid))
5629 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5635 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5637 /* Read the time zone file from /etc before doing chroot. */
5639 if (NULL != pre_chroot_nslookup_to_load_resolver
5640 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5642 /* Initialize resolver library. */
5643 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5645 if (chroot(pw->pw_dir) < 0)
5647 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5651 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5654 if (setuid(pw->pw_uid))
5656 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5660 char putenv_dummy[64];
5662 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5663 if (putenv(putenv_dummy) != 0)
5665 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5668 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5669 if (putenv(putenv_dummy) != 0)
5671 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5677 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5680 #endif /* defined unix */
5683 /* This will be FALSE unless the command line specified --service
5687 /* Yup, so now we must attempt to establish a connection
5688 * with the service dispatcher. This will only work if this
5689 * process was launched by the service control manager to
5690 * actually run as a service. If this isn't the case, i've
5691 * known it take around 30 seconds or so for the call to return.
5694 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5695 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5697 /* Service has run, and at this point is now being stopped, so just return */
5702 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5704 /* An error occurred. Usually it's because --service was wrongly specified
5705 * and we were unable to connect to the Service Control Dispatcher because
5706 * it wasn't expecting us and is therefore not listening.
5708 * For now, just continue below to call the listen_loop function.
5711 #endif /* def _WIN32 */
5721 /*********************************************************************
5723 * Function : bind_port_helper
5725 * Description : Bind the listen port. Handles logging, and aborts
5729 * 1 : haddr = Host address to bind to. Use NULL to bind to
5731 * 2 : hport = Specifies port to bind to.
5732 * 3 : backlog = Listen backlog.
5734 * Returns : Port that was opened.
5736 *********************************************************************/
5737 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5742 result = bind_port(haddr, hport, backlog, &bfd);
5746 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5750 log_error(LOG_LEVEL_FATAL,
5751 "can't bind to %s:%d: There may be another Privoxy "
5752 "or some other proxy running on port %d",
5753 bind_address, hport, hport);
5756 log_error(LOG_LEVEL_FATAL,
5757 "can't bind to %s:%d: The hostname is not resolvable",
5758 bind_address, hport);
5761 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5762 bind_address, hport);
5765 /* shouldn't get here */
5766 return JB_INVALID_SOCKET;
5771 if (bfd >= FD_SETSIZE)
5773 log_error(LOG_LEVEL_FATAL,
5774 "Bind socket number too high to use select(): %d >= %d",
5782 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5787 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5795 /*********************************************************************
5797 * Function : bind_ports_helper
5799 * Description : Bind the listen ports. Handles logging, and aborts
5803 * 1 : config = Privoxy configuration. Specifies ports
5805 * 2 : sockets = Preallocated array of opened sockets
5806 * corresponding to specification in config.
5807 * All non-opened sockets will be set to
5808 * JB_INVALID_SOCKET.
5810 * Returns : Nothing. Inspect sockets argument.
5812 *********************************************************************/
5813 static void bind_ports_helper(struct configuration_spec * config,
5814 jb_socket sockets[])
5818 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5820 if (config->hport[i])
5822 sockets[i] = bind_port_helper(config->haddr[i],
5823 config->hport[i], config->listen_backlog);
5824 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5825 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5827 struct accept_filter_arg af_options;
5828 bzero(&af_options, sizeof(af_options));
5829 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5830 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5831 sizeof(af_options)))
5833 log_error(LOG_LEVEL_ERROR,
5834 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5841 sockets[i] = JB_INVALID_SOCKET;
5844 config->need_bind = 0;
5848 /*********************************************************************
5850 * Function : close_ports_helper
5852 * Description : Close listenings ports.
5855 * 1 : sockets = Array of opened and non-opened sockets to
5856 * close. All sockets will be set to
5857 * JB_INVALID_SOCKET.
5859 * Returns : Nothing.
5861 *********************************************************************/
5862 static void close_ports_helper(jb_socket sockets[])
5866 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5868 if (JB_INVALID_SOCKET != sockets[i])
5870 close_socket(sockets[i]);
5872 sockets[i] = JB_INVALID_SOCKET;
5878 /* Without this simple workaround we get this compiler warning from _beginthread
5879 * warning C4028: formal parameter 1 different from declaration
5881 void w32_service_listen_loop(void *p)
5885 #endif /* def _WIN32 */
5888 /*********************************************************************
5890 * Function : listen_loop
5892 * Description : bind the listen port and enter a "FOREVER" listening loop.
5898 *********************************************************************/
5899 static void listen_loop(void)
5901 struct client_states *csp_list = NULL;
5902 struct client_state *csp = NULL;
5903 jb_socket bfds[MAX_LISTENING_SOCKETS];
5904 struct configuration_spec *config;
5905 unsigned int active_threads = 0;
5906 #if defined(FEATURE_PTHREAD)
5907 pthread_attr_t attrs;
5909 pthread_attr_init(&attrs);
5910 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5913 config = load_config();
5915 #ifdef FEATURE_CONNECTION_SHARING
5917 * XXX: Should be relocated once it no
5918 * longer needs to emit log messages.
5920 initialize_reusable_connections();
5921 #endif /* def FEATURE_CONNECTION_SHARING */
5923 bind_ports_helper(config, bfds);
5925 #ifdef FEATURE_GRACEFUL_TERMINATION
5926 while (!g_terminate)
5931 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
5932 while (waitpid(-1, NULL, WNOHANG) > 0)
5934 /* zombie children */
5936 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5939 * Free data that was used by died threads
5941 active_threads = sweep();
5945 * Re-open the errlog after HUP signal
5947 if (received_hup_signal)
5949 if (NULL != config->logfile)
5951 init_error_log(Argv[0], config->logfile);
5953 received_hup_signal = 0;
5957 csp_list = zalloc_or_die(sizeof(*csp_list));
5958 csp = &csp_list->csp;
5960 log_error(LOG_LEVEL_CONNECT,
5961 "Waiting for the next client connection. Currently active threads: %u",
5965 * This config may be outdated, but for accept_connection()
5966 * it's fresh enough.
5968 csp->config = config;
5970 if (!accept_connection(csp, bfds))
5972 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5977 csp->flags |= CSP_FLAG_ACTIVE;
5978 csp->server_connection.sfd = JB_INVALID_SOCKET;
5980 csp->config = config = load_config();
5982 if (config->need_bind)
5985 * Since we were listening to the "old port", we will not see
5986 * a "listen" param change until the next request. So, at
5987 * least 1 more request must be made for us to find the new
5988 * setting. I am simply closing the old socket and binding the
5991 * Which-ever is correct, we will serve 1 more page via the
5992 * old settings. This should probably be a "show-status"
5993 * request. This should not be a so common of an operation
5994 * that this will hurt people's feelings.
5997 close_ports_helper(bfds);
5999 bind_ports_helper(config, bfds);
6002 #ifdef FEATURE_TOGGLE
6003 if (global_toggle_state)
6004 #endif /* def FEATURE_TOGGLE */
6006 csp->flags |= CSP_FLAG_TOGGLED_ON;
6009 if (run_loader(csp))
6011 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
6012 /* Never get here - LOG_LEVEL_FATAL causes program exit */
6016 if (block_acl(NULL,csp))
6018 log_error(LOG_LEVEL_CONNECT,
6019 "Connection from %s on %s (socket %d) dropped due to ACL",
6020 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
6021 close_socket(csp->cfd);
6022 freez(csp->ip_addr_str);
6023 freez(csp->listen_addr_str);
6027 #endif /* def FEATURE_ACL */
6029 if ((0 != config->max_client_connections)
6030 && (active_threads >= config->max_client_connections))
6032 log_error(LOG_LEVEL_CONNECT,
6033 "Rejecting connection from %s. Maximum number of connections reached.",
6035 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6036 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6037 close_socket(csp->cfd);
6038 freez(csp->ip_addr_str);
6039 freez(csp->listen_addr_str);
6044 /* add it to the list of clients */
6045 csp_list->next = clients->next;
6046 clients->next = csp_list;
6048 if (config->multi_threaded)
6052 /* this is a switch () statement in the C preprocessor - ugh */
6053 #undef SELECTED_ONE_OPTION
6055 /* Use Pthreads in preference to native code */
6056 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6057 #define SELECTED_ONE_OPTION
6059 pthread_t the_thread;
6062 ret = pthread_create(&the_thread, &attrs,
6063 (void * (*)(void *))serve, csp);
6064 child_id = ret ? -1 : 0;
6068 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
6069 #define SELECTED_ONE_OPTION
6070 child_id = _beginthread(
6071 (void (*)(void *))serve,
6076 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6077 #define SELECTED_ONE_OPTION
6079 thread_id tid = spawn_thread
6080 (server_thread, "server", B_NORMAL_PRIORITY, csp);
6082 if ((tid >= 0) && (resume_thread(tid) == B_OK))
6084 child_id = (int) tid;
6093 #if !defined(SELECTED_ONE_OPTION)
6096 /* This block is only needed when using fork().
6097 * When using threads, the server thread was
6098 * created and run by the call to _beginthread().
6100 if (child_id == 0) /* child */
6103 #ifdef FEATURE_TOGGLE
6104 int inherited_toggle_state = global_toggle_state;
6105 #endif /* def FEATURE_TOGGLE */
6110 * If we've been toggled or we've blocked the request, tell Mom
6113 #ifdef FEATURE_TOGGLE
6114 if (inherited_toggle_state != global_toggle_state)
6116 rc |= RC_FLAG_TOGGLED;
6118 #endif /* def FEATURE_TOGGLE */
6120 #ifdef FEATURE_STATISTICS
6121 if (csp->flags & CSP_FLAG_REJECTED)
6123 rc |= RC_FLAG_BLOCKED;
6125 #endif /* ndef FEATURE_STATISTICS */
6129 else if (child_id > 0) /* parent */
6131 /* in a fork()'d environment, the parent's
6132 * copy of the client socket and the CSP
6136 #if !defined(_WIN32) && !defined(__CYGWIN__)
6138 wait(&child_status);
6141 * Evaluate child's return code: If the child has
6142 * - been toggled, toggle ourselves
6143 * - blocked its request, bump up the stats counter
6146 #ifdef FEATURE_TOGGLE
6147 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6149 global_toggle_state = !global_toggle_state;
6151 #endif /* def FEATURE_TOGGLE */
6153 #ifdef FEATURE_STATISTICS
6155 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6159 #endif /* def FEATURE_STATISTICS */
6161 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6162 close_socket(csp->cfd);
6163 csp->flags &= ~CSP_FLAG_ACTIVE;
6167 #undef SELECTED_ONE_OPTION
6168 /* end of cpp switch () */
6173 * Spawning the child failed, assume it's because
6174 * there are too many children running already.
6175 * XXX: If you assume ...
6177 log_error(LOG_LEVEL_ERROR,
6178 "Unable to take any additional connections: %E. Active threads: %u",
6180 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6181 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6182 close_socket(csp->cfd);
6183 csp->flags &= ~CSP_FLAG_ACTIVE;
6192 #if defined(FEATURE_PTHREAD)
6193 pthread_attr_destroy(&attrs);
6196 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6198 #ifdef FEATURE_GRACEFUL_TERMINATION
6200 log_error(LOG_LEVEL_INFO, "Graceful termination requested.");
6202 unload_current_config_file();
6203 unload_current_actions_file();
6204 unload_current_re_filterfile();
6205 #ifdef FEATURE_TRUST
6206 unload_current_trust_file();
6209 if (config->multi_threaded)
6216 } while ((clients->next != NULL) && (--i > 0));
6220 log_error(LOG_LEVEL_ERROR, "Graceful termination failed "
6221 "- still some live clients after 1 minute wait.");
6231 #ifdef FEATURE_HTTPS_INSPECTION
6233 * Only release TLS backed resources if there
6234 * are no active connections left.
6236 if (clients->next == NULL)
6242 log_error(LOG_LEVEL_INFO, "Exiting gracefully.");
6244 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6245 /* Cleanup - remove taskbar icon etc. */
6250 #endif /* FEATURE_GRACEFUL_TERMINATION */