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 #ifdef FEATURE_HTTPS_INSPECTION
999 if (fwd != NULL && fwd->forward_host &&
1000 fwd->type != FORWARD_WEBSERVER && client_use_ssl(csp))
1002 *request_line = strdup("CONNECT ");
1007 *request_line = strdup(http->gpc);
1008 string_append(request_line, " ");
1011 if (fwd != NULL && fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1013 #ifdef FEATURE_HTTPS_INSPECTION
1014 if (client_use_ssl(csp))
1016 char port_string[10];
1018 string_append(request_line, http->host);
1019 snprintf(port_string, sizeof(port_string), ":%d", http->port);
1020 string_append(request_line, port_string);
1025 string_append(request_line, http->url);
1030 string_append(request_line, http->path);
1032 string_append(request_line, " ");
1033 string_append(request_line, http->version);
1035 if (*request_line == NULL)
1037 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1039 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1043 /*********************************************************************
1045 * Function : change_request_destination
1047 * Description : Parse a (rewritten) request line and regenerate
1048 * the http request data.
1051 * 1 : csp = Current client state (buffers, headers, etc...)
1053 * Returns : Forwards the parse_http_request() return code.
1054 * Terminates in case of memory problems.
1056 *********************************************************************/
1057 static jb_err change_request_destination(struct client_state *csp)
1059 struct http_request *http = csp->http;
1062 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1063 csp->headers->first->str);
1064 free_http_request(http);
1065 err = parse_http_request(csp->headers->first->str, http);
1066 if (JB_ERR_OK != err)
1068 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1069 jb_err_to_string(err));
1071 if (http->ssl && strcmpic(csp->http->gpc, "CONNECT"))
1074 * A client header filter changed the request URL from
1075 * http:// to https:// which we currently don't support.
1077 log_error(LOG_LEVEL_ERROR, "Changing the request destination from http "
1078 "to https behind the client's back currently isn't supported.");
1079 return JB_ERR_PARSE;
1086 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1087 /*********************************************************************
1089 * Function : server_response_is_complete
1091 * Description : Determines whether we should stop reading
1092 * from the server socket.
1095 * 1 : csp = Current client state (buffers, headers, etc...)
1096 * 2 : content_length = Length of content received so far.
1098 * Returns : TRUE if the response is complete,
1101 *********************************************************************/
1102 static int server_response_is_complete(struct client_state *csp,
1103 unsigned long long content_length)
1105 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1107 if (!strcmpic(csp->http->gpc, "HEAD"))
1110 * "HEAD" implies no body, we are thus expecting
1111 * no content. XXX: incomplete "list" of methods?
1113 csp->expected_content_length = 0;
1114 content_length_known = TRUE;
1115 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1118 if (csp->http->status == 204 || csp->http->status == 304)
1121 * Expect no body. XXX: incomplete "list" of status codes?
1123 csp->expected_content_length = 0;
1124 content_length_known = TRUE;
1125 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1128 return (content_length_known && ((0 == csp->expected_content_length)
1129 || (csp->expected_content_length <= content_length)));
1133 #ifdef FEATURE_CONNECTION_SHARING
1134 /*********************************************************************
1136 * Function : wait_for_alive_connections
1138 * Description : Waits for alive connections to timeout.
1144 *********************************************************************/
1145 static void wait_for_alive_connections(void)
1147 int connections_alive = close_unusable_connections();
1149 while (0 < connections_alive)
1151 log_error(LOG_LEVEL_CONNECT,
1152 "Waiting for %d connections to timeout.",
1155 connections_alive = close_unusable_connections();
1158 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1161 #endif /* def FEATURE_CONNECTION_SHARING */
1164 /*********************************************************************
1166 * Function : save_connection_destination
1168 * Description : Remembers a connection for reuse later on.
1171 * 1 : sfd = Open socket to remember.
1172 * 2 : http = The destination for the connection.
1173 * 3 : fwd = The forwarder settings used.
1174 * 4 : server_connection = storage.
1178 *********************************************************************/
1179 static void save_connection_destination(jb_socket sfd,
1180 const struct http_request *http,
1181 const struct forward_spec *fwd,
1182 struct reusable_connection *server_connection)
1184 assert(sfd != JB_INVALID_SOCKET);
1185 assert(NULL != http->host);
1187 server_connection->sfd = sfd;
1188 server_connection->host = strdup_or_die(http->host);
1189 server_connection->port = http->port;
1191 assert(NULL != fwd);
1192 assert(server_connection->gateway_host == NULL);
1193 assert(server_connection->gateway_port == 0);
1194 assert(server_connection->forwarder_type == 0);
1195 assert(server_connection->forward_host == NULL);
1196 assert(server_connection->forward_port == 0);
1198 server_connection->forwarder_type = fwd->type;
1199 if (NULL != fwd->gateway_host)
1201 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1205 server_connection->gateway_host = NULL;
1207 server_connection->gateway_port = fwd->gateway_port;
1208 if (NULL != fwd->auth_username)
1210 server_connection->auth_username = strdup_or_die(fwd->auth_username);
1214 server_connection->auth_username = NULL;
1216 if (NULL != fwd->auth_password)
1218 server_connection->auth_password = strdup_or_die(fwd->auth_password);
1222 server_connection->auth_password = NULL;
1225 if (NULL != fwd->forward_host)
1227 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1231 server_connection->forward_host = NULL;
1233 server_connection->forward_port = fwd->forward_port;
1235 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1238 /*********************************************************************
1240 * Function : verify_request_length
1242 * Description : Checks if we already got the whole client requests
1243 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1246 * Data that doesn't belong to the current request is
1247 * either thrown away to let the client retry on a clean
1248 * socket, or stashed to be dealt with after the current
1249 * request is served.
1252 * 1 : csp = Current client state (buffers, headers, etc...)
1256 *********************************************************************/
1257 static void verify_request_length(struct client_state *csp)
1259 unsigned long long buffered_request_bytes =
1260 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1262 if ((csp->expected_client_content_length != 0)
1263 && (buffered_request_bytes != 0))
1265 if (csp->expected_client_content_length >= buffered_request_bytes)
1267 csp->expected_client_content_length -= buffered_request_bytes;
1268 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1269 "to account for the %llu ones we already got.",
1270 csp->expected_client_content_length, buffered_request_bytes);
1274 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1275 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1276 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1277 "Marking the server socket tainted after throwing %llu bytes away.",
1278 buffered_request_bytes - csp->expected_client_content_length);
1279 csp->expected_client_content_length = 0;
1280 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1283 if (csp->expected_client_content_length == 0)
1285 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1289 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1290 && ((csp->client_iob->cur < csp->client_iob->eod)
1291 || (csp->expected_client_content_length != 0)))
1293 if (strcmpic(csp->http->gpc, "GET")
1294 && strcmpic(csp->http->gpc, "HEAD")
1295 && strcmpic(csp->http->gpc, "TRACE")
1296 && strcmpic(csp->http->gpc, "OPTIONS")
1297 && strcmpic(csp->http->gpc, "DELETE"))
1299 /* XXX: this is an incomplete hack */
1300 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1301 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1305 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1307 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1309 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1310 log_error(LOG_LEVEL_CONNECT,
1311 "Possible pipeline attempt detected. The connection will not "
1312 "be kept alive and we will only serve the first request.");
1313 /* Nuke the pipelined requests from orbit, just to be sure. */
1314 clear_iob(csp->client_iob);
1319 * Keep the pipelined data around for now, we'll deal with
1320 * it once we're done serving the current request.
1322 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1323 assert(csp->client_iob->eod >= csp->client_iob->cur);
1324 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1325 "%d bytes of pipelined data received.",
1326 (int)(csp->client_iob->eod - csp->client_iob->cur));
1332 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1333 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1338 /*********************************************************************
1340 * Function : mark_server_socket_tainted
1342 * Description : Makes sure we don't reuse a server socket
1343 * (if we didn't read everything the server sent
1344 * us reusing the socket would lead to garbage).
1347 * 1 : csp = Current client state (buffers, headers, etc...)
1351 *********************************************************************/
1352 static void mark_server_socket_tainted(struct client_state *csp)
1355 * For consistency we always mark the server socket
1356 * tainted, however, to reduce the log noise we only
1357 * emit a log message if the server socket could have
1358 * actually been reused.
1360 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1361 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1363 log_error(LOG_LEVEL_CONNECT,
1364 "Marking the server socket %d tainted.",
1365 csp->server_connection.sfd);
1367 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1370 /*********************************************************************
1372 * Function : get_request_line
1374 * Description : Read the client request line.
1377 * 1 : csp = Current client state (buffers, headers, etc...)
1379 * Returns : Pointer to request line or NULL in case of errors.
1381 *********************************************************************/
1382 static char *get_request_line(struct client_state *csp)
1384 char buf[BUFFER_SIZE];
1385 char *request_line = NULL;
1388 memset(buf, 0, sizeof(buf));
1390 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1393 * If there are multiple pipelined requests waiting,
1394 * the flag will be set again once the next request
1397 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1399 request_line = get_header(csp->client_iob);
1400 if ((NULL != request_line) && ('\0' != *request_line))
1402 return request_line;
1406 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1407 "received yet. Continuing reading from %d.", csp->cfd);
1415 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1417 !data_is_available(csp->cfd, csp->config->socket_timeout)
1420 if (socket_is_still_alive(csp->cfd))
1422 log_error(LOG_LEVEL_CONNECT,
1423 "No request line on socket %d received in time. Timeout: %d.",
1424 csp->cfd, csp->config->socket_timeout);
1425 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1426 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1427 get_write_delay(csp));
1431 log_error(LOG_LEVEL_CONNECT,
1432 "The client side of the connection on socket %d got "
1433 "closed without sending a complete request line.", csp->cfd);
1438 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1440 if (len <= 0) return NULL;
1443 * If there is no memory left for buffering the
1444 * request, there is nothing we can do but hang up
1446 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1451 request_line = get_header(csp->client_iob);
1453 } while ((NULL != request_line) && ('\0' == *request_line));
1455 return request_line;
1461 CHUNK_STATUS_MISSING_DATA,
1462 CHUNK_STATUS_BODY_COMPLETE,
1463 CHUNK_STATUS_PARSE_ERROR
1467 /*********************************************************************
1469 * Function : chunked_body_is_complete
1471 * Description : Figures out whether or not a chunked body is complete.
1473 * Currently it always starts at the beginning of the
1474 * buffer which is somewhat wasteful and prevents Privoxy
1475 * from starting to forward the correctly parsed chunks
1476 * as soon as theoretically possible.
1478 * Should be modified to work with a common buffer,
1479 * and allow the caller to skip already parsed chunks.
1481 * This would allow the function to be used for unbuffered
1482 * response bodies as well.
1485 * 1 : iob = Buffer with the body to check.
1486 * 2 : length = Length of complete body
1488 * Returns : Enum with the result of the check.
1490 *********************************************************************/
1491 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1493 unsigned int chunksize;
1499 * We need at least a single digit, followed by "\r\n",
1500 * followed by an unknown amount of data, followed by "\r\n".
1502 if (p + 5 > iob->eod)
1504 return CHUNK_STATUS_MISSING_DATA;
1506 if (sscanf(p, "%x", &chunksize) != 1)
1508 return CHUNK_STATUS_PARSE_ERROR;
1512 * We want at least a single digit, followed by "\r\n",
1513 * followed by the specified amount of data, followed by "\r\n".
1515 if (p + chunksize + 5 > iob->eod)
1517 return CHUNK_STATUS_MISSING_DATA;
1520 /* Skip chunk-size. */
1521 p = strstr(p, "\r\n");
1524 return CHUNK_STATUS_PARSE_ERROR;
1526 /* Move beyond the chunkdata. */
1529 /* Make sure we're still within the buffer and have two bytes left */
1530 if (p + 2 > iob->eod)
1532 return CHUNK_STATUS_MISSING_DATA;
1535 /* There should be another "\r\n" to skip */
1536 if (memcmp(p, "\r\n", 2))
1538 return CHUNK_STATUS_PARSE_ERROR;
1541 } while (chunksize > 0U);
1543 *length = (size_t)(p - iob->cur);
1544 assert(*length <= (size_t)(iob->eod - iob->cur));
1545 assert(p <= iob->eod);
1547 return CHUNK_STATUS_BODY_COMPLETE;
1552 /*********************************************************************
1554 * Function : receive_chunked_client_request_body
1556 * Description : Read the chunk-encoded client request body.
1557 * Failures are dealt with.
1560 * 1 : csp = Current client state (buffers, headers, etc...)
1562 * Returns : JB_ERR_OK or JB_ERR_PARSE
1564 *********************************************************************/
1565 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1568 enum chunk_status status;
1570 while (CHUNK_STATUS_MISSING_DATA ==
1571 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1573 char buf[BUFFER_SIZE];
1576 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1578 log_error(LOG_LEVEL_ERROR,
1579 "Timeout while waiting for the client body.");
1582 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1585 log_error(LOG_LEVEL_ERROR,
1586 "Reading the client body failed: %E");
1589 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1594 if (status != CHUNK_STATUS_BODY_COMPLETE)
1596 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1597 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1598 log_error(LOG_LEVEL_CLF,
1599 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1600 return JB_ERR_PARSE;
1602 log_error(LOG_LEVEL_CONNECT,
1603 "Chunked client body completely read. Length: %lu", body_length);
1604 csp->expected_client_content_length = body_length;
1612 /*********************************************************************
1614 * Function : fuzz_chunked_transfer_encoding
1616 * Description : Treat the fuzzed input as chunked transfer encoding
1617 * to check and dechunk.
1620 * 1 : csp = Used to store the data.
1621 * 2 : fuzz_input_file = File to read the input from.
1623 * Returns : Result of dechunking
1625 *********************************************************************/
1626 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1629 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1630 enum chunk_status status;
1632 status = chunked_body_is_complete(csp->iob, &length);
1633 if (CHUNK_STATUS_BODY_COMPLETE != status)
1635 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1638 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1643 /*********************************************************************
1645 * Function : fuzz_client_request
1647 * Description : Try to get a client request from the fuzzed input.
1650 * 1 : csp = Current client state (buffers, headers, etc...)
1651 * 2 : fuzz_input_file = File to read the input from.
1653 * Returns : Result of fuzzing.
1655 *********************************************************************/
1656 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1661 csp->ip_addr_str = "fuzzer";
1663 if (strcmp(fuzz_input_file, "-") != 0)
1665 log_error(LOG_LEVEL_FATAL,
1666 "Fuzzed client requests can currently only be read from stdin (-).");
1668 err = receive_client_request(csp);
1669 if (err != JB_ERR_OK)
1673 err = parse_client_request(csp);
1674 if (err != JB_ERR_OK)
1682 #endif /* def FUZZ */
1685 #ifdef FEATURE_FORCE_LOAD
1686 /*********************************************************************
1688 * Function : force_required
1690 * Description : Checks a request line to see if it contains
1691 * the FORCE_PREFIX. If it does, it is removed
1692 * unless enforcing requests has beend disabled.
1695 * 1 : request_line = HTTP request line
1697 * Returns : TRUE if force is required, FALSE otherwise.
1699 *********************************************************************/
1700 static int force_required(const struct client_state *csp, char *request_line)
1704 p = strstr(request_line, "http://");
1708 p += strlen("http://");
1712 /* Intercepted request usually don't specify the protocol. */
1716 /* Go to the beginning of the path */
1721 * If the path is missing the request line is invalid and we
1722 * are done here. The client-visible rejection happens later on.
1727 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1729 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1731 /* XXX: Should clean more carefully */
1732 strclean(request_line, FORCE_PREFIX);
1733 log_error(LOG_LEVEL_FORCE,
1734 "Enforcing request: \"%s\".", request_line);
1738 log_error(LOG_LEVEL_FORCE,
1739 "Ignored force prefix in request: \"%s\".", request_line);
1745 #endif /* def FEATURE_FORCE_LOAD */
1748 /*********************************************************************
1750 * Function : receive_client_request
1752 * Description : Read the client's request (more precisely the
1753 * client headers) and answer it if necessary.
1756 * 1 : csp = Current client state (buffers, headers, etc...)
1758 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1760 *********************************************************************/
1761 static jb_err receive_client_request(struct client_state *csp)
1763 char buf[BUFFER_SIZE];
1766 struct http_request *http;
1770 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1771 struct list header_list;
1772 struct list *headers = &header_list;
1774 /* We don't care if the arriving data is a valid HTTP request or not. */
1775 csp->requests_received_total++;
1779 memset(buf, 0, sizeof(buf));
1781 req = get_request_line(csp);
1784 mark_server_socket_tainted(csp);
1785 return JB_ERR_PARSE;
1787 assert(*req != '\0');
1789 if (client_protocol_is_unsupported(csp, req))
1791 return JB_ERR_PARSE;
1794 #ifdef FEATURE_FORCE_LOAD
1795 if (force_required(csp, req))
1797 csp->flags |= CSP_FLAG_FORCED;
1799 #endif /* def FEATURE_FORCE_LOAD */
1801 err = parse_http_request(req, http);
1803 if (JB_ERR_OK != err)
1805 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1806 get_write_delay(csp));
1807 /* XXX: Use correct size */
1808 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1809 log_error(LOG_LEVEL_ERROR,
1810 "Couldn't parse request line received from %s: %s",
1811 csp->ip_addr_str, jb_err_to_string(err));
1813 free_http_request(http);
1814 return JB_ERR_PARSE;
1817 /* grab the rest of the client's headers */
1821 p = get_header(csp->client_iob);
1825 /* There are no additional headers to read. */
1832 * We didn't receive a complete header
1833 * line yet, get the rest of it.
1835 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1837 log_error(LOG_LEVEL_ERROR,
1838 "Stopped grabbing the client headers.");
1839 destroy_list(headers);
1840 return JB_ERR_PARSE;
1843 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1846 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1847 destroy_list(headers);
1848 return JB_ERR_PARSE;
1851 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1854 * If there is no memory left for buffering the
1855 * request, there is nothing we can do but hang up
1857 destroy_list(headers);
1858 return JB_ERR_MEMORY;
1863 if (!strncmpic(p, "Transfer-Encoding:", 18))
1866 * XXX: should be called through sed()
1867 * but currently can't.
1869 client_transfer_encoding(csp, &p);
1872 * We were able to read a complete
1873 * header and can finally enlist it.
1880 if (http->host == NULL)
1883 * If we still don't know the request destination,
1884 * the request is invalid or the client uses
1885 * Privoxy without its knowledge.
1887 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1890 * Our attempts to get the request destination
1891 * elsewhere failed or Privoxy is configured
1892 * to only accept proxy requests.
1894 * An error response has already been sent
1895 * and we're done here.
1897 return JB_ERR_PARSE;
1901 #ifdef FEATURE_CLIENT_TAGS
1902 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1903 set_client_address(csp, headers);
1904 get_tag_list_for_client(csp->client_tags, csp->client_address);
1908 * Determine the actions for this URL
1910 #ifdef FEATURE_TOGGLE
1911 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1913 /* Most compatible set of actions (i.e. none) */
1914 init_current_action(csp->action);
1917 #endif /* ndef FEATURE_TOGGLE */
1919 get_url_actions(csp, http);
1922 enlist(csp->headers, http->cmd);
1924 /* Append the previously read headers */
1925 err = list_append_list_unique(csp->headers, headers);
1926 destroy_list(headers);
1933 /*********************************************************************
1935 * Function : parse_client_request
1937 * Description : Parses the client's request and decides what to do
1940 * Note that since we're not using select() we could get
1941 * blocked here if a client connected, then didn't say
1945 * 1 : csp = Current client state (buffers, headers, etc...)
1947 * Returns : JB_ERR_OK or JB_ERR_PARSE
1949 *********************************************************************/
1950 static jb_err parse_client_request(struct client_state *csp)
1952 struct http_request *http = csp->http;
1955 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1956 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1957 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1958 && (csp->http->ssl == 0))
1960 /* Assume persistence until further notice */
1961 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1963 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1965 if (csp->http->ssl == 0)
1968 * This whole block belongs to chat() but currently
1969 * has to be executed before sed().
1971 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1973 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1975 return JB_ERR_PARSE;
1980 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1982 verify_request_length(csp);
1984 #ifndef FEATURE_HTTPS_INSPECTION
1987 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1991 err = sed(csp, FILTER_CLIENT_HEADERS);
1992 if (JB_ERR_OK != err)
1994 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1996 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1997 csp->ip_addr_str, csp->http->cmd);
1998 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1999 return JB_ERR_PARSE;
2001 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
2003 /* Check request line for rewrites. */
2004 if ((NULL == csp->headers->first->str)
2005 || (strcmp(http->cmd, csp->headers->first->str) &&
2006 (JB_ERR_OK != change_request_destination(csp))))
2009 * A header filter broke the request line - bail out.
2011 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
2012 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2013 /* XXX: Use correct size */
2014 log_error(LOG_LEVEL_CLF,
2015 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2016 log_error(LOG_LEVEL_ERROR,
2017 "Invalid request line after applying header filters.");
2018 free_http_request(http);
2020 return JB_ERR_PARSE;
2023 if (client_has_unsupported_expectations(csp))
2025 return JB_ERR_PARSE;
2033 /*********************************************************************
2035 * Function : read_http_request_body
2037 * Description : Reads remaining request body from the client.
2040 * 1 : csp = Current client state (buffers, headers, etc...)
2042 * Returns : 0 on success, anything else is an error.
2044 *********************************************************************/
2045 static int read_http_request_body(struct client_state *csp)
2047 size_t to_read = csp->expected_client_content_length;
2050 assert(to_read != 0);
2052 /* check if all data has been already read */
2053 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2058 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2059 to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2060 to_read -= (unsigned)len)
2062 char buf[BUFFER_SIZE];
2063 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2065 log_error(LOG_LEVEL_CONNECT,
2066 "Waiting for up to %lu bytes of request body from the client.",
2068 len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2071 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2074 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2078 assert(to_read >= len);
2083 log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %llu more bytes",
2084 csp->expected_client_content_length);
2087 log_error(LOG_LEVEL_CONNECT, "The last %llu bytes of the request body have been read",
2088 csp->expected_client_content_length);
2093 /*********************************************************************
2095 * Function : update_client_headers
2097 * Description : Updates the HTTP headers from the client request.
2100 * 1 : csp = Current client state (buffers, headers, etc...)
2101 * 2 : new_content_length = new content length value to set
2103 * Returns : 0 on success, anything else is an error.
2105 *********************************************************************/
2106 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2108 static const char content_length[] = "Content-Length:";
2110 struct list_entry *p;
2112 #ifndef FEATURE_HTTPS_INSPECTION
2113 for (p = csp->headers->first;
2115 for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2117 !updated && (p != NULL); p = p->next)
2119 /* Header crunch()ed in previous run? -> ignore */
2125 /* Does the current parser handle this header? */
2126 if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2128 updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2140 /*********************************************************************
2142 * Function : can_filter_request_body
2144 * Description : Checks if the current request body can be stored in
2145 * the client_iob without hitting buffer limit.
2148 * 1 : csp = Current client state (buffers, headers, etc...)
2150 * Returns : TRUE if the current request size do not exceed buffer limit
2153 *********************************************************************/
2154 static int can_filter_request_body(const struct client_state *csp)
2156 if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2157 csp->expected_client_content_length))
2159 log_error(LOG_LEVEL_INFO,
2160 "Not filtering request body from %s: buffer limit %lu will be exceeded "
2161 "(content length %lluu)", csp->ip_addr_str, csp->config->buffer_limit,
2162 csp->expected_client_content_length);
2169 /*********************************************************************
2171 * Function : send_http_request
2173 * Description : Sends the HTTP headers from the client request
2174 * and all the body data that has already been received.
2177 * 1 : csp = Current client state (buffers, headers, etc...)
2179 * Returns : 0 on success, anything else is an error.
2181 *********************************************************************/
2182 static int send_http_request(struct client_state *csp)
2186 const char *to_send;
2188 int filter_client_body = csp->expected_client_content_length != 0 &&
2189 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2191 if (filter_client_body)
2193 if (read_http_request_body(csp))
2197 to_send_len = csp->expected_client_content_length;
2198 to_send = execute_client_body_filters(csp, &to_send_len);
2199 if (to_send == NULL)
2201 /* just flush client_iob */
2202 filter_client_body = FALSE;
2204 else if (to_send_len != csp->expected_client_content_length &&
2205 update_client_headers(csp, to_send_len))
2207 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2210 csp->expected_client_content_length = 0;
2213 hdr = list_to_text(csp->headers);
2216 /* FIXME Should handle error properly */
2217 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2219 list_remove_all(csp->headers);
2222 * Write the client's (modified) header to the server
2223 * (along with anything else that may be in the buffer)
2225 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2230 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2231 csp->http->hostport);
2235 if (filter_client_body)
2237 write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2241 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2242 csp->http->hostport);
2247 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2248 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2250 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2251 csp->http->hostport);
2258 #ifdef FEATURE_HTTPS_INSPECTION
2259 /*********************************************************************
2261 * Function : read_https_request_body
2263 * Description : Reads remaining request body from the client.
2266 * 1 : csp = Current client state (buffers, headers, etc...)
2268 * Returns : 0 on success, anything else is an error.
2270 *********************************************************************/
2271 static int read_https_request_body(struct client_state *csp)
2273 size_t to_read = csp->expected_client_content_length;
2276 assert(to_read != 0);
2278 /* check if all data has been already read */
2279 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2284 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2285 to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2286 data_is_available(csp->cfd, csp->config->socket_timeout));
2287 to_read -= (unsigned)len)
2289 unsigned char buf[BUFFER_SIZE];
2290 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2292 log_error(LOG_LEVEL_CONNECT,
2293 "Waiting for up to %lu bytes of request body from the client.",
2295 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2296 (unsigned)max_bytes_to_read);
2299 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2302 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2306 assert(to_read >= len);
2311 log_error(LOG_LEVEL_CONNECT,
2312 "Not enough request body has been read: expected %lu more bytes",
2317 log_error(LOG_LEVEL_CONNECT,
2318 "The last %llu bytes of the request body have been read",
2319 csp->expected_client_content_length);
2324 /*********************************************************************
2326 * Function : receive_and_send_encrypted_post_data
2328 * Description : Reads remaining request body from the client and sends
2332 * 1 : csp = Current client state (buffers, headers, etc...)
2334 * Returns : 0 on success, anything else is an error.
2336 *********************************************************************/
2337 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2339 int content_length_known = csp->expected_client_content_length != 0;
2341 while (is_ssl_pending(&(csp->ssl_client_attr))
2342 || (content_length_known && csp->expected_client_content_length != 0))
2344 unsigned char buf[BUFFER_SIZE];
2346 int max_bytes_to_read = sizeof(buf);
2348 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2350 max_bytes_to_read = (int)csp->expected_client_content_length;
2352 log_error(LOG_LEVEL_CONNECT,
2353 "Waiting for up to %d bytes of request body from the client.",
2355 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2356 (unsigned)max_bytes_to_read);
2363 /* XXX: Does this actually happen? */
2366 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2368 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2373 if (csp->expected_client_content_length != 0)
2375 if (csp->expected_client_content_length >= len)
2377 csp->expected_client_content_length -= (unsigned)len;
2379 if (csp->expected_client_content_length == 0)
2381 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2387 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2394 /*********************************************************************
2396 * Function : send_https_request
2398 * Description : Sends the HTTP headers from the client request
2399 * and all the body data that has already been received.
2402 * 1 : csp = Current client state (buffers, headers, etc...)
2404 * Returns : 0 on success, anything else is an error.
2406 *********************************************************************/
2407 static int send_https_request(struct client_state *csp)
2412 const char *to_send;
2414 int filter_client_body = csp->expected_client_content_length != 0 &&
2415 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2417 if (filter_client_body)
2419 if (read_https_request_body(csp))
2423 to_send_len = csp->expected_client_content_length;
2424 to_send = execute_client_body_filters(csp, &to_send_len);
2425 if (to_send == NULL)
2427 /* just flush client_iob */
2428 filter_client_body = FALSE;
2430 else if (to_send_len != csp->expected_client_content_length &&
2431 update_client_headers(csp, to_send_len))
2433 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2436 csp->expected_client_content_length = 0;
2439 hdr = list_to_text(csp->https_headers);
2442 /* FIXME Should handle error properly */
2443 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2445 list_remove_all(csp->https_headers);
2448 * Write the client's (modified) header to the server
2449 * (along with anything else that may be in the buffer)
2451 ret = ssl_send_data(&(csp->ssl_server_attr),
2452 (const unsigned char *)hdr, strlen(hdr));
2457 log_error(LOG_LEVEL_CONNECT,
2458 "Failed sending encrypted request headers to: %s: %E",
2459 csp->http->hostport);
2460 mark_server_socket_tainted(csp);
2464 if (filter_client_body)
2466 ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2470 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2471 csp->http->hostport);
2476 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2477 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2478 csp->client_iob)) < 0))
2480 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2481 csp->http->hostport);
2484 if (flushed != 0 || csp->expected_client_content_length != 0)
2486 if (csp->expected_client_content_length != 0)
2488 if (csp->expected_client_content_length < flushed)
2490 log_error(LOG_LEVEL_ERROR,
2491 "Flushed %ld bytes of request body while only expecting %llu",
2492 flushed, csp->expected_client_content_length);
2493 csp->expected_client_content_length = 0;
2497 log_error(LOG_LEVEL_CONNECT,
2498 "Flushed %ld bytes of request body while expecting %llu",
2499 flushed, csp->expected_client_content_length);
2500 csp->expected_client_content_length -= (unsigned)flushed;
2501 if (receive_and_send_encrypted_post_data(csp))
2509 log_error(LOG_LEVEL_CONNECT,
2510 "Flushed %ld bytes of request body", flushed);
2514 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2521 /*********************************************************************
2523 * Function : receive_encrypted_request
2525 * Description : Receives an encrypted request.
2528 * 1 : csp = Current client state (buffers, headers, etc...)
2530 * Returns : JB_ERR_OK on success,
2531 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2533 *********************************************************************/
2534 static jb_err receive_encrypted_request(struct client_state *csp)
2536 char buf[BUFFER_SIZE];
2542 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2543 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2544 !data_is_available(csp->cfd, csp->config->socket_timeout))
2546 log_error(LOG_LEVEL_CONNECT,
2547 "Socket %d timed out while waiting for client headers", csp->cfd);
2548 return JB_ERR_PARSE;
2550 len = ssl_recv_data(&(csp->ssl_client_attr),
2551 (unsigned char *)buf, sizeof(buf));
2554 log_error(LOG_LEVEL_CONNECT,
2555 "Socket %d closed while waiting for client headers", csp->cfd);
2556 return JB_ERR_PARSE;
2560 return JB_ERR_PARSE;
2562 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2564 return JB_ERR_MEMORY;
2566 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2567 } while (p == NULL);
2569 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2575 /*********************************************************************
2577 * Function : change_encrypted_request_destination
2579 * Description : Parse a (rewritten) request line from an encrypted
2580 * request and regenerate the http request data.
2583 * 1 : csp = Current client state (buffers, headers, etc...)
2585 * Returns : Forwards the parse_http_request() return code.
2586 * Terminates in case of memory problems.
2588 *********************************************************************/
2589 static jb_err change_encrypted_request_destination(struct client_state *csp)
2592 char *original_host = csp->http->host;
2593 int original_port = csp->http->port;
2595 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2596 csp->https_headers->first->str);
2597 csp->http->host = NULL;
2598 free_http_request(csp->http);
2599 err = parse_http_request(csp->https_headers->first->str, csp->http);
2600 if (JB_ERR_OK != err)
2602 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2603 jb_err_to_string(err));
2604 freez(original_host);
2608 if (csp->http->host == NULL)
2610 char port_string[10];
2612 * The rewritten request line did not specify a host
2613 * which means we can use the original host specified
2616 csp->http->host = original_host;
2617 csp->http->port = original_port;
2618 log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2621 * If the rewritten request line didn't contain a host
2622 * it also didn't contain a port so we can reuse the host
2625 freez(csp->http->hostport);
2626 csp->http->hostport = strdup_or_die(csp->http->host);
2627 snprintf(port_string, sizeof(port_string), ":%d", original_port);
2628 err = string_append(&csp->http->hostport, port_string);
2629 if (err != JB_ERR_OK)
2631 log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2632 jb_err_to_string(err));
2637 * While the request line didn't mention it,
2638 * we're https-inspecting and want to speak TLS
2641 csp->http->server_ssl = 1;
2646 /* The rewrite filter added a host so we can ditch the original */
2647 freez(original_host);
2648 csp->http->server_ssl = csp->http->ssl;
2651 csp->http->client_ssl = 1;
2653 freez(csp->https_headers->first->str);
2654 build_request_line(csp, NULL, &csp->https_headers->first->str);
2656 if (!server_use_ssl(csp))
2658 log_error(LOG_LEVEL_REDIRECTS,
2659 "Rewritten request line results in downgrade to http");
2661 * Replace the unencryptd headers received with the
2662 * CONNECT request with the ones we received securely.
2664 destroy_list(csp->headers);
2665 csp->headers->first = csp->https_headers->first;
2666 csp->headers->last = csp->https_headers->last;
2667 csp->https_headers->first = NULL;
2668 csp->https_headers->last = NULL;
2676 /*********************************************************************
2678 * Function : process_encrypted_request
2680 * Description : Receives and parses an encrypted request.
2683 * 1 : csp = Current client state (buffers, headers, etc...)
2685 * Returns : JB_ERR_OK on success,
2686 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2688 *********************************************************************/
2689 static jb_err process_encrypted_request(struct client_state *csp)
2694 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2695 struct list header_list;
2696 struct list *headers = &header_list;
2698 assert(csp->ssl_with_client_is_opened);
2700 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2701 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2703 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2706 err = receive_encrypted_request(csp);
2707 if (err != JB_ERR_OK)
2709 if (csp->client_iob->cur == NULL ||
2710 csp->client_iob->cur == csp->client_iob->eod)
2713 * We did not receive any data, most likely because the
2714 * client is done. Don't log this as a parse failure.
2716 return JB_ERR_PARSE;
2718 /* XXX: Also used for JB_ERR_MEMORY */
2719 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2720 jb_err_to_string(err));
2721 ssl_send_data_delayed(&(csp->ssl_client_attr),
2722 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2726 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2727 request_line = get_header(csp->client_iob);
2728 if (request_line == NULL)
2730 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2731 ssl_send_data_delayed(&(csp->ssl_client_attr),
2732 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2733 return JB_ERR_PARSE;
2735 assert(*request_line != '\0');
2737 if (client_protocol_is_unsupported(csp, request_line))
2740 * If the protocol is unsupported we're done here.
2741 * client_protocol_is_unsupported() took care of sending
2742 * the error response and logging the error message.
2744 return JB_ERR_PARSE;
2747 #ifdef FEATURE_FORCE_LOAD
2748 if (force_required(csp, request_line))
2750 csp->flags |= CSP_FLAG_FORCED;
2752 #endif /* def FEATURE_FORCE_LOAD */
2754 free_http_request(csp->http);
2756 err = parse_http_request(request_line, csp->http);
2757 /* XXX: Restore ssl setting. This is ugly */
2758 csp->http->client_ssl = 1;
2759 csp->http->server_ssl = 1;
2761 freez(request_line);
2762 if (JB_ERR_OK != err)
2764 ssl_send_data_delayed(&(csp->ssl_client_attr),
2765 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2766 /* XXX: Use correct size */
2767 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2768 log_error(LOG_LEVEL_ERROR,
2769 "Couldn't parse request line received from %s: %s",
2770 csp->ip_addr_str, jb_err_to_string(err));
2772 free_http_request(csp->http);
2773 return JB_ERR_PARSE;
2776 /* Parse the rest of the client's headers. */
2780 p = get_header(csp->client_iob);
2784 /* There are no additional headers to read. */
2791 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2794 * Our attempts to get the request destination
2797 log_error(LOG_LEVEL_ERROR,
2798 "Failed to get the encrypted request destination");
2799 ssl_send_data_delayed(&(csp->ssl_client_attr),
2800 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2801 return JB_ERR_PARSE;
2804 /* Split the domain we just got for pattern matching */
2805 init_domain_components(csp->http);
2807 #ifdef FEATURE_CLIENT_TAGS
2808 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2809 if (csp->client_address == NULL)
2811 set_client_address(csp, headers);
2812 get_tag_list_for_client(csp->client_tags, csp->client_address);
2816 #ifdef FEATURE_TOGGLE
2817 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2821 * Determine the actions for this request after
2822 * clearing the ones from the previous one.
2824 free_current_action(csp->action);
2825 get_url_actions(csp, csp->http);
2828 enlist(csp->https_headers, csp->http->cmd);
2830 /* Append the previously read headers */
2831 err = list_append_list_unique(csp->https_headers, headers);
2832 destroy_list(headers);
2833 if (JB_ERR_OK != err)
2835 /* XXX: Send error message */
2839 /* XXX: Work around crash */
2840 csp->error_message = NULL;
2842 /* XXX: Why do this here? */
2845 err = sed_https(csp);
2846 if (JB_ERR_OK != err)
2848 ssl_send_data_delayed(&(csp->ssl_client_attr),
2849 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2850 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2852 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2853 csp->ip_addr_str, csp->http->cmd);
2854 return JB_ERR_PARSE;
2857 if ((NULL == csp->https_headers->first->str)
2858 || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2859 (JB_ERR_OK != change_encrypted_request_destination(csp))))
2861 ssl_send_data_delayed(&(csp->ssl_client_attr),
2862 (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2863 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2864 log_error(LOG_LEVEL_ERROR,
2865 "Invalid request line after applying header filters.");
2866 /* XXX: Use correct size */
2867 log_error(LOG_LEVEL_CLF,
2868 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2870 return JB_ERR_PARSE;
2873 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2874 log_applied_actions(csp->action);
2875 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2882 /*********************************************************************
2884 * Function : cgi_page_requested
2886 * Description : Checks if a request is for an internal CGI page.
2889 * 1 : host = The host requested by the client.
2891 * Returns : 1 if a CGI page has been requested, 0 otherwise
2893 *********************************************************************/
2894 static int cgi_page_requested(const char *host)
2896 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2897 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2898 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2899 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2909 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2910 /*********************************************************************
2912 * Function : continue_https_chat
2914 * Description : Behaves similar to chat() but only deals with
2915 * https-inspected requests that arrive on an already
2916 * established connection. The first request is always
2917 * served by chat() which is a lot more complex as it
2918 * has to deal with forwarding settings and connection
2921 * If a connection to the server has already been
2922 * opened it is reused unless the request is blocked
2923 * or the forwarder changed.
2925 * If a connection to the server has not yet been
2926 * opened (because the previous request was crunched),
2927 * or the forwarder changed, the connection is dropped
2928 * so that the client retries on a fresh one.
2931 * 1 : csp = Current client state (buffers, headers, etc...)
2933 * Returns : Nothing.
2935 *********************************************************************/
2936 static void continue_https_chat(struct client_state *csp)
2938 const struct forward_spec *fwd;
2940 if (JB_ERR_OK != process_encrypted_request(csp))
2942 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2946 csp->requests_received_total++;
2949 * We have an encrypted request. Check if one of the crunchers wants it.
2951 if (crunch_response_triggered(csp, crunchers_all))
2954 * Yes. The client got the crunch response and we're done here.
2958 if (csp->ssl_with_server_is_opened == 0)
2960 log_error(LOG_LEVEL_CONNECT,
2961 "Dropping the client connection on socket %d. "
2962 "The server connection has not been established yet.",
2964 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2967 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2969 fwd = forward_url(csp, csp->http);
2970 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2972 log_error(LOG_LEVEL_CONNECT,
2973 "Dropping the client connection on socket %d with "
2974 "server socket %d connected to %s. The forwarder has changed.",
2975 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2976 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2980 log_error(LOG_LEVEL_CONNECT,
2981 "Reusing server socket %d connected to %s. Requests already sent: %u.",
2982 csp->server_connection.sfd, csp->server_connection.host,
2983 csp->server_connection.requests_sent_total);
2985 if (send_https_request(csp))
2988 * Most likely the server connection timed out. We can't easily
2989 * create a new one so simply drop the client connection without a
2990 * error response to let the client retry.
2992 log_error(LOG_LEVEL_CONNECT,
2993 "Dropping client connection on socket %d. "
2994 "Forwarding the encrypted client request failed.",
2998 csp->server_connection.request_sent = time(NULL);
2999 csp->server_connection.requests_sent_total++;
3000 handle_established_connection(csp);
3001 freez(csp->receive_buffer);
3003 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3007 /*********************************************************************
3009 * Function : handle_established_connection
3011 * Description : Shuffle data between client and server once the
3012 * connection has been established.
3015 * 1 : csp = Current client state (buffers, headers, etc...)
3017 * Returns : Nothing.
3019 *********************************************************************/
3020 static void handle_established_connection(struct client_state *csp)
3026 struct pollfd poll_fds[2];
3030 struct timeval timeout;
3033 int ms_iis5_hack = 0;
3034 unsigned long long byte_count = 0;
3035 struct http_request *http;
3036 long len = 0; /* for buffer sizes (and negative error codes) */
3037 int buffer_and_filter_content = 0;
3038 unsigned int write_delay;
3039 #ifdef FEATURE_HTTPS_INSPECTION
3041 int use_ssl_tunnel = 0;
3042 csp->dont_verify_certificate = 0;
3044 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3046 /* Pass encrypted content without filtering. */
3051 /* Skeleton for HTTP response, if we should intercept the request */
3052 struct http_response *rsp;
3053 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3054 int watch_client_socket;
3057 csp->receive_buffer_size = csp->config->receive_buffer_size;
3058 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3059 if (csp->receive_buffer == NULL)
3061 log_error(LOG_LEVEL_ERROR,
3062 "Out of memory. Failed to allocate the receive buffer.");
3063 rsp = cgi_error_memory();
3064 send_crunch_response(csp, rsp);
3071 maxfd = (csp->cfd > csp->server_connection.sfd) ?
3072 csp->cfd : csp->server_connection.sfd;
3075 /* pass data between the client and server
3076 * until one or the other shuts down the connection.
3081 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3082 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3084 write_delay = get_write_delay(csp);
3090 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3091 if (!watch_client_socket)
3093 maxfd = csp->server_connection.sfd;
3096 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3098 FD_SET(csp->cfd, &rfds);
3101 FD_SET(csp->server_connection.sfd, &rfds);
3102 #endif /* ndef HAVE_POLL */
3104 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3105 if ((csp->flags & CSP_FLAG_CHUNKED)
3106 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3107 && ((csp->iob->eod - csp->iob->cur) >= 5)
3108 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3111 * XXX: This check should be obsolete now,
3112 * but let's wait a while to be sure.
3114 log_error(LOG_LEVEL_CONNECT,
3115 "Looks like we got the last chunk together with "
3116 "the server headers but didn't detect it earlier. "
3117 "We better stop reading.");
3118 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3119 csp->expected_content_length = byte_count;
3120 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3122 if (server_body && server_response_is_complete(csp, byte_count))
3124 if (csp->expected_content_length == byte_count)
3126 log_error(LOG_LEVEL_CONNECT,
3127 "Done reading from server. Content length: %llu as expected. "
3128 "Bytes most recently read: %ld.",
3133 log_error(LOG_LEVEL_CONNECT,
3134 "Done reading from server. Expected content length: %llu. "
3135 "Actual content length: %llu. Bytes most recently read: %ld.",
3136 csp->expected_content_length, byte_count, len);
3140 * XXX: Should not jump around, handle_established_connection()
3141 * is complicated enough already.
3145 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3148 poll_fds[0].fd = csp->cfd;
3149 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3150 if (!watch_client_socket)
3153 * Ignore incoming data, but still watch out
3154 * for disconnects etc. These flags are always
3155 * implied anyway but explicitly setting them
3158 poll_fds[0].events = POLLERR|POLLHUP;
3163 poll_fds[0].events = POLLIN;
3165 poll_fds[1].fd = csp->server_connection.sfd;
3166 poll_fds[1].events = POLLIN;
3167 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3169 timeout.tv_sec = csp->config->socket_timeout;
3170 timeout.tv_usec = 0;
3171 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3172 #endif /* def HAVE_POLL */
3174 /*server or client not responding in timeout */
3177 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3178 csp->config->socket_timeout, http->url);
3179 if ((byte_count == 0) && (http->ssl == 0))
3181 send_crunch_response(csp, error_response(csp, "connection-timeout"));
3183 mark_server_socket_tainted(csp);
3184 #ifdef FEATURE_HTTPS_INSPECTION
3185 close_client_and_server_ssl_connections(csp);
3192 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3194 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3196 mark_server_socket_tainted(csp);
3197 #ifdef FEATURE_HTTPS_INSPECTION
3198 close_client_and_server_ssl_connections(csp);
3204 * This is the body of the browser's request,
3205 * just read and write it.
3207 * Receives data from browser and sends it to server
3209 * XXX: Make sure the client doesn't use pipelining
3210 * behind Privoxy's back.
3213 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3215 log_error(LOG_LEVEL_CONNECT,
3216 "The client socket %d has become unusable while "
3217 "the server socket %d is still open.",
3218 csp->cfd, csp->server_connection.sfd);
3219 mark_server_socket_tainted(csp);
3223 if (poll_fds[0].revents != 0)
3225 if (FD_ISSET(csp->cfd, &rfds))
3226 #endif /* def HAVE_POLL*/
3228 int max_bytes_to_read = (int)csp->receive_buffer_size;
3230 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3231 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3233 if (data_is_available(csp->cfd, 0))
3236 * If the next request is already waiting, we have
3237 * to stop select()ing the client socket. Otherwise
3238 * we would always return right away and get nothing
3241 watch_client_socket = 0;
3242 log_error(LOG_LEVEL_CONNECT,
3243 "Stop watching client socket %d. "
3244 "There's already another request waiting.",
3249 * If the client socket is set, but there's no data
3250 * available on the socket, the client went fishing
3251 * and continuing talking to the server makes no sense.
3253 log_error(LOG_LEVEL_CONNECT,
3254 "The client closed socket %d while "
3255 "the server socket %d is still open.",
3256 csp->cfd, csp->server_connection.sfd);
3257 mark_server_socket_tainted(csp);
3260 if (csp->expected_client_content_length != 0)
3262 if (csp->expected_client_content_length < csp->receive_buffer_size)
3264 max_bytes_to_read = (int)csp->expected_client_content_length;
3266 log_error(LOG_LEVEL_CONNECT,
3267 "Waiting for up to %d bytes from the client.",
3270 assert(max_bytes_to_read <= csp->receive_buffer_size);
3271 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3273 #ifdef FEATURE_HTTPS_INSPECTION
3274 if (client_use_ssl(csp))
3276 if (csp->http->status == 101)
3278 len = ssl_recv_data(&(csp->ssl_client_attr),
3279 (unsigned char *)csp->receive_buffer,
3280 (size_t)max_bytes_to_read);
3283 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3284 "on client socket %d for an upgraded connection",
3290 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3291 "on client socket %d for an upgraded connection",
3295 byte_count += (unsigned long long)len;
3296 len = ssl_send_data(&(csp->ssl_server_attr),
3297 (unsigned char *)csp->receive_buffer, (size_t)len);
3300 log_error(LOG_LEVEL_ERROR, "Failed to send data "
3301 "on server socket %d for an upgraded connection",
3302 csp->server_connection.sfd);
3307 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3311 #endif /* def FEATURE_HTTPS_INSPECTION */
3313 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3317 /* XXX: not sure if this is necessary. */
3318 mark_server_socket_tainted(csp);
3319 break; /* "game over, man" */
3322 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3323 if (csp->expected_client_content_length != 0)
3325 assert(len <= max_bytes_to_read);
3326 csp->expected_client_content_length -= (unsigned)len;
3327 log_error(LOG_LEVEL_CONNECT,
3328 "Expected client content length set to %llu "
3329 "after reading %ld bytes.",
3330 csp->expected_client_content_length, len);
3331 if (csp->expected_client_content_length == 0)
3333 log_error(LOG_LEVEL_CONNECT,
3334 "Done reading from the client.");
3335 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3338 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3340 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3342 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3343 mark_server_socket_tainted(csp);
3351 * The server wants to talk. It could be the header or the body.
3352 * If `hdr' is null, then it's the header otherwise it's the body.
3353 * FIXME: Does `hdr' really mean `host'? No.
3356 if (poll_fds[1].revents != 0)
3358 if (FD_ISSET(csp->server_connection.sfd, &rfds))
3359 #endif /* HAVE_POLL */
3361 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3363 * If we are buffering content, we don't want to eat up to
3364 * buffer-limit bytes if the client no longer cares about them.
3365 * If we aren't buffering, however, a dead client socket will be
3366 * noticed pretty much right away anyway, so we can reduce the
3367 * overhead by skipping the check.
3369 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3372 log_error(LOG_LEVEL_CONNECT,
3373 "The server still wants to talk, but the client may already have hung up on us.");
3375 log_error(LOG_LEVEL_CONNECT,
3376 "The server still wants to talk, but the client hung up on us.");
3377 mark_server_socket_tainted(csp);
3378 #ifdef FEATURE_HTTPS_INSPECTION
3379 close_client_and_server_ssl_connections(csp);
3382 #endif /* def _WIN32 */
3384 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3386 #ifdef FEATURE_HTTPS_INSPECTION
3388 * Reading data from standard or secured connection (HTTP/HTTPS)
3390 if (server_use_ssl(csp))
3392 len = ssl_recv_data(&(csp->ssl_server_attr),
3393 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3398 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3399 (int)csp->receive_buffer_size);
3404 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3406 if ((http->ssl && (csp->fwd == NULL))
3407 #ifdef FEATURE_HTTPS_INSPECTION
3413 * Just hang up. We already confirmed the client's CONNECT
3414 * request with status code 200 and unencrypted content is
3415 * no longer welcome.
3417 log_error(LOG_LEVEL_ERROR,
3418 "CONNECT already confirmed. Unable to tell the client about the problem.");
3421 else if (byte_count)
3424 * Just hang up. We already transmitted the original headers
3425 * and parts of the original content and therefore missed the
3426 * chance to send an error message (without risking data corruption).
3428 * XXX: we could retry with a fancy range request here.
3430 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3431 "Unable to tell the client about the problem.");
3432 mark_server_socket_tainted(csp);
3433 #ifdef FEATURE_HTTPS_INSPECTION
3434 close_client_and_server_ssl_connections(csp);
3439 * XXX: Consider handling the cases above the same.
3441 mark_server_socket_tainted(csp);
3445 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3446 if (csp->flags & CSP_FLAG_CHUNKED)
3448 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3450 /* XXX: this is a temporary hack */
3451 log_error(LOG_LEVEL_CONNECT,
3452 "Looks like we reached the end of the last chunk. "
3453 "We better stop reading.");
3454 csp->expected_content_length = byte_count + (unsigned long long)len;
3455 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3459 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3462 * This is guaranteed by allocating with zalloc_or_die()
3463 * and never (intentionally) writing to the last byte.
3465 * csp->receive_buffer_size is the size of the part of the
3466 * buffer we intentionally write to, but we actually
3467 * allocated csp->receive_buffer_size+1 bytes so the assertion
3468 * stays within the allocated range.
3470 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3473 * Add a trailing zero to let be able to use string operations.
3474 * XXX: do we still need this with filter_popups gone?
3476 assert(len <= csp->receive_buffer_size);
3477 csp->receive_buffer[len] = '\0';
3480 * Normally, this would indicate that we've read
3481 * as much as the server has sent us and we can
3482 * close the client connection. However, Microsoft
3483 * in its wisdom has released IIS/5 with a bug that
3484 * prevents it from sending the trailing \r\n in
3485 * a 302 redirect header (and possibly other headers).
3486 * To work around this if we've haven't parsed
3487 * a full header we'll append a trailing \r\n
3488 * and see if this now generates a valid one.
3490 * This hack shouldn't have any impacts. If we've
3491 * already transmitted the header or if this is a
3492 * SSL connection, then we won't bother with this
3493 * hack. So we only work on partially received
3494 * headers. If we append a \r\n and this still
3495 * doesn't generate a valid header, then we won't
3496 * transmit anything to the client.
3501 if (server_body || (http->ssl
3502 #ifdef FEATURE_HTTPS_INSPECTION
3508 * If we have been buffering up the document,
3509 * now is the time to apply content modification
3510 * and send the result to the client.
3512 if (buffer_and_filter_content)
3514 p = execute_content_filters(csp);
3516 * If content filtering fails, use the original
3517 * buffer and length.
3518 * (see p != NULL ? p : csp->iob->cur below)
3522 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3524 #ifdef FEATURE_COMPRESSION
3525 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3526 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3528 char *compressed_content = compress_buffer(p,
3529 (size_t *)&csp->content_length, csp->config->compression_level);
3530 if (compressed_content != NULL)
3533 p = compressed_content;
3534 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3539 if (JB_ERR_OK != update_server_headers(csp))
3541 log_error(LOG_LEVEL_FATAL,
3542 "Failed to update server headers. after filtering.");
3545 hdr = list_to_text(csp->headers);
3548 /* FIXME Should handle error properly */
3549 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3552 #ifdef FEATURE_HTTPS_INSPECTION
3554 * Sending data with standard or secured connection (HTTP/HTTPS)
3556 if (client_use_ssl(csp))
3558 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3559 (const unsigned char *)hdr, strlen(hdr),
3560 get_write_delay(csp)) < 0)
3561 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3562 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3563 csp->content_length, get_write_delay(csp)) < 0))
3565 log_error(LOG_LEVEL_ERROR,
3566 "Failed to send the modified content to the client over TLS");
3569 mark_server_socket_tainted(csp);
3570 close_client_and_server_ssl_connections(csp);
3575 #endif /* def FEATURE_HTTPS_INSPECTION */
3577 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3578 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3579 (size_t)csp->content_length, write_delay))
3581 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3584 mark_server_socket_tainted(csp);
3593 break; /* "game over, man" */
3597 * This is NOT the body, so
3598 * Let's pretend the server just sent us a blank line.
3600 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3601 len = (int)strlen(csp->receive_buffer);
3604 * Now, let the normal header parsing algorithm below do its
3605 * job. If it fails, we'll exit instead of continuing.
3612 * If we're in the body of the server document, just write it to
3613 * the client, unless we need to buffer the body for later
3614 * content-filtering.
3616 if (server_body || (http->ssl
3617 #ifdef FEATURE_HTTPS_INSPECTION
3622 if (buffer_and_filter_content)
3625 * If there is no memory left for buffering the content, or the buffer limit
3626 * has been reached, switch to non-filtering mode, i.e. make & write the
3627 * header, flush the iob and buf, and get out of the way.
3629 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3634 log_error(LOG_LEVEL_INFO,
3635 "Flushing header and buffers. Stepping back from filtering.");
3637 hdr = list_to_text(csp->headers);
3641 * Memory is too tight to even generate the header.
3642 * Send our static "Out-of-memory" page.
3644 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3645 rsp = cgi_error_memory();
3646 send_crunch_response(csp, rsp);
3647 mark_server_socket_tainted(csp);
3648 #ifdef FEATURE_HTTPS_INSPECTION
3649 close_client_and_server_ssl_connections(csp);
3653 hdrlen = strlen(hdr);
3655 #ifdef FEATURE_HTTPS_INSPECTION
3657 * Sending data with standard or secured connection (HTTP/HTTPS)
3659 if (client_use_ssl(csp))
3661 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3662 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3663 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3665 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3666 (const unsigned char *)csp->receive_buffer, (size_t)len,
3667 get_write_delay(csp)) < 0))
3669 log_error(LOG_LEVEL_CONNECT,
3670 "Flush header and buffers to client failed");
3672 mark_server_socket_tainted(csp);
3673 close_client_and_server_ssl_connections(csp);
3678 #endif /* def FEATURE_HTTPS_INSPECTION */
3680 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3681 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3682 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3685 log_error(LOG_LEVEL_CONNECT,
3686 "Flush header and buffers to client failed: %E");
3688 mark_server_socket_tainted(csp);
3694 * Reset the byte_count to the amount of bytes
3695 * we just flushed. len will be added a few lines below,
3696 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3698 byte_count = (unsigned long long)flushed;
3700 buffer_and_filter_content = 0;
3706 #ifdef FEATURE_HTTPS_INSPECTION
3708 * Sending data with standard or secured connection (HTTP/HTTPS)
3710 if (client_use_ssl(csp))
3712 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3713 (const unsigned char *)csp->receive_buffer, (size_t)len,
3714 get_write_delay(csp));
3717 log_error(LOG_LEVEL_ERROR,
3718 "Sending data to client failed");
3719 mark_server_socket_tainted(csp);
3720 close_client_and_server_ssl_connections(csp);
3725 #endif /* def FEATURE_HTTPS_INSPECTION */
3727 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3728 (size_t)len, write_delay))
3730 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3731 mark_server_socket_tainted(csp);
3736 byte_count += (unsigned long long)len;
3742 * We're still looking for the end of the server's header.
3743 * Buffer up the data we just read. If that fails, there's
3744 * little we can do but send our static out-of-memory page.
3746 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3748 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3749 rsp = cgi_error_memory();
3750 send_crunch_response(csp, rsp);
3751 mark_server_socket_tainted(csp);
3752 #ifdef FEATURE_HTTPS_INSPECTION
3753 close_client_and_server_ssl_connections(csp);
3758 /* Convert iob into something sed() can digest */
3759 if (JB_ERR_PARSE == get_server_headers(csp))
3764 * Well, we tried our MS IIS/5 hack and it didn't work.
3765 * The header is incomplete and there isn't anything
3766 * we can do about it.
3768 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3769 "Applying the MS IIS5 hack didn't help.");
3770 log_error(LOG_LEVEL_CLF,
3771 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3772 #ifdef FEATURE_HTTPS_INSPECTION
3774 * Sending data with standard or secured connection (HTTP/HTTPS)
3776 if (client_use_ssl(csp))
3778 ssl_send_data_delayed(&(csp->ssl_client_attr),
3779 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3780 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3783 #endif /* def FEATURE_HTTPS_INSPECTION */
3785 write_socket_delayed(csp->cfd,
3786 INVALID_SERVER_HEADERS_RESPONSE,
3787 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3789 mark_server_socket_tainted(csp);
3790 #ifdef FEATURE_HTTPS_INSPECTION
3791 close_client_and_server_ssl_connections(csp);
3798 * Since we have to wait for more from the server before
3799 * we can parse the headers we just continue here.
3801 log_error(LOG_LEVEL_CONNECT,
3802 "Continuing buffering server headers from socket %d. "
3803 "Bytes most recently read: %ld.", csp->cfd, len);
3810 * Account for the content bytes we
3811 * might have gotten with the headers.
3813 assert(csp->iob->eod >= csp->iob->cur);
3814 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3817 /* Did we actually get anything? */
3818 if (NULL == csp->headers->first)
3820 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3822 log_error(LOG_LEVEL_ERROR,
3823 "No server or forwarder response received on socket %d. "
3824 "Closing client socket %d without sending data.",
3825 csp->server_connection.sfd, csp->cfd);
3826 log_error(LOG_LEVEL_CLF,
3827 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3831 log_error(LOG_LEVEL_ERROR,
3832 "No server or forwarder response received on socket %d.",
3833 csp->server_connection.sfd);
3834 send_crunch_response(csp, error_response(csp, "no-server-data"));
3836 free_http_request(http);
3837 mark_server_socket_tainted(csp);
3838 #ifdef FEATURE_HTTPS_INSPECTION
3839 close_client_and_server_ssl_connections(csp);
3844 if (!csp->headers->first->str)
3846 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3848 assert(csp->headers->first->str);
3850 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3851 strncmpic(csp->headers->first->str, "ICY", 3))
3854 * It doesn't look like a HTTP (or Shoutcast) response:
3855 * tell the client and log the problem.
3857 if (strlen(csp->headers->first->str) > 30)
3859 csp->headers->first->str[30] = '\0';
3861 log_error(LOG_LEVEL_ERROR,
3862 "Invalid server or forwarder response. Starts with: %s",
3863 csp->headers->first->str);
3864 log_error(LOG_LEVEL_CLF,
3865 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3866 #ifdef FEATURE_HTTPS_INSPECTION
3868 * Sending data with standard or secured connection (HTTP/HTTPS)
3870 if (client_use_ssl(csp))
3872 ssl_send_data_delayed(&(csp->ssl_client_attr),
3873 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3874 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3875 get_write_delay(csp));
3878 #endif /* def FEATURE_HTTPS_INSPECTION */
3880 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3881 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3883 free_http_request(http);
3884 mark_server_socket_tainted(csp);
3885 #ifdef FEATURE_HTTPS_INSPECTION
3886 close_client_and_server_ssl_connections(csp);
3892 * Disable redirect checkers, so that they will be only run
3893 * again if the user also enables them through tags.
3895 * From a performance point of view it doesn't matter,
3896 * but it prevents duplicated log messages.
3898 #ifdef FEATURE_FAST_REDIRECTS
3899 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
3901 csp->action->flags &= ~ACTION_REDIRECT;
3904 * We have now received the entire server header,
3905 * filter it and send the result to the client
3907 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3909 log_error(LOG_LEVEL_CLF,
3910 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3911 #ifdef FEATURE_HTTPS_INSPECTION
3913 * Sending data with standard or secured connection (HTTP/HTTPS)
3915 if (client_use_ssl(csp))
3917 ssl_send_data_delayed(&(csp->ssl_client_attr),
3918 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3919 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3920 get_write_delay(csp));
3925 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3926 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3928 free_http_request(http);
3929 mark_server_socket_tainted(csp);
3930 #ifdef FEATURE_HTTPS_INSPECTION
3931 close_client_and_server_ssl_connections(csp);
3935 hdr = list_to_text(csp->headers);
3938 /* FIXME Should handle error properly */
3939 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3942 if ((csp->flags & CSP_FLAG_CHUNKED)
3943 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3944 && ((csp->iob->eod - csp->iob->cur) >= 5)
3945 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3947 log_error(LOG_LEVEL_CONNECT,
3948 "Looks like we got the last chunk together with "
3949 "the server headers. We better stop reading.");
3950 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3951 csp->expected_content_length = byte_count;
3952 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3955 csp->server_connection.response_received = time(NULL);
3957 if (crunch_response_triggered(csp, crunchers_light))
3960 * One of the tags created by a server-header
3961 * tagger triggered a crunch. We already
3962 * delivered the crunch response to the client
3963 * and are done here after cleaning up.
3966 mark_server_socket_tainted(csp);
3967 #ifdef FEATURE_HTTPS_INSPECTION
3968 close_client_and_server_ssl_connections(csp);
3973 /* Buffer and pcrs filter this if appropriate. */
3974 buffer_and_filter_content = content_requires_filtering(csp);
3976 if (!buffer_and_filter_content)
3979 * Write the server's (modified) header to
3980 * the client (along with anything else that
3981 * may be in the buffer). Use standard or secured
3984 #ifdef FEATURE_HTTPS_INSPECTION
3985 if (client_use_ssl(csp))
3987 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3988 (const unsigned char *)hdr, strlen(hdr),
3989 get_write_delay(csp)) < 0)
3990 || ((len = ssl_flush_socket(&(csp->ssl_client_attr),
3993 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3996 * The write failed, so don't bother mentioning it
3997 * to the client... it probably can't hear us anyway.
4000 mark_server_socket_tainted(csp);
4001 #ifdef FEATURE_HTTPS_INSPECTION
4002 close_client_and_server_ssl_connections(csp);
4008 #endif /* def FEATURE_HTTPS_INSPECTION */
4010 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
4011 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
4013 log_error(LOG_LEVEL_ERROR,
4014 "write header to client failed");
4016 * The write failed, so don't bother mentioning it
4017 * to the client... it probably can't hear us anyway.
4020 mark_server_socket_tainted(csp);
4026 /* we're finished with the server's header */
4032 * If this was a MS IIS/5 hack then it means the server
4033 * has already closed the connection. Nothing more to read.
4038 log_error(LOG_LEVEL_ERROR,
4039 "Closed server connection detected. "
4040 "Applying the MS IIS5 hack didn't help.");
4041 log_error(LOG_LEVEL_CLF,
4042 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4043 #ifdef FEATURE_HTTPS_INSPECTION
4045 * Sending data with standard or secured connection (HTTP/HTTPS)
4047 if (client_use_ssl(csp))
4049 ssl_send_data_delayed(&(csp->ssl_client_attr),
4050 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4051 strlen(INVALID_SERVER_HEADERS_RESPONSE),
4052 get_write_delay(csp));
4055 #endif /* def FEATURE_HTTPS_INSPECTION */
4057 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4058 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4060 mark_server_socket_tainted(csp);
4061 #ifdef FEATURE_HTTPS_INSPECTION
4062 close_client_and_server_ssl_connections(csp);
4069 mark_server_socket_tainted(csp);
4070 #ifdef FEATURE_HTTPS_INSPECTION
4071 close_client_and_server_ssl_connections(csp);
4073 return; /* huh? we should never get here */
4076 if (csp->content_length == 0)
4079 * If Privoxy didn't recalculate the Content-Length,
4080 * byte_count is still correct.
4082 csp->content_length = byte_count;
4085 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4086 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4087 && (csp->expected_content_length != byte_count))
4089 log_error(LOG_LEVEL_CONNECT,
4090 "Received %llu bytes while expecting %llu.",
4091 byte_count, csp->expected_content_length);
4092 mark_server_socket_tainted(csp);
4096 #ifdef FEATURE_HTTPS_INSPECTION
4097 if (client_use_ssl(csp))
4099 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4100 csp->ip_addr_str, http->gpc, http->hostport, http->path,
4101 http->version, csp->content_length);
4106 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4107 csp->ip_addr_str, http->ocmd, csp->content_length);
4109 csp->server_connection.timestamp = time(NULL);
4113 /*********************************************************************
4117 * Description : Once a connection from the client has been accepted,
4118 * this function is called (via serve()) to handle the
4119 * main business of the communication. This function
4120 * returns after dealing with a single request. It can
4121 * be called multiple times with the same client socket
4122 * if the client is keeping the connection alive.
4124 * The decision whether or not a client connection will
4125 * be kept alive is up to the caller which also must
4126 * close the client socket when done.
4128 * FIXME: chat is nearly thousand lines long.
4132 * 1 : csp = Current client state (buffers, headers, etc...)
4134 * Returns : Nothing.
4136 *********************************************************************/
4137 static void chat(struct client_state *csp)
4139 const struct forward_spec *fwd;
4140 struct http_request *http;
4141 /* Skeleton for HTTP response, if we should intercept the request */
4142 struct http_response *rsp;
4143 #ifdef FEATURE_HTTPS_INSPECTION
4144 int use_ssl_tunnel = 0;
4149 if (receive_client_request(csp) != JB_ERR_OK)
4153 if (parse_client_request(csp) != JB_ERR_OK)
4158 #ifdef FEATURE_HTTPS_INSPECTION
4160 * Setting flags to use old solution with SSL tunnel and to disable
4161 * certificate verification.
4163 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4164 && !cgi_page_requested(csp->http->host))
4169 if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4171 csp->dont_verify_certificate = 1;
4176 * build the http request to send to the server
4177 * we have to do one of the following:
4179 * create = use the original HTTP request to create a new
4180 * HTTP request that has either the path component
4181 * without the http://domainspec (w/path) or the
4182 * full orininal URL (w/url)
4183 * Note that the path and/or the HTTP version may
4184 * have been altered by now.
4186 * SSL proxy = Open a socket to the host:port of the server
4187 * and create TLS/SSL connection with server and
4188 * with client. Then behave like mediator between
4189 * client and server over TLS/SSL.
4191 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4192 * with request to a parent proxy. Note that we'll be sending
4193 * forwarding the CFAIL message ourselves if connecting to the parent
4194 * fails, but we won't send a CSUCCEED message if it works,
4195 * since that would result in a double message (ours and the
4196 * parent's). After sending the request to the parent, we
4197 * must parse answer and send it to client. If connection
4198 * with server is established, we do TLS/SSL proxy. Otherwise
4199 * we send parent response to client and close connections.
4201 * here's the matrix:
4204 * +--------+--------+
4206 * 0 | create | SSL |
4207 * | w/path | proxy |
4208 * Forwarding +--------+--------+
4210 * 1 | create | proxy |
4211 * | w/url |+forward|
4212 * +--------+--------+
4216 #ifdef FEATURE_HTTPS_INSPECTION
4218 * Presetting SSL client and server flags
4220 if (http->ssl && !use_ssl_tunnel)
4222 http->client_ssl = 1;
4223 http->server_ssl = 1;
4227 http->client_ssl = 0;
4228 http->server_ssl = 0;
4232 #ifdef FEATURE_HTTPS_INSPECTION
4234 * Log the request unless we're https inspecting
4235 * in which case we don't have the path yet and
4236 * will log the request later.
4238 if (!client_use_ssl(csp))
4241 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4244 if (http->ssl && connect_port_is_forbidden(csp))
4246 const char *acceptable_connect_ports =
4247 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4248 assert(NULL != acceptable_connect_ports);
4249 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4250 "limit-connect{%s} doesn't allow CONNECT requests to %s",
4251 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4252 csp->action->flags |= ACTION_BLOCK;
4254 #ifdef FEATURE_HTTPS_INSPECTION
4255 http->client_ssl = 0;
4256 http->server_ssl = 0;
4261 * We have a request. Check if one of the crunchers wants it
4262 * unless the client wants to use TLS/SSL in which case we
4263 * haven't setup the TLS context yet and will send the crunch
4267 #ifdef FEATURE_HTTPS_INSPECTION
4268 !client_use_ssl(csp) &&
4270 crunch_response_triggered(csp, crunchers_all))
4273 * Yes. The client got the crunch response and we're done here.
4278 #ifdef FEATURE_HTTPS_INSPECTION
4279 if (client_use_ssl(csp) && !use_ssl_tunnel)
4283 * Creating a SSL proxy.
4285 * By sending the CSUCCEED message we're lying to the client as
4286 * the connection hasn't actually been established yet. We don't
4287 * establish the connection until we have seen and parsed the
4288 * encrypted client headers.
4290 if (write_socket_delayed(csp->cfd, CSUCCEED,
4291 strlen(CSUCCEED), get_write_delay(csp)) != 0)
4293 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4297 ret = create_client_ssl_connection(csp);
4300 log_error(LOG_LEVEL_ERROR,
4301 "Failed to open a secure connection with the client");
4304 if (JB_ERR_OK != process_encrypted_request(csp))
4306 close_client_ssl_connection(csp);
4310 * We have an encrypted request. Check if one of the crunchers now
4311 * wants it (for example because the previously invisible path was
4312 * required to match).
4314 if (crunch_response_triggered(csp, crunchers_all))
4317 * Yes. The client got the crunch response and we're done here.
4324 /* decide how to route the HTTP request */
4325 fwd = forward_url(csp, http);
4327 freez(csp->headers->first->str);
4328 build_request_line(csp, fwd, &csp->headers->first->str);
4330 log_applied_actions(csp->action);
4331 if (fwd->forward_host)
4333 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4334 fwd->forward_host, fwd->forward_port, http->hostport);
4338 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4341 /* here we connect to the server, gateway, or the forwarder */
4343 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4344 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4345 && socket_is_still_alive(csp->server_connection.sfd)
4346 && connection_destination_matches(&csp->server_connection, http, fwd))
4348 log_error(LOG_LEVEL_CONNECT,
4349 "Reusing server socket %d connected to %s. Total requests: %u.",
4350 csp->server_connection.sfd, csp->server_connection.host,
4351 csp->server_connection.requests_sent_total);
4355 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4357 #ifdef FEATURE_CONNECTION_SHARING
4358 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4359 #ifdef FEATURE_HTTPS_INSPECTION
4360 && !server_use_ssl(csp)
4364 remember_connection(&csp->server_connection);
4367 #endif /* def FEATURE_CONNECTION_SHARING */
4369 log_error(LOG_LEVEL_CONNECT,
4370 "Closing server socket %d connected to %s. Total requests: %u.",
4371 csp->server_connection.sfd, csp->server_connection.host,
4372 csp->server_connection.requests_sent_total);
4373 close_socket(csp->server_connection.sfd);
4375 mark_connection_closed(&csp->server_connection);
4377 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4380 * Connecting to destination server
4382 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4384 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4386 if (fwd->type != SOCKS_NONE)
4389 rsp = error_response(csp, "forwarding-failed");
4391 else if (errno == EINVAL)
4393 rsp = error_response(csp, "no-such-domain");
4397 rsp = error_response(csp, "connect-failed");
4400 /* Write the answer to the client */
4403 send_crunch_response(csp, rsp);
4407 * Temporary workaround to prevent already-read client
4408 * bodies from being parsed as new requests. For now we
4409 * err on the safe side and throw all the following
4410 * requests under the bus, even if no client body has been
4411 * buffered. A compliant client will repeat the dropped
4412 * requests on an untainted connection.
4414 * The proper fix is to discard the no longer needed
4415 * client body in the buffer (if there is one) and to
4416 * continue parsing the bytes that follow.
4418 #ifdef FEATURE_HTTPS_INSPECTION
4419 close_client_ssl_connection(csp);
4421 drain_and_close_socket(csp->cfd);
4422 csp->cfd = JB_INVALID_SOCKET;
4427 #ifdef FEATURE_HTTPS_INSPECTION
4429 * Creating TLS/SSL connections with destination server or parent
4430 * proxy. If forwarding is enabled, we must send client request to
4431 * parent proxy and receive, parse and resend parent proxy answer.
4433 if (http->ssl && !use_ssl_tunnel)
4435 if (fwd->forward_host != NULL)
4437 char server_response[BUFFER_SIZE];
4440 char *hdr = list_to_text(csp->headers);
4441 memset(server_response, 0, sizeof(server_response));
4445 log_error(LOG_LEVEL_FATAL,
4446 "Out of memory parsing client header");
4448 list_remove_all(csp->headers);
4451 * Sending client's CONNECT request to the parent proxy
4453 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4459 log_error(LOG_LEVEL_CONNECT,
4460 "Sending request headers to: %s failed", http->hostport);
4461 mark_server_socket_tainted(csp);
4462 close_client_ssl_connection(csp);
4466 /* Waiting for parent proxy server response */
4467 len = read_socket(csp->server_connection.sfd, server_response,
4468 sizeof(server_response)-1);
4472 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4473 "server on socket %d.", csp->server_connection.sfd);
4475 rsp = error_response(csp, "no-server-data");
4478 send_crunch_response(csp, rsp);
4480 mark_server_socket_tainted(csp);
4481 close_client_ssl_connection(csp);
4486 * Test if the connection to the destination server was
4487 * established successfully by the parent proxy.
4489 if (!tunnel_established_successfully(server_response, (unsigned int)len))
4491 log_error(LOG_LEVEL_ERROR,
4492 "The forwarder %s failed to establish a connection with %s",
4493 fwd->forward_host, http->host);
4494 rsp = error_response(csp, "connect-failed");
4497 send_crunch_response(csp, rsp);
4499 mark_server_socket_tainted(csp);
4500 close_client_ssl_connection(csp);
4503 } /* -END- if (fwd->forward_host != NULL) */
4506 * We can now create the TLS/SSL connection with the destination server.
4508 int ret = create_server_ssl_connection(csp);
4511 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4512 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4515 * If the server certificate is invalid, we must inform
4516 * the client and then close connection to the client.
4518 ssl_send_certificate_error(csp);
4519 close_client_and_server_ssl_connections(csp);
4522 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4523 || csp->server_cert_verification_result == SSL_CERT_VALID)
4526 * The TLS/SSL connection wasn't created but an invalid
4527 * certificate wasn't detected. Report it as connection
4530 rsp = error_response(csp, "connect-failed");
4533 send_crunch_response(csp, rsp);
4535 close_client_and_server_ssl_connections(csp);
4539 }/* -END- if (http->ssl) */
4540 #endif /* def FEATURE_HTTPS_INSPECTION */
4542 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4543 save_connection_destination(csp->server_connection.sfd,
4544 http, fwd, &csp->server_connection);
4545 csp->server_connection.keep_alive_timeout =
4546 (unsigned)csp->config->keep_alive_timeout;
4548 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4550 csp->server_connection.requests_sent_total++;
4552 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4554 /* Client headers have been sent optimistically */
4555 assert(csp->headers->last == NULL);
4557 else if (http->ssl == 0 || (fwd->forward_host
4558 #ifdef FEATURE_HTTPS_INSPECTION
4563 if (send_http_request(csp))
4565 rsp = error_response(csp, "connect-failed");
4568 send_crunch_response(csp, rsp);
4576 * Using old solution with SSL tunnel or new solution with SSL proxy
4578 list_remove_all(csp->headers);
4579 #ifdef FEATURE_HTTPS_INSPECTION
4584 * We're running an SSL tunnel and we're not forwarding,
4585 * so just ditch the client headers, send the "connect succeeded"
4586 * message to the client, flush the rest, and get out of the way.
4588 if (write_socket_delayed(csp->cfd, CSUCCEED,
4589 strlen(CSUCCEED), get_write_delay(csp)))
4594 #ifdef FEATURE_HTTPS_INSPECTION
4598 * If server certificate has been verified and is invalid,
4599 * we must inform the client and then close the connection
4600 * with client and server.
4602 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4603 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4605 ssl_send_certificate_error(csp);
4606 close_client_and_server_ssl_connections(csp);
4609 if (send_https_request(csp))
4611 rsp = error_response(csp, "connect-failed");
4614 send_crunch_response(csp, rsp);
4616 close_client_and_server_ssl_connections(csp);
4620 #endif /* def FEATURE_HTTPS_INSPECTION */
4621 clear_iob(csp->client_iob);
4622 }/* -END- else ... if (http->ssl == 1) */
4624 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4626 /* XXX: should the time start earlier for optimistically sent data? */
4627 csp->server_connection.request_sent = time(NULL);
4629 handle_established_connection(csp);
4630 freez(csp->receive_buffer);
4635 /*********************************************************************
4637 * Function : fuzz_server_response
4639 * Description : Treat the input as a whole server response.
4642 * 1 : csp = Current client state (buffers, headers, etc...)
4643 * 2 : fuzz_input_file = File to read the input from.
4647 *********************************************************************/
4648 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4650 static struct forward_spec fwd; /* Zero'd due to being static */
4653 if (strcmp(fuzz_input_file, "-") == 0)
4655 /* XXX: Doesn't work yet. */
4656 csp->server_connection.sfd = 0;
4660 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4661 if (csp->server_connection.sfd == -1)
4663 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4668 csp->content_type |= CT_GIF;
4669 csp->action->flags |= ACTION_DEANIMATE;
4670 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4672 csp->http->path = strdup_or_die("/");
4673 csp->http->host = strdup_or_die("fuzz.example.org");
4674 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4675 /* Prevent client socket monitoring */
4676 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4677 csp->flags |= CSP_FLAG_CHUNKED;
4679 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4680 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4682 csp->content_type |= CT_DECLARED|CT_GIF;
4684 csp->config->socket_timeout = 0;
4686 cgi_init_error_messages();
4688 handle_established_connection(csp);
4689 freez(csp->receive_buffer);
4696 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4697 /*********************************************************************
4699 * Function : prepare_csp_for_next_request
4701 * Description : Put the csp in a mostly vergin state.
4704 * 1 : csp = Current client state (buffers, headers, etc...)
4708 *********************************************************************/
4709 static void prepare_csp_for_next_request(struct client_state *csp)
4711 csp->content_type = 0;
4712 csp->content_length = 0;
4713 csp->expected_content_length = 0;
4714 csp->expected_client_content_length = 0;
4715 list_remove_all(csp->headers);
4716 clear_iob(csp->iob);
4717 freez(csp->error_message);
4718 free_http_request(csp->http);
4719 destroy_list(csp->headers);
4720 #ifdef FEATURE_HTTPS_INSPECTION
4721 destroy_list(csp->https_headers);
4723 destroy_list(csp->tags);
4724 #ifdef FEATURE_CLIENT_TAGS
4725 destroy_list(csp->client_tags);
4726 freez(csp->client_address);
4728 free_current_action(csp->action);
4729 if (NULL != csp->fwd)
4731 unload_forward_spec(csp->fwd);
4734 /* XXX: Store per-connection flags someplace else. */
4735 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4736 #ifdef FEATURE_TOGGLE
4737 if (global_toggle_state)
4738 #endif /* def FEATURE_TOGGLE */
4740 csp->flags |= CSP_FLAG_TOGGLED_ON;
4743 if (csp->client_iob->eod > csp->client_iob->cur)
4745 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4746 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4748 assert(bytes_to_shift > 0);
4749 assert(data_length > 0);
4751 log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4752 data_length, bytes_to_shift);
4753 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4754 csp->client_iob->cur = csp->client_iob->buf;
4755 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4756 csp->client_iob->eod = csp->client_iob->buf + data_length;
4757 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4759 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4764 * We mainly care about resetting client_iob->cur so we don't
4765 * waste buffer space at the beginning and don't mess up the
4766 * request restoration done by cgi_show_request().
4768 * Freeing the buffer itself isn't technically necessary,
4769 * but makes debugging more convenient.
4771 clear_iob(csp->client_iob);
4774 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4777 /*********************************************************************
4781 * Description : This is little more than chat. We only "serve" to
4782 * to close (or remember) any socket that chat may have
4786 * 1 : csp = Current client state (buffers, headers, etc...)
4790 *********************************************************************/
4791 static void serve(struct client_state *csp)
4793 int config_file_change_detected = 0; /* Only used for debugging */
4794 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4795 #ifdef FEATURE_CONNECTION_SHARING
4796 static int monitor_thread_running = 0;
4797 #endif /* def FEATURE_CONNECTION_SHARING */
4798 int continue_chatting = 0;
4800 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4801 csp->ip_addr_str, csp->cfd);
4805 unsigned int latency;
4807 #ifdef FEATURE_HTTPS_INSPECTION
4808 if (continue_chatting && client_use_ssl(csp))
4810 continue_https_chat(csp);
4819 * If the request has been crunched,
4820 * the calculated latency is zero.
4822 latency = (unsigned)(csp->server_connection.response_received -
4823 csp->server_connection.request_sent) / 2;
4825 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4826 && (csp->flags & CSP_FLAG_CRUNCHED)
4827 && (csp->expected_client_content_length != 0))
4829 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4830 log_error(LOG_LEVEL_CONNECT,
4831 "Tainting client socket %d due to unread data.", csp->cfd);
4834 continue_chatting = (csp->config->feature_flags
4835 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4836 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4837 && (csp->cfd != JB_INVALID_SOCKET)
4838 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4839 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4840 || (csp->flags & CSP_FLAG_CHUNKED));
4842 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4843 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4845 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4847 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4849 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4850 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4851 || !socket_is_still_alive(csp->server_connection.sfd)
4852 || !(latency < csp->server_connection.keep_alive_timeout))
4854 log_error(LOG_LEVEL_CONNECT,
4855 "Closing server socket %d connected to %s. "
4856 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4857 csp->server_connection.sfd, (csp->server_connection.host != NULL) ?
4858 csp->server_connection.host : csp->http->host,
4859 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4860 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4861 socket_is_still_alive(csp->server_connection.sfd),
4862 csp->server_connection.keep_alive_timeout);
4863 #ifdef FEATURE_CONNECTION_SHARING
4864 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4866 forget_connection(csp->server_connection.sfd);
4868 #endif /* def FEATURE_CONNECTION_SHARING */
4869 #ifdef FEATURE_HTTPS_INSPECTION
4870 close_server_ssl_connection(csp);
4872 close_socket(csp->server_connection.sfd);
4873 mark_connection_closed(&csp->server_connection);
4874 #ifdef FEATURE_HTTPS_INSPECTION
4875 if (continue_chatting && client_use_ssl(csp))
4878 * Close the client socket as well as Privoxy currently
4879 * can't establish a new server connection when the client
4880 * socket is reused and would drop the connection in
4881 * continue_https_chat() anyway.
4883 continue_chatting = 0;
4884 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4885 log_error(LOG_LEVEL_CONNECT,
4886 "Client socket %d is no longer usable. "
4887 "The server socket has been closed.", csp->cfd);
4893 if (continue_chatting && any_loaded_file_changed(csp))
4895 continue_chatting = 0;
4896 config_file_change_detected = 1;
4898 #ifdef FEATURE_HTTPS_INSPECTION
4899 if (continue_chatting && client_use_ssl(csp) &&
4900 csp->ssl_with_client_is_opened == 0)
4902 continue_chatting = 0;
4903 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4904 "The TLS session has been terminated.", csp->cfd);
4908 if (continue_chatting)
4910 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4911 && socket_is_still_alive(csp->cfd))
4913 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4914 "pipelined on socket %d and the socket is still alive.",
4915 csp->requests_received_total+1, csp->cfd);
4916 prepare_csp_for_next_request(csp);
4920 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4922 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4924 log_error(LOG_LEVEL_CONNECT,
4925 "Waiting for the next client request on socket %d. "
4926 "Keeping the server socket %d to %s open.",
4927 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4931 log_error(LOG_LEVEL_CONNECT,
4932 "Waiting for the next client request on socket %d. "
4933 "No server socket to keep open.", csp->cfd);
4937 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4938 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4939 && socket_is_still_alive(csp->cfd))
4941 log_error(LOG_LEVEL_CONNECT,
4942 "Data arrived in time on client socket %d. Requests so far: %u",
4943 csp->cfd, csp->requests_received_total);
4944 prepare_csp_for_next_request(csp);
4948 #ifdef FEATURE_CONNECTION_SHARING
4949 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4950 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4951 && (socket_is_still_alive(csp->server_connection.sfd))
4952 #ifdef FEATURE_HTTPS_INSPECTION
4953 && !server_use_ssl(csp)
4957 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4959 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4964 remember_connection(&csp->server_connection);
4965 csp->server_connection.sfd = JB_INVALID_SOCKET;
4966 drain_and_close_socket(csp->cfd);
4967 csp->cfd = JB_INVALID_SOCKET;
4968 privoxy_mutex_lock(&connection_reuse_mutex);
4969 if (!monitor_thread_running)
4971 monitor_thread_running = 1;
4972 privoxy_mutex_unlock(&connection_reuse_mutex);
4973 wait_for_alive_connections();
4974 privoxy_mutex_lock(&connection_reuse_mutex);
4975 monitor_thread_running = 0;
4977 privoxy_mutex_unlock(&connection_reuse_mutex);
4979 #endif /* def FEATURE_CONNECTION_SHARING */
4983 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4985 log_error(LOG_LEVEL_CONNECT,
4986 "Closing server socket %d connected to %s. Keep-alive: %u. "
4987 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4988 "Configuration file change detected: %u",
4989 csp->server_connection.sfd, csp->server_connection.host,
4990 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4991 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4992 socket_is_still_alive(csp->server_connection.sfd),
4993 csp->server_connection.keep_alive_timeout,
4994 config_file_change_detected);
4996 } while (continue_chatting);
5000 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
5002 if (csp->cfd != JB_INVALID_SOCKET)
5004 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
5005 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
5006 "Configuration file change detected: %u. Requests received: %u.",
5007 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
5008 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
5009 config_file_change_detected, csp->requests_received_total);
5010 #ifdef FEATURE_HTTPS_INSPECTION
5011 close_client_ssl_connection(csp);
5013 drain_and_close_socket(csp->cfd);
5016 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5018 #ifdef FEATURE_CONNECTION_SHARING
5019 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5021 forget_connection(csp->server_connection.sfd);
5023 #endif /* def FEATURE_CONNECTION_SHARING */
5025 #ifdef FEATURE_HTTPS_INSPECTION
5026 close_server_ssl_connection(csp);
5027 #endif /* def FEATURE_HTTPS_INSPECTION */
5029 close_socket(csp->server_connection.sfd);
5032 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
5033 mark_connection_closed(&csp->server_connection);
5036 free_csp_resources(csp);
5038 csp->flags &= ~CSP_FLAG_ACTIVE;
5044 /*********************************************************************
5046 * Function : server_thread
5048 * Description : We only exist to call `serve' in a threaded environment.
5051 * 1 : data = Current client state (buffers, headers, etc...)
5053 * Returns : Always 0.
5055 *********************************************************************/
5056 static int32 server_thread(void *data)
5058 serve((struct client_state *) data);
5065 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5066 /*********************************************************************
5070 * Description : Print usage info & exit.
5072 * Parameters : Pointer to argv[0] for identifying ourselves
5076 *********************************************************************/
5077 static void usage(const char *name)
5079 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
5080 "Usage: %s [--config-test] "
5083 #endif /* defined(unix) */
5086 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
5087 #endif /* defined(unix) */
5088 "[--version] [configfile]\n",
5092 show_fuzz_usage(name);
5095 printf("Aborting\n");
5100 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5103 #ifdef MUTEX_LOCKS_AVAILABLE
5104 /*********************************************************************
5106 * Function : privoxy_mutex_lock
5108 * Description : Locks a mutex.
5111 * 1 : mutex = The mutex to lock.
5113 * Returns : Void. May exit in case of errors.
5115 *********************************************************************/
5116 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5118 #ifdef FEATURE_PTHREAD
5119 int err = pthread_mutex_lock(mutex);
5122 if (mutex != &log_mutex)
5124 log_error(LOG_LEVEL_FATAL,
5125 "Mutex locking failed: %s.\n", strerror(err));
5130 EnterCriticalSection(mutex);
5131 #endif /* def FEATURE_PTHREAD */
5135 /*********************************************************************
5137 * Function : privoxy_mutex_unlock
5139 * Description : Unlocks a mutex.
5142 * 1 : mutex = The mutex to unlock.
5144 * Returns : Void. May exit in case of errors.
5146 *********************************************************************/
5147 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5149 #ifdef FEATURE_PTHREAD
5150 int err = pthread_mutex_unlock(mutex);
5153 if (mutex != &log_mutex)
5155 log_error(LOG_LEVEL_FATAL,
5156 "Mutex unlocking failed: %s.\n", strerror(err));
5161 LeaveCriticalSection(mutex);
5162 #endif /* def FEATURE_PTHREAD */
5166 /*********************************************************************
5168 * Function : privoxy_mutex_init
5170 * Description : Prepares a mutex.
5173 * 1 : mutex = The mutex to initialize.
5175 * Returns : Void. May exit in case of errors.
5177 *********************************************************************/
5178 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5180 #ifdef FEATURE_PTHREAD
5181 int err = pthread_mutex_init(mutex, 0);
5184 printf("Fatal error. Mutex initialization failed: %s.\n",
5189 InitializeCriticalSection(mutex);
5190 #endif /* def FEATURE_PTHREAD */
5192 #endif /* def MUTEX_LOCKS_AVAILABLE */
5194 /*********************************************************************
5196 * Function : initialize_mutexes
5198 * Description : Prepares mutexes if mutex support is available.
5202 * Returns : Void, exits in case of errors.
5204 *********************************************************************/
5205 static void initialize_mutexes(void)
5207 #ifdef MUTEX_LOCKS_AVAILABLE
5209 * Prepare global mutex semaphores
5212 #ifdef FEATURE_HTTPS_INSPECTION
5213 privoxy_mutex_init(&certificate_mutex);
5214 privoxy_mutex_init(&ssl_init_mutex);
5217 privoxy_mutex_init(&log_mutex);
5218 privoxy_mutex_init(&log_init_mutex);
5219 privoxy_mutex_init(&connection_reuse_mutex);
5220 #ifdef FEATURE_EXTERNAL_FILTERS
5221 privoxy_mutex_init(&external_filter_mutex);
5223 #ifdef FEATURE_CLIENT_TAGS
5224 privoxy_mutex_init(&client_tags_mutex);
5226 #ifdef FEATURE_EXTENDED_STATISTICS
5227 privoxy_mutex_init(&filter_statistics_mutex);
5228 privoxy_mutex_init(&block_statistics_mutex);
5232 * XXX: The assumptions below are a bit naive
5233 * and can cause locks that aren't necessary.
5235 * For example older FreeBSD versions (< 6.x?)
5236 * have no gethostbyname_r, but gethostbyname is
5239 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5240 privoxy_mutex_init(&resolver_mutex);
5241 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5243 * XXX: should we use a single mutex for
5244 * localtime() and gmtime() as well?
5246 #ifndef HAVE_GMTIME_R
5247 privoxy_mutex_init(&gmtime_mutex);
5248 #endif /* ndef HAVE_GMTIME_R */
5250 #ifndef HAVE_LOCALTIME_R
5251 privoxy_mutex_init(&localtime_mutex);
5252 #endif /* ndef HAVE_GMTIME_R */
5254 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5255 privoxy_mutex_init(&rand_mutex);
5256 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5258 #endif /* def MUTEX_LOCKS_AVAILABLE */
5261 /*********************************************************************
5265 * Description : Load the config file and start the listen loop.
5266 * This function is a lot more *sane* with the `load_config'
5267 * and `listen_loop' functions; although it stills does
5268 * a *little* too much for my taste.
5271 * 1 : argc = Number of parameters (including $0).
5272 * 2 : argv = Array of (char *)'s to the parameters.
5274 * Returns : 1 if : can't open config file, unrecognized directive,
5275 * stats requested in multi-thread mode, can't open the
5276 * log file, can't open the jar file, listen port is invalid,
5277 * any load fails, and can't bind port.
5279 * Else main never returns, the process must be signaled
5280 * to terminate execution. Or, on Windows, use the
5281 * "File", "Exit" menu option.
5283 *********************************************************************/
5285 int real_main(int argc, char **argv)
5287 int main(int argc, char **argv)
5291 int do_config_test = 0;
5292 #ifndef HAVE_ARC4RANDOM
5293 unsigned int random_seed;
5296 struct passwd *pw = NULL;
5297 struct group *grp = NULL;
5299 char *pre_chroot_nslookup_to_load_resolver = NULL;
5302 char *fuzz_input_type = NULL;
5303 char *fuzz_input_file = NULL;
5310 #if !defined(_WIN32)
5317 /* Prepare mutexes if supported and necessary. */
5318 initialize_mutexes();
5320 /* Enable logging until further notice. */
5324 * Parse the command line arguments
5326 * XXX: simply printing usage information in case of
5327 * invalid arguments isn't particularly user friendly.
5329 while (++argc_pos < argc)
5332 /* Check to see if the service must be installed or uninstalled */
5333 if (strncmp(argv[argc_pos], "--install", 9) == 0)
5335 const char *pName = argv[argc_pos] + 9;
5338 exit((install_service(pName)) ? 0 : 1);
5340 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5342 const char *pName = argv[argc_pos] + 11;
5345 exit((uninstall_service(pName)) ? 0 : 1);
5347 else if (strcmp(argv[argc_pos], "--service") == 0)
5349 bRunAsService = TRUE;
5350 w32_set_service_cwd();
5351 atexit(w32_service_exit_notify);
5354 #endif /* defined(_WIN32) */
5357 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5359 if (strcmp(argv[argc_pos], "--help") == 0)
5364 else if (strcmp(argv[argc_pos], "--version") == 0)
5366 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5372 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5374 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5378 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5380 if (++argc_pos == argc) usage(argv[0]);
5381 pidfile = strdup_or_die(argv[argc_pos]);
5384 else if (strcmp(argv[argc_pos], "--user") == 0)
5389 if (++argc_pos == argc) usage(argv[argc_pos]);
5391 user_arg = strdup_or_die(argv[argc_pos]);
5392 group_name = strchr(user_arg, '.');
5393 if (NULL != group_name)
5395 /* Nul-terminate the user name */
5398 /* Skip the former delimiter to actually reach the group name */
5401 grp = getgrnam(group_name);
5404 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5407 pw = getpwnam(user_arg);
5410 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5416 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5418 if (++argc_pos == argc) usage(argv[0]);
5419 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5422 else if (strcmp(argv[argc_pos], "--chroot") == 0)
5426 #endif /* defined(unix) */
5428 else if (strcmp(argv[argc_pos], "--config-test") == 0)
5433 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5436 if (argc < argc_pos + 2) usage(argv[0]);
5437 fuzz_input_type = argv[argc_pos];
5439 fuzz_input_file = argv[argc_pos];
5441 else if (strcmp(argv[argc_pos], "--stfu") == 0)
5443 set_debug_level(LOG_LEVEL_STFU);
5446 else if (argc_pos + 1 != argc)
5449 * This is neither the last command line
5450 * option, nor was it recognized before,
5451 * therefore it must be invalid.
5457 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5459 configfile = argv[argc_pos];
5462 } /* -END- while (more arguments) */
5464 show_version(Argv[0]);
5467 if (*configfile != '/')
5469 char cwd[BUFFER_SIZE];
5471 size_t abs_file_size;
5473 /* make config-filename absolute here */
5474 if (NULL == getcwd(cwd, sizeof(cwd)))
5476 perror("failed to get current working directory");
5480 basedir = strdup_or_die(cwd);
5482 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5483 abs_file = malloc_or_die(abs_file_size);
5484 strlcpy(abs_file, basedir, abs_file_size);
5485 strlcat(abs_file, "/", abs_file_size);
5486 strlcat(abs_file, configfile, abs_file_size);
5487 configfile = abs_file;
5489 #endif /* defined unix */
5493 clients->next = NULL;
5495 /* XXX: factor out initialising after the next stable release. */
5500 #ifndef HAVE_ARC4RANDOM
5501 random_seed = (unsigned int)time(NULL);
5503 srandom(random_seed);
5506 #endif /* ifdef HAVE_RANDOM */
5507 #endif /* ifndef HAVE_ARC4RANDOM */
5510 * Unix signal handling
5512 * Catch the abort, interrupt and terminate signals for a graceful exit
5513 * Catch the hangup signal so the errlog can be reopened.
5515 * Ignore the broken pipe signal as connection failures
5516 * are handled when and where they occur without relying
5519 #if !defined(_WIN32)
5522 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5524 for (idx = 0; idx < SZ(catched_signals); idx++)
5526 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5527 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5529 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5530 #endif /* ifdef sun */
5532 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5536 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5538 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5542 #else /* ifdef _WIN32 */
5543 # ifdef _WIN_CONSOLE
5545 * We *are* in a windows console app.
5546 * Print a verbose messages about FAQ's and such
5548 printf("%s", win32_blurb);
5549 # endif /* def _WIN_CONSOLE */
5550 #endif /* def _WIN32 */
5553 if (fuzz_input_type != NULL)
5555 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5557 log_error(LOG_LEVEL_FATAL,
5558 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5559 "Various data structures are static which is unsafe when using threads.");
5564 exit(NULL == load_config());
5567 /* Initialize the CGI subsystem */
5568 cgi_init_error_messages();
5571 * If running on unix and without the --no-daemon
5572 * option, become a daemon. I.e. fork, detach
5573 * from tty and get process group leadership
5582 if (pid < 0) /* error */
5587 else if (pid != 0) /* parent */
5592 * must check for errors
5593 * child died due to missing files aso
5596 wpid = waitpid(pid, &status, WNOHANG);
5608 * stderr (fd 2) will be closed later on,
5609 * when the config file has been parsed.
5615 * Reserve fd 0 and 1 to prevent abort() and friends
5616 * from sending stuff to the clients or servers.
5618 fd = open("/dev/null", O_RDONLY);
5621 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5625 if (dup2(fd, 0) == -1)
5627 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5631 fd = open("/dev/null", O_WRONLY);
5634 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5638 if (dup2(fd, 1) == -1)
5640 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5645 #ifdef FEATURE_EXTERNAL_FILTERS
5646 for (fd = 0; fd < 3; fd++)
5648 mark_socket_for_close_on_execute(fd);
5652 if (chdir("/") != 0)
5654 log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5657 } /* -END- if (daemon_mode) */
5660 * As soon as we have written the PID file, we can switch
5661 * to the user and group ID indicated by the --user option
5663 if (pidfile != NULL)
5665 write_pid_file(pidfile);
5669 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5671 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5675 if (setgroups(1, &grp->gr_gid))
5677 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5680 else if (initgroups(pw->pw_name, pw->pw_gid))
5682 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5688 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5690 /* Read the time zone file from /etc before doing chroot. */
5692 if (NULL != pre_chroot_nslookup_to_load_resolver
5693 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5695 /* Initialize resolver library. */
5696 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5698 if (chroot(pw->pw_dir) < 0)
5700 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5704 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5707 if (setuid(pw->pw_uid))
5709 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5713 char putenv_dummy[64];
5715 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5716 if (putenv(putenv_dummy) != 0)
5718 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5721 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5722 if (putenv(putenv_dummy) != 0)
5724 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5730 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5733 #endif /* defined unix */
5736 /* This will be FALSE unless the command line specified --service
5740 /* Yup, so now we must attempt to establish a connection
5741 * with the service dispatcher. This will only work if this
5742 * process was launched by the service control manager to
5743 * actually run as a service. If this isn't the case, i've
5744 * known it take around 30 seconds or so for the call to return.
5747 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5748 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5750 /* Service has run, and at this point is now being stopped, so just return */
5755 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5757 /* An error occurred. Usually it's because --service was wrongly specified
5758 * and we were unable to connect to the Service Control Dispatcher because
5759 * it wasn't expecting us and is therefore not listening.
5761 * For now, just continue below to call the listen_loop function.
5764 #endif /* def _WIN32 */
5774 /*********************************************************************
5776 * Function : bind_port_helper
5778 * Description : Bind the listen port. Handles logging, and aborts
5782 * 1 : haddr = Host address to bind to. Use NULL to bind to
5784 * 2 : hport = Specifies port to bind to.
5785 * 3 : backlog = Listen backlog.
5787 * Returns : Port that was opened.
5789 *********************************************************************/
5790 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5795 result = bind_port(haddr, hport, backlog, &bfd);
5799 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5803 log_error(LOG_LEVEL_FATAL,
5804 "can't bind to %s:%d: There may be another Privoxy "
5805 "or some other proxy running on port %d",
5806 bind_address, hport, hport);
5809 log_error(LOG_LEVEL_FATAL,
5810 "can't bind to %s:%d: The hostname is not resolvable",
5811 bind_address, hport);
5814 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5815 bind_address, hport);
5818 /* shouldn't get here */
5819 return JB_INVALID_SOCKET;
5824 if (bfd >= FD_SETSIZE)
5826 log_error(LOG_LEVEL_FATAL,
5827 "Bind socket number too high to use select(): %d >= %d",
5835 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5840 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5848 /*********************************************************************
5850 * Function : bind_ports_helper
5852 * Description : Bind the listen ports. Handles logging, and aborts
5856 * 1 : config = Privoxy configuration. Specifies ports
5858 * 2 : sockets = Preallocated array of opened sockets
5859 * corresponding to specification in config.
5860 * All non-opened sockets will be set to
5861 * JB_INVALID_SOCKET.
5863 * Returns : Nothing. Inspect sockets argument.
5865 *********************************************************************/
5866 static void bind_ports_helper(struct configuration_spec * config,
5867 jb_socket sockets[])
5871 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5873 if (config->hport[i])
5875 sockets[i] = bind_port_helper(config->haddr[i],
5876 config->hport[i], config->listen_backlog);
5877 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5878 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5880 struct accept_filter_arg af_options;
5881 bzero(&af_options, sizeof(af_options));
5882 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5883 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5884 sizeof(af_options)))
5886 log_error(LOG_LEVEL_ERROR,
5887 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5894 sockets[i] = JB_INVALID_SOCKET;
5897 config->need_bind = 0;
5901 /*********************************************************************
5903 * Function : close_ports_helper
5905 * Description : Close listenings ports.
5908 * 1 : sockets = Array of opened and non-opened sockets to
5909 * close. All sockets will be set to
5910 * JB_INVALID_SOCKET.
5912 * Returns : Nothing.
5914 *********************************************************************/
5915 static void close_ports_helper(jb_socket sockets[])
5919 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5921 if (JB_INVALID_SOCKET != sockets[i])
5923 close_socket(sockets[i]);
5925 sockets[i] = JB_INVALID_SOCKET;
5931 /* Without this simple workaround we get this compiler warning from _beginthread
5932 * warning C4028: formal parameter 1 different from declaration
5934 void w32_service_listen_loop(void *p)
5938 #endif /* def _WIN32 */
5941 /*********************************************************************
5943 * Function : listen_loop
5945 * Description : bind the listen port and enter a "FOREVER" listening loop.
5951 *********************************************************************/
5952 static void listen_loop(void)
5954 struct client_states *csp_list = NULL;
5955 struct client_state *csp = NULL;
5956 jb_socket bfds[MAX_LISTENING_SOCKETS];
5957 struct configuration_spec *config;
5958 unsigned int active_threads = 0;
5959 #if defined(FEATURE_PTHREAD)
5960 pthread_attr_t attrs;
5962 pthread_attr_init(&attrs);
5963 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5966 config = load_config();
5968 #ifdef FEATURE_CONNECTION_SHARING
5970 * XXX: Should be relocated once it no
5971 * longer needs to emit log messages.
5973 initialize_reusable_connections();
5974 #endif /* def FEATURE_CONNECTION_SHARING */
5976 bind_ports_helper(config, bfds);
5978 #ifdef FEATURE_GRACEFUL_TERMINATION
5979 while (!g_terminate)
5984 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
5985 while (waitpid(-1, NULL, WNOHANG) > 0)
5987 /* zombie children */
5989 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5992 * Free data that was used by died threads
5994 active_threads = sweep();
5998 * Re-open the errlog after HUP signal
6000 if (received_hup_signal)
6002 if (NULL != config->logfile)
6004 init_error_log(Argv[0], config->logfile);
6006 received_hup_signal = 0;
6010 csp_list = zalloc_or_die(sizeof(*csp_list));
6011 csp = &csp_list->csp;
6013 log_error(LOG_LEVEL_CONNECT,
6014 "Waiting for the next client connection. Currently active threads: %u",
6018 * This config may be outdated, but for accept_connection()
6019 * it's fresh enough.
6021 csp->config = config;
6023 if (!accept_connection(csp, bfds))
6025 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
6030 csp->flags |= CSP_FLAG_ACTIVE;
6031 csp->server_connection.sfd = JB_INVALID_SOCKET;
6033 csp->config = config = load_config();
6035 if (config->need_bind)
6038 * Since we were listening to the "old port", we will not see
6039 * a "listen" param change until the next request. So, at
6040 * least 1 more request must be made for us to find the new
6041 * setting. I am simply closing the old socket and binding the
6044 * Which-ever is correct, we will serve 1 more page via the
6045 * old settings. This should probably be a "show-status"
6046 * request. This should not be a so common of an operation
6047 * that this will hurt people's feelings.
6050 close_ports_helper(bfds);
6052 bind_ports_helper(config, bfds);
6055 #ifdef FEATURE_TOGGLE
6056 if (global_toggle_state)
6057 #endif /* def FEATURE_TOGGLE */
6059 csp->flags |= CSP_FLAG_TOGGLED_ON;
6062 if (run_loader(csp))
6064 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
6065 /* Never get here - LOG_LEVEL_FATAL causes program exit */
6069 if (block_acl(NULL,csp))
6071 log_error(LOG_LEVEL_CONNECT,
6072 "Connection from %s on %s (socket %d) dropped due to ACL",
6073 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
6074 close_socket(csp->cfd);
6075 freez(csp->ip_addr_str);
6076 freez(csp->listen_addr_str);
6080 #endif /* def FEATURE_ACL */
6082 if ((0 != config->max_client_connections)
6083 && (active_threads >= config->max_client_connections))
6085 log_error(LOG_LEVEL_CONNECT,
6086 "Rejecting connection from %s. Maximum number of connections reached.",
6088 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6089 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6090 close_socket(csp->cfd);
6091 freez(csp->ip_addr_str);
6092 freez(csp->listen_addr_str);
6097 /* add it to the list of clients */
6098 csp_list->next = clients->next;
6099 clients->next = csp_list;
6101 if (config->multi_threaded)
6105 /* this is a switch () statement in the C preprocessor - ugh */
6106 #undef SELECTED_ONE_OPTION
6108 /* Use Pthreads in preference to native code */
6109 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6110 #define SELECTED_ONE_OPTION
6112 pthread_t the_thread;
6115 ret = pthread_create(&the_thread, &attrs,
6116 (void * (*)(void *))serve, csp);
6117 child_id = ret ? -1 : 0;
6121 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
6122 #define SELECTED_ONE_OPTION
6123 child_id = _beginthread(
6124 (void (*)(void *))serve,
6129 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6130 #define SELECTED_ONE_OPTION
6132 thread_id tid = spawn_thread
6133 (server_thread, "server", B_NORMAL_PRIORITY, csp);
6135 if ((tid >= 0) && (resume_thread(tid) == B_OK))
6137 child_id = (int) tid;
6146 #if !defined(SELECTED_ONE_OPTION)
6149 /* This block is only needed when using fork().
6150 * When using threads, the server thread was
6151 * created and run by the call to _beginthread().
6153 if (child_id == 0) /* child */
6156 #ifdef FEATURE_TOGGLE
6157 int inherited_toggle_state = global_toggle_state;
6158 #endif /* def FEATURE_TOGGLE */
6163 * If we've been toggled or we've blocked the request, tell Mom
6166 #ifdef FEATURE_TOGGLE
6167 if (inherited_toggle_state != global_toggle_state)
6169 rc |= RC_FLAG_TOGGLED;
6171 #endif /* def FEATURE_TOGGLE */
6173 #ifdef FEATURE_STATISTICS
6174 if (csp->flags & CSP_FLAG_REJECTED)
6176 rc |= RC_FLAG_BLOCKED;
6178 #endif /* ndef FEATURE_STATISTICS */
6182 else if (child_id > 0) /* parent */
6184 /* in a fork()'d environment, the parent's
6185 * copy of the client socket and the CSP
6189 #if !defined(_WIN32) && !defined(__CYGWIN__)
6191 wait(&child_status);
6194 * Evaluate child's return code: If the child has
6195 * - been toggled, toggle ourselves
6196 * - blocked its request, bump up the stats counter
6199 #ifdef FEATURE_TOGGLE
6200 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6202 global_toggle_state = !global_toggle_state;
6204 #endif /* def FEATURE_TOGGLE */
6206 #ifdef FEATURE_STATISTICS
6208 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6212 #endif /* def FEATURE_STATISTICS */
6214 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6215 close_socket(csp->cfd);
6216 csp->flags &= ~CSP_FLAG_ACTIVE;
6220 #undef SELECTED_ONE_OPTION
6221 /* end of cpp switch () */
6226 * Spawning the child failed, assume it's because
6227 * there are too many children running already.
6228 * XXX: If you assume ...
6230 log_error(LOG_LEVEL_ERROR,
6231 "Unable to take any additional connections: %E. Active threads: %u",
6233 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6234 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6235 close_socket(csp->cfd);
6236 csp->flags &= ~CSP_FLAG_ACTIVE;
6245 #if defined(FEATURE_PTHREAD)
6246 pthread_attr_destroy(&attrs);
6249 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6251 #ifdef FEATURE_GRACEFUL_TERMINATION
6253 log_error(LOG_LEVEL_INFO, "Graceful termination requested.");
6255 unload_current_config_file();
6256 unload_current_actions_file();
6257 unload_current_re_filterfile();
6258 #ifdef FEATURE_TRUST
6259 unload_current_trust_file();
6262 if (config->multi_threaded)
6269 } while ((clients->next != NULL) && (--i > 0));
6273 log_error(LOG_LEVEL_ERROR, "Graceful termination failed "
6274 "- still some live clients after 1 minute wait.");
6284 #ifdef FEATURE_HTTPS_INSPECTION
6286 * Only release TLS backed resources if there
6287 * are no active connections left.
6289 if (clients->next == NULL)
6295 log_error(LOG_LEVEL_INFO, "Exiting gracefully.");
6297 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6298 /* Cleanup - remove taskbar icon etc. */
6303 #endif /* FEATURE_GRACEFUL_TERMINATION */