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-2020 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 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
102 #endif /* def __GLIBC__ */
107 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
108 #endif /* HAVE_POLL */
115 #ifdef FEATURE_HTTPS_INSPECTION
121 #include "miscutil.h"
123 #include "jbsockets.h"
128 #include "urlmatch.h"
129 #ifdef FEATURE_CLIENT_TAGS
130 #include "client-tags.h"
134 struct client_states clients[1];
135 struct file_list files[1];
137 #ifdef FEATURE_STATISTICS
138 int urls_read = 0; /* total nr of urls read inc rejected */
139 int urls_rejected = 0; /* total nr of urls rejected */
140 #endif /* def FEATURE_STATISTICS */
142 #ifdef FEATURE_GRACEFUL_TERMINATION
146 #if !defined(_WIN32) && !defined(__OS2__)
147 static void sig_handler(int the_signal);
149 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
150 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
151 static jb_err get_server_headers(struct client_state *csp);
152 static const char *crunch_reason(const struct http_response *rsp);
153 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
154 static char *get_request_line(struct client_state *csp);
155 static jb_err receive_client_request(struct client_state *csp);
156 static jb_err parse_client_request(struct client_state *csp);
157 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
158 static jb_err change_request_destination(struct client_state *csp);
159 static void chat(struct client_state *csp);
160 static void serve(struct client_state *csp);
161 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
162 static void usage(const char *myname);
164 static void initialize_mutexes(void);
165 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
166 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
167 static void close_ports_helper(jb_socket sockets[]);
168 static void listen_loop(void);
169 static void serve(struct client_state *csp);
172 static int32 server_thread(void *data);
173 #endif /* def __BEOS__ */
176 #define sleep(N) Sleep(((N) * 1000))
180 #define sleep(N) DosSleep(((N) * 100))
184 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
185 void show_fuzz_usage(const char *name);
188 #ifdef MUTEX_LOCKS_AVAILABLE
190 * XXX: Does the locking stuff really belong in this file?
192 privoxy_mutex_t log_mutex;
193 privoxy_mutex_t log_init_mutex;
194 privoxy_mutex_t connection_reuse_mutex;
196 #ifdef LIMIT_MUTEX_NUMBER
197 privoxy_mutex_t certificates_mutexes[32];
199 privoxy_mutex_t certificates_mutexes[65536];
200 #endif /* LIMIT_MUTEX_NUMBER */
201 privoxy_mutex_t rng_mutex;
203 #ifdef FEATURE_EXTERNAL_FILTERS
204 privoxy_mutex_t external_filter_mutex;
206 #ifdef FEATURE_CLIENT_TAGS
207 privoxy_mutex_t client_tags_mutex;
210 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
211 privoxy_mutex_t resolver_mutex;
212 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
214 #ifndef HAVE_GMTIME_R
215 privoxy_mutex_t gmtime_mutex;
216 #endif /* ndef HAVE_GMTIME_R */
218 #ifndef HAVE_LOCALTIME_R
219 privoxy_mutex_t localtime_mutex;
220 #endif /* ndef HAVE_GMTIME_R */
222 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
223 privoxy_mutex_t rand_mutex;
224 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
226 #endif /* def MUTEX_LOCKS_AVAILABLE */
229 const char *basedir = NULL;
230 const char *pidfile = NULL;
231 static int received_hup_signal = 0;
232 #endif /* defined unix */
234 /* HTTP snipplets. */
235 static const char CSUCCEED[] =
236 "HTTP/1.1 200 Connection established\r\n\r\n";
238 static const char CHEADER[] =
239 "HTTP/1.1 400 Invalid header received from client\r\n"
240 "Content-Type: text/plain\r\n"
241 "Connection: close\r\n\r\n"
242 "Invalid header received from client.\r\n";
244 static const char FTP_RESPONSE[] =
245 "HTTP/1.1 400 Invalid request received from client\r\n"
246 "Content-Type: text/plain\r\n"
247 "Connection: close\r\n\r\n"
248 "Invalid request. Privoxy doesn't support FTP.\r\n";
250 static const char GOPHER_RESPONSE[] =
251 "HTTP/1.1 400 Invalid request received from client\r\n"
252 "Content-Type: text/plain\r\n"
253 "Connection: close\r\n\r\n"
254 "Invalid request. Privoxy doesn't support gopher.\r\n";
256 /* XXX: should be a template */
257 static const char MISSING_DESTINATION_RESPONSE[] =
258 "HTTP/1.1 400 Bad request received from client\r\n"
259 "Content-Type: text/plain\r\n"
260 "Connection: close\r\n\r\n"
261 "Bad request. Privoxy was unable to extract the destination.\r\n";
263 /* XXX: should be a template */
264 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
265 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
266 "Content-Type: text/plain\r\n"
267 "Connection: close\r\n\r\n"
268 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
270 /* XXX: should be a template */
271 static const char MESSED_UP_REQUEST_RESPONSE[] =
272 "HTTP/1.1 400 Malformed request after rewriting\r\n"
273 "Content-Type: text/plain\r\n"
274 "Connection: close\r\n\r\n"
275 "Bad request. Messed up with header filters.\r\n";
277 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
278 "HTTP/1.1 503 Too many open connections\r\n"
279 "Content-Type: text/plain\r\n"
280 "Connection: close\r\n\r\n"
281 "Maximum number of open connections reached.\r\n";
283 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
284 "HTTP/1.1 504 Connection timeout\r\n"
285 "Content-Type: text/plain\r\n"
286 "Connection: close\r\n\r\n"
287 "The connection timed out because the client request didn't arrive in time.\r\n";
289 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
290 "HTTP/1.1 400 Failed reading client body\r\n"
291 "Content-Type: text/plain\r\n"
292 "Connection: close\r\n\r\n"
293 "Failed parsing or buffering the chunk-encoded client body.\r\n";
295 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
296 "HTTP/1.1 417 Expecting too much\r\n"
297 "Content-Type: text/plain\r\n"
298 "Connection: close\r\n\r\n"
299 "Privoxy detected an unsupported Expect header value.\r\n";
301 /* A function to crunch a response */
302 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
304 /* Crunch function flags */
305 #define CF_NO_FLAGS 0
306 /* Cruncher applies to forced requests as well */
307 #define CF_IGNORE_FORCE 1
308 /* Crunched requests are counted for the block statistics */
309 #define CF_COUNT_AS_REJECT 2
311 /* A crunch function and its flags */
314 const crunch_func_ptr cruncher;
318 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
320 /* Complete list of cruncher functions */
321 static const struct cruncher crunchers_all[] = {
322 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
323 { block_url, CF_COUNT_AS_REJECT },
325 { trust_url, CF_COUNT_AS_REJECT },
326 #endif /* def FEATURE_TRUST */
327 { redirect_url, CF_NO_FLAGS },
328 { dispatch_cgi, CF_IGNORE_FORCE},
332 /* Light version, used after tags are applied */
333 static const struct cruncher crunchers_light[] = {
334 { block_url, CF_COUNT_AS_REJECT },
335 { redirect_url, CF_NO_FLAGS },
341 * XXX: Don't we really mean
347 #if !defined(_WIN32) && !defined(__OS2__)
348 /*********************************************************************
350 * Function : sig_handler
352 * Description : Signal handler for different signals.
353 * Exit gracefully on TERM and INT
354 * or set a flag that will cause the errlog
355 * to be reopened by the main thread on HUP.
358 * 1 : the_signal = the signal cause this function to call
362 *********************************************************************/
363 static void sig_handler(int the_signal)
369 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
381 received_hup_signal = 1;
387 * We shouldn't be here, unless we catch signals
388 * in main() that we can't handle here!
390 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
398 /*********************************************************************
400 * Function : get_write_delay
402 * Description : Parse the delay-response parameter.
405 * 1 : csp = Current client state (buffers, headers, etc...)
407 * Returns : Number of milliseconds to delay writes.
409 *********************************************************************/
410 static unsigned int get_write_delay(const struct client_state *csp)
416 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
420 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
422 delay = (unsigned)strtol(newval, &endptr, 0);
425 log_error(LOG_LEVEL_FATAL,
426 "Invalid delay-response{} parameter: '%s'", newval);
434 /*********************************************************************
436 * Function : client_protocol_is_unsupported
438 * Description : Checks if the client used a known unsupported
439 * protocol and deals with it by sending an error
443 * 1 : csp = Current client state (buffers, headers, etc...)
444 * 2 : req = the first request line send by the client
446 * Returns : TRUE if an error response has been generated, or
447 * FALSE if the request doesn't look invalid.
449 *********************************************************************/
450 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
453 * If it's a FTP or gopher request, we don't support it.
455 * These checks are better than nothing, but they might
456 * not work in all configurations and some clients might
457 * have problems digesting the answer.
459 * They should, however, never cause more problems than
460 * Privoxy's old behaviour (returning the misleading HTML
463 * "Could not resolve http://(ftp|gopher)://example.org").
465 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
467 const char *response = NULL;
468 const char *protocol = NULL;
470 if (!strncmpic(req, "GET ftp://", 10))
472 response = FTP_RESPONSE;
477 response = GOPHER_RESPONSE;
480 log_error(LOG_LEVEL_ERROR,
481 "%s tried to use Privoxy as %s proxy: %s",
482 csp->ip_addr_str, protocol, req);
483 log_error(LOG_LEVEL_CLF,
484 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
486 write_socket_delayed(csp->cfd, response, strlen(response),
487 get_write_delay(csp));
496 /*********************************************************************
498 * Function : client_has_unsupported_expectations
500 * Description : Checks if the client used an unsupported expectation
501 * in which case an error message is delivered.
504 * 1 : csp = Current client state (buffers, headers, etc...)
506 * Returns : TRUE if an error response has been generated, or
507 * FALSE if the request doesn't look invalid.
509 *********************************************************************/
510 static int client_has_unsupported_expectations(const struct client_state *csp)
512 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
514 log_error(LOG_LEVEL_ERROR,
515 "Rejecting request from client %s with unsupported Expect header value",
517 log_error(LOG_LEVEL_CLF,
518 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
519 write_socket_delayed(csp->cfd,
520 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
521 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
522 get_write_delay(csp));
532 /*********************************************************************
534 * Function : get_request_destination_elsewhere
536 * Description : If the client's request was redirected into
537 * Privoxy without the client's knowledge,
538 * the request line lacks the destination host.
540 * This function tries to get it elsewhere,
541 * provided accept-intercepted-requests is enabled.
543 * "Elsewhere" currently only means "Host: header",
544 * but in the future we may ask the redirecting
545 * packet filter to look the destination up.
547 * If the destination stays unknown, an error
548 * response is send to the client and headers
549 * are freed so that chat() can return directly.
552 * 1 : csp = Current client state (buffers, headers, etc...)
553 * 2 : headers = a header list
555 * Returns : JB_ERR_OK if the destination is now known, or
556 * JB_ERR_PARSE if it isn't.
558 *********************************************************************/
559 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 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
581 /* Split the domain we just got for pattern matching */
582 init_domain_components(csp->http);
589 /* We can't work without destination. Go spread the news.*/
591 req = list_to_text(headers);
593 /* XXX: Use correct size */
594 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
595 csp->ip_addr_str, csp->http->cmd);
596 log_error(LOG_LEVEL_ERROR,
597 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
598 csp->ip_addr_str, csp->http->cmd, req);
601 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
602 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
603 destroy_list(headers);
608 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
609 * to get the destination IP address, use it as host directly
610 * or do a reverse DNS lookup first.
615 /*********************************************************************
617 * Function : get_server_headers
619 * Description : Parses server headers in iob and fills them
620 * into csp->headers so that they can later be
624 * 1 : csp = Current client state (buffers, headers, etc...)
626 * Returns : JB_ERR_OK if everything went fine, or
627 * JB_ERR_PARSE if the headers were incomplete.
629 *********************************************************************/
630 static jb_err get_server_headers(struct client_state *csp)
632 int continue_hack_in_da_house = 0;
635 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
640 * continue hack in da house. Ignore the ending of
641 * this head and continue enlisting header lines.
642 * The reason is described below.
644 enlist(csp->headers, "");
645 continue_hack_in_da_house = 0;
648 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
651 * It's a bodyless continue response, don't
652 * stop header parsing after reaching its end.
654 * As a result Privoxy will concatenate the
655 * next response's head and parse and deliver
656 * the headers as if they belonged to one request.
658 * The client will separate them because of the
659 * empty line between them.
661 * XXX: What we're doing here is clearly against
662 * the intended purpose of the continue header,
663 * and under some conditions (HTTP/1.0 client request)
664 * it's a standard violation.
666 * Anyway, "sort of against the spec" is preferable
667 * to "always getting confused by Continue responses"
668 * (Privoxy's behaviour before this hack was added)
670 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
671 continue_hack_in_da_house = 1;
673 else if (*header == '\0')
676 * If the header is empty, but the Continue hack
677 * isn't active, we can assume that we reached the
678 * end of the buffer before we hit the end of the
681 * Inform the caller an let it decide how to handle it.
686 if (JB_ERR_MEMORY == enlist(csp->headers, header))
689 * XXX: Should we quit the request and return a
690 * out of memory error page instead?
692 log_error(LOG_LEVEL_ERROR,
693 "Out of memory while enlisting server headers. %s lost.",
703 /*********************************************************************
705 * Function : crunch_reason
707 * Description : Translates the crunch reason code into a string.
710 * 1 : rsp = a http_response
712 * Returns : A string with the crunch reason or an error description.
714 *********************************************************************/
715 static const char *crunch_reason(const struct http_response *rsp)
717 char * reason = NULL;
722 return "Internal error while searching for crunch reason";
725 switch (rsp->crunch_reason)
728 reason = "Unsupported HTTP feature";
734 reason = "Untrusted";
737 reason = "Redirected";
743 reason = "DNS failure";
745 case FORWARDING_FAILED:
746 reason = "Forwarding failed";
749 reason = "Connection failure";
752 reason = "Out of memory (may mask other reasons)";
754 case CONNECTION_TIMEOUT:
755 reason = "Connection timeout";
758 reason = "No server data received";
761 reason = "No reason recorded";
769 /*********************************************************************
771 * Function : log_applied_actions
773 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
777 * 1 : actions = Current action spec to log
781 *********************************************************************/
782 static void log_applied_actions(const struct current_action_spec *actions)
785 * The conversion to text requires lots of memory allocations so
786 * we only do the conversion if the user is actually interested.
788 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
790 char *actions_as_text = actions_to_line_of_text(actions);
791 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
792 freez(actions_as_text);
797 /*********************************************************************
799 * Function : send_crunch_response
801 * Description : Delivers already prepared response for
802 * intercepted requests, logs the interception
803 * and frees the response.
806 * 1 : csp = Current client state (buffers, headers, etc...)
807 * 2 : rsp = Fully prepared response. Will be freed on exit.
811 *********************************************************************/
812 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
814 const struct http_request *http = csp->http;
818 assert(rsp->head != NULL);
822 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
826 * Extract the status code from the actual head
827 * that will be send to the client. It is the only
828 * way to get it right for all requests, including
829 * the fixed ones for out-of-memory problems.
831 * A head starts like this: 'HTTP/1.1 200...'
835 status_code[0] = rsp->head[9];
836 status_code[1] = rsp->head[10];
837 status_code[2] = rsp->head[11];
838 status_code[3] = '\0';
840 /* Log that the request was crunched and why. */
841 log_applied_actions(csp->action);
842 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
843 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
844 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
846 /* Write the answer to the client */
847 #ifdef FEATURE_HTTPS_INSPECTION
848 if (client_use_ssl(csp))
850 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
851 (const unsigned char *)rsp->head, rsp->head_length) < 0)
852 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
853 (const unsigned char *)rsp->body, rsp->content_length) < 0))
855 /* There is nothing we can do about it. */
856 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
857 "for %s through client socket %d using TLS/SSL",
858 http->url, csp->cfd);
864 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
865 get_write_delay(csp))
866 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
867 get_write_delay(csp)))
869 /* There is nothing we can do about it. */
870 log_error(LOG_LEVEL_CONNECT,
871 "Couldn't deliver the error message for %s through client socket %d: %E",
872 http->url, csp->cfd);
876 /* Clean up and return */
877 if (cgi_error_memory() != rsp)
879 free_http_response(rsp);
885 /*********************************************************************
887 * Function : crunch_response_triggered
889 * Description : Checks if the request has to be crunched,
890 * and delivers the crunch response if necessary.
893 * 1 : csp = Current client state (buffers, headers, etc...)
894 * 2 : crunchers = list of cruncher functions to run
896 * Returns : TRUE if the request was answered with a crunch response
899 *********************************************************************/
900 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
902 struct http_response *rsp = NULL;
903 const struct cruncher *c;
906 * If CGI request crunching is disabled,
907 * check the CGI dispatcher out of order to
908 * prevent unintentional blocks or redirects.
910 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
911 && (NULL != (rsp = dispatch_cgi(csp))))
913 /* Deliver, log and free the interception response. */
914 send_crunch_response(csp, rsp);
915 csp->flags |= CSP_FLAG_CRUNCHED;
919 for (c = crunchers; c->cruncher != NULL; c++)
922 * Check the cruncher if either Privoxy is toggled
923 * on and the request isn't forced, or if the cruncher
924 * applies to forced requests as well.
926 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
927 !(csp->flags & CSP_FLAG_FORCED)) ||
928 (c->flags & CF_IGNORE_FORCE))
930 rsp = c->cruncher(csp);
933 /* Deliver, log and free the interception response. */
934 send_crunch_response(csp, rsp);
935 csp->flags |= CSP_FLAG_CRUNCHED;
936 #ifdef FEATURE_STATISTICS
937 if (c->flags & CF_COUNT_AS_REJECT)
939 csp->flags |= CSP_FLAG_REJECTED;
941 #endif /* def FEATURE_STATISTICS */
952 /*********************************************************************
954 * Function : build_request_line
956 * Description : Builds the HTTP request line.
958 * If a HTTP forwarder is used it expects the whole URL,
959 * web servers only get the path.
962 * 1 : csp = Current client state (buffers, headers, etc...)
963 * 2 : fwd = The forwarding spec used for the request
964 * XXX: Should use http->fwd instead.
965 * 3 : request_line = The old request line which will be replaced.
967 * Returns : Nothing. Terminates in case of memory problems.
969 *********************************************************************/
970 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
972 struct http_request *http = csp->http;
975 * Downgrade http version from 1.1 to 1.0
976 * if +downgrade action applies.
978 if ((csp->action->flags & ACTION_DOWNGRADE)
979 && (!strcmpic(http->ver, "HTTP/1.1")))
982 http->ver = strdup_or_die("HTTP/1.0");
986 * Rebuild the request line.
988 freez(*request_line);
989 *request_line = strdup(http->gpc);
990 string_append(request_line, " ");
992 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
994 string_append(request_line, http->url);
998 string_append(request_line, http->path);
1000 string_append(request_line, " ");
1001 string_append(request_line, http->ver);
1003 if (*request_line == NULL)
1005 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1007 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1011 /*********************************************************************
1013 * Function : change_request_destination
1015 * Description : Parse a (rewritten) request line and regenerate
1016 * the http request data.
1019 * 1 : csp = Current client state (buffers, headers, etc...)
1021 * Returns : Forwards the parse_http_request() return code.
1022 * Terminates in case of memory problems.
1024 *********************************************************************/
1025 static jb_err change_request_destination(struct client_state *csp)
1027 struct http_request *http = csp->http;
1030 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1031 csp->headers->first->str);
1032 free_http_request(http);
1033 err = parse_http_request(csp->headers->first->str, http);
1034 if (JB_ERR_OK != err)
1036 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1037 jb_err_to_string(err));
1044 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1045 /*********************************************************************
1047 * Function : server_response_is_complete
1049 * Description : Determines whether we should stop reading
1050 * from the server socket.
1053 * 1 : csp = Current client state (buffers, headers, etc...)
1054 * 2 : content_length = Length of content received so far.
1056 * Returns : TRUE if the response is complete,
1059 *********************************************************************/
1060 static int server_response_is_complete(struct client_state *csp,
1061 unsigned long long content_length)
1063 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1065 if (!strcmpic(csp->http->gpc, "HEAD"))
1068 * "HEAD" implies no body, we are thus expecting
1069 * no content. XXX: incomplete "list" of methods?
1071 csp->expected_content_length = 0;
1072 content_length_known = TRUE;
1073 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1076 if (csp->http->status == 204 || csp->http->status == 304)
1079 * Expect no body. XXX: incomplete "list" of status codes?
1081 csp->expected_content_length = 0;
1082 content_length_known = TRUE;
1083 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1086 return (content_length_known && ((0 == csp->expected_content_length)
1087 || (csp->expected_content_length <= content_length)));
1091 #ifdef FEATURE_CONNECTION_SHARING
1092 /*********************************************************************
1094 * Function : wait_for_alive_connections
1096 * Description : Waits for alive connections to timeout.
1102 *********************************************************************/
1103 static void wait_for_alive_connections(void)
1105 int connections_alive = close_unusable_connections();
1107 while (0 < connections_alive)
1109 log_error(LOG_LEVEL_CONNECT,
1110 "Waiting for %d connections to timeout.",
1113 connections_alive = close_unusable_connections();
1116 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1119 #endif /* def FEATURE_CONNECTION_SHARING */
1122 /*********************************************************************
1124 * Function : save_connection_destination
1126 * Description : Remembers a connection for reuse later on.
1129 * 1 : sfd = Open socket to remember.
1130 * 2 : http = The destination for the connection.
1131 * 3 : fwd = The forwarder settings used.
1132 * 4 : server_connection = storage.
1136 *********************************************************************/
1137 void save_connection_destination(jb_socket sfd,
1138 const struct http_request *http,
1139 const struct forward_spec *fwd,
1140 struct reusable_connection *server_connection)
1142 assert(sfd != JB_INVALID_SOCKET);
1143 assert(NULL != http->host);
1145 server_connection->sfd = sfd;
1146 server_connection->host = strdup_or_die(http->host);
1147 server_connection->port = http->port;
1149 assert(NULL != fwd);
1150 assert(server_connection->gateway_host == NULL);
1151 assert(server_connection->gateway_port == 0);
1152 assert(server_connection->forwarder_type == 0);
1153 assert(server_connection->forward_host == NULL);
1154 assert(server_connection->forward_port == 0);
1156 server_connection->forwarder_type = fwd->type;
1157 if (NULL != fwd->gateway_host)
1159 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1163 server_connection->gateway_host = NULL;
1165 server_connection->gateway_port = fwd->gateway_port;
1167 if (NULL != fwd->forward_host)
1169 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1173 server_connection->forward_host = NULL;
1175 server_connection->forward_port = fwd->forward_port;
1179 /*********************************************************************
1181 * Function : verify_request_length
1183 * Description : Checks if we already got the whole client requests
1184 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1187 * Data that doesn't belong to the current request is
1188 * either thrown away to let the client retry on a clean
1189 * socket, or stashed to be dealt with after the current
1190 * request is served.
1193 * 1 : csp = Current client state (buffers, headers, etc...)
1197 *********************************************************************/
1198 static void verify_request_length(struct client_state *csp)
1200 unsigned long long buffered_request_bytes =
1201 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1203 if ((csp->expected_client_content_length != 0)
1204 && (buffered_request_bytes != 0))
1206 if (csp->expected_client_content_length >= buffered_request_bytes)
1208 csp->expected_client_content_length -= buffered_request_bytes;
1209 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1210 "to account for the %llu ones we already got.",
1211 csp->expected_client_content_length, buffered_request_bytes);
1215 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1216 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1217 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1218 "Marking the server socket tainted after throwing %llu bytes away.",
1219 buffered_request_bytes - csp->expected_client_content_length);
1220 csp->expected_client_content_length = 0;
1221 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1224 if (csp->expected_client_content_length == 0)
1226 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1230 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1231 && ((csp->client_iob->cur < csp->client_iob->eod)
1232 || (csp->expected_client_content_length != 0)))
1234 if (strcmpic(csp->http->gpc, "GET")
1235 && strcmpic(csp->http->gpc, "HEAD")
1236 && strcmpic(csp->http->gpc, "TRACE")
1237 && strcmpic(csp->http->gpc, "OPTIONS")
1238 && strcmpic(csp->http->gpc, "DELETE"))
1240 /* XXX: this is an incomplete hack */
1241 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1242 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1246 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1248 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1250 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1251 log_error(LOG_LEVEL_CONNECT,
1252 "Possible pipeline attempt detected. The connection will not "
1253 "be kept alive and we will only serve the first request.");
1254 /* Nuke the pipelined requests from orbit, just to be sure. */
1255 clear_iob(csp->client_iob);
1260 * Keep the pipelined data around for now, we'll deal with
1261 * it once we're done serving the current request.
1263 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1264 assert(csp->client_iob->eod >= csp->client_iob->cur);
1265 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1266 "%d bytes of pipelined data received.",
1267 (int)(csp->client_iob->eod - csp->client_iob->cur));
1273 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1274 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1277 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1280 /*********************************************************************
1282 * Function : mark_server_socket_tainted
1284 * Description : Makes sure we don't reuse a server socket
1285 * (if we didn't read everything the server sent
1286 * us reusing the socket would lead to garbage).
1289 * 1 : csp = Current client state (buffers, headers, etc...)
1293 *********************************************************************/
1294 static void mark_server_socket_tainted(struct client_state *csp)
1297 * For consistency we always mark the server socket
1298 * tainted, however, to reduce the log noise we only
1299 * emit a log message if the server socket could have
1300 * actually been reused.
1302 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1303 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1305 log_error(LOG_LEVEL_CONNECT,
1306 "Marking the server socket %d tainted.",
1307 csp->server_connection.sfd);
1309 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1312 /*********************************************************************
1314 * Function : get_request_line
1316 * Description : Read the client request line.
1319 * 1 : csp = Current client state (buffers, headers, etc...)
1321 * Returns : Pointer to request line or NULL in case of errors.
1323 *********************************************************************/
1324 static char *get_request_line(struct client_state *csp)
1326 char buf[BUFFER_SIZE];
1327 char *request_line = NULL;
1330 memset(buf, 0, sizeof(buf));
1332 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1335 * If there are multiple pipelined requests waiting,
1336 * the flag will be set again once the next request
1339 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1341 request_line = get_header(csp->client_iob);
1342 if ((NULL != request_line) && ('\0' != *request_line))
1344 return request_line;
1348 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1349 "received yet. Continuing reading from %d.", csp->cfd);
1357 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1359 !data_is_available(csp->cfd, csp->config->socket_timeout)
1362 if (socket_is_still_alive(csp->cfd))
1364 log_error(LOG_LEVEL_CONNECT,
1365 "No request line on socket %d received in time. Timeout: %d.",
1366 csp->cfd, csp->config->socket_timeout);
1367 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1368 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1369 get_write_delay(csp));
1373 log_error(LOG_LEVEL_CONNECT,
1374 "The client side of the connection on socket %d got "
1375 "closed without sending a complete request line.", csp->cfd);
1380 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1382 if (len <= 0) return NULL;
1385 * If there is no memory left for buffering the
1386 * request, there is nothing we can do but hang up
1388 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1393 request_line = get_header(csp->client_iob);
1395 } while ((NULL != request_line) && ('\0' == *request_line));
1397 return request_line;
1403 CHUNK_STATUS_MISSING_DATA,
1404 CHUNK_STATUS_BODY_COMPLETE,
1405 CHUNK_STATUS_PARSE_ERROR
1409 /*********************************************************************
1411 * Function : chunked_body_is_complete
1413 * Description : Figures out whether or not a chunked body is complete.
1415 * Currently it always starts at the beginning of the
1416 * buffer which is somewhat wasteful and prevents Privoxy
1417 * from starting to forward the correctly parsed chunks
1418 * as soon as theoretically possible.
1420 * Should be modified to work with a common buffer,
1421 * and allow the caller to skip already parsed chunks.
1423 * This would allow the function to be used for unbuffered
1424 * response bodies as well.
1427 * 1 : iob = Buffer with the body to check.
1428 * 2 : length = Length of complete body
1430 * Returns : Enum with the result of the check.
1432 *********************************************************************/
1433 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1435 unsigned int chunksize;
1441 * We need at least a single digit, followed by "\r\n",
1442 * followed by an unknown amount of data, followed by "\r\n".
1444 if (p + 5 > iob->eod)
1446 return CHUNK_STATUS_MISSING_DATA;
1448 if (sscanf(p, "%x", &chunksize) != 1)
1450 return CHUNK_STATUS_PARSE_ERROR;
1454 * We want at least a single digit, followed by "\r\n",
1455 * followed by the specified amount of data, followed by "\r\n".
1457 if (p + chunksize + 5 > iob->eod)
1459 return CHUNK_STATUS_MISSING_DATA;
1462 /* Skip chunk-size. */
1463 p = strstr(p, "\r\n");
1466 return CHUNK_STATUS_PARSE_ERROR;
1468 /* Move beyond the chunkdata. */
1471 /* There should be another "\r\n" to skip */
1472 if (memcmp(p, "\r\n", 2))
1474 return CHUNK_STATUS_PARSE_ERROR;
1477 } while (chunksize > 0U);
1479 *length = (size_t)(p - iob->cur);
1480 assert(*length <= (size_t)(iob->eod - iob->cur));
1481 assert(p <= iob->eod);
1483 return CHUNK_STATUS_BODY_COMPLETE;
1488 /*********************************************************************
1490 * Function : receive_chunked_client_request_body
1492 * Description : Read the chunk-encoded client request body.
1493 * Failures are dealt with.
1496 * 1 : csp = Current client state (buffers, headers, etc...)
1498 * Returns : JB_ERR_OK or JB_ERR_PARSE
1500 *********************************************************************/
1501 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1504 enum chunk_status status;
1506 while (CHUNK_STATUS_MISSING_DATA ==
1507 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1509 char buf[BUFFER_SIZE];
1512 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1514 log_error(LOG_LEVEL_ERROR,
1515 "Timeout while waiting for the client body.");
1518 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1521 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1524 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1529 if (status != CHUNK_STATUS_BODY_COMPLETE)
1531 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1532 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1533 log_error(LOG_LEVEL_CLF,
1534 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1535 return JB_ERR_PARSE;
1537 log_error(LOG_LEVEL_CONNECT,
1538 "Chunked client body completely read. Length: %d", body_length);
1539 csp->expected_client_content_length = body_length;
1547 /*********************************************************************
1549 * Function : fuzz_chunked_transfer_encoding
1551 * Description : Treat the fuzzed input as chunked transfer encoding
1552 * to check and dechunk.
1555 * 1 : csp = Used to store the data.
1556 * 2 : fuzz_input_file = File to read the input from.
1558 * Returns : Result of dechunking
1560 *********************************************************************/
1561 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1564 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1565 enum chunk_status status;
1567 status = chunked_body_is_complete(csp->iob, &length);
1568 if (CHUNK_STATUS_BODY_COMPLETE != status)
1570 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1573 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1578 /*********************************************************************
1580 * Function : fuzz_client_request
1582 * Description : Try to get a client request from the fuzzed input.
1585 * 1 : csp = Current client state (buffers, headers, etc...)
1586 * 2 : fuzz_input_file = File to read the input from.
1588 * Returns : Result of fuzzing.
1590 *********************************************************************/
1591 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1596 csp->ip_addr_str = "fuzzer";
1598 if (strcmp(fuzz_input_file, "-") != 0)
1600 log_error(LOG_LEVEL_FATAL,
1601 "Fuzzed client requests can currenty only be read from stdin (-).");
1603 err = receive_client_request(csp);
1604 if (err != JB_ERR_OK)
1608 err = parse_client_request(csp);
1609 if (err != JB_ERR_OK)
1617 #endif /* def FUZZ */
1620 #ifdef FEATURE_FORCE_LOAD
1621 /*********************************************************************
1623 * Function : force_required
1625 * Description : Checks a request line to see if it contains
1626 * the FORCE_PREFIX. If it does, it is removed
1627 * unless enforcing requests has beend disabled.
1630 * 1 : request_line = HTTP request line
1632 * Returns : TRUE if force is required, FALSE otherwise.
1634 *********************************************************************/
1635 static int force_required(const struct client_state *csp, char *request_line)
1639 p = strstr(request_line, "http://");
1643 p += strlen("http://");
1647 /* Intercepted request usually don't specify the protocol. */
1651 /* Go to the beginning of the path */
1656 * If the path is missing the request line is invalid and we
1657 * are done here. The client-visible rejection happens later on.
1662 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1664 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1666 /* XXX: Should clean more carefully */
1667 strclean(request_line, FORCE_PREFIX);
1668 log_error(LOG_LEVEL_FORCE,
1669 "Enforcing request: \"%s\".", request_line);
1673 log_error(LOG_LEVEL_FORCE,
1674 "Ignored force prefix in request: \"%s\".", request_line);
1680 #endif /* def FEATURE_FORCE_LOAD */
1683 /*********************************************************************
1685 * Function : receive_client_request
1687 * Description : Read the client's request (more precisely the
1688 * client headers) and answer it if necessary.
1691 * 1 : csp = Current client state (buffers, headers, etc...)
1693 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1695 *********************************************************************/
1696 static jb_err receive_client_request(struct client_state *csp)
1698 char buf[BUFFER_SIZE];
1701 struct http_request *http;
1705 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1706 struct list header_list;
1707 struct list *headers = &header_list;
1709 /* We don't care if the arriving data is a valid HTTP request or not. */
1710 csp->requests_received_total++;
1714 memset(buf, 0, sizeof(buf));
1716 req = get_request_line(csp);
1719 mark_server_socket_tainted(csp);
1720 return JB_ERR_PARSE;
1722 assert(*req != '\0');
1724 if (client_protocol_is_unsupported(csp, req))
1726 return JB_ERR_PARSE;
1729 #ifdef FEATURE_FORCE_LOAD
1730 if (force_required(csp, req))
1732 csp->flags |= CSP_FLAG_FORCED;
1734 #endif /* def FEATURE_FORCE_LOAD */
1736 err = parse_http_request(req, http);
1738 if (JB_ERR_OK != err)
1740 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1741 get_write_delay(csp));
1742 /* XXX: Use correct size */
1743 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1744 log_error(LOG_LEVEL_ERROR,
1745 "Couldn't parse request line received from %s: %s",
1746 csp->ip_addr_str, jb_err_to_string(err));
1748 free_http_request(http);
1749 return JB_ERR_PARSE;
1752 /* grab the rest of the client's headers */
1756 p = get_header(csp->client_iob);
1760 /* There are no additional headers to read. */
1767 * We didn't receive a complete header
1768 * line yet, get the rest of it.
1770 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1772 log_error(LOG_LEVEL_ERROR,
1773 "Stopped grabbing the client headers.");
1774 destroy_list(headers);
1775 return JB_ERR_PARSE;
1778 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1781 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1782 destroy_list(headers);
1783 return JB_ERR_PARSE;
1786 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1789 * If there is no memory left for buffering the
1790 * request, there is nothing we can do but hang up
1792 destroy_list(headers);
1793 return JB_ERR_MEMORY;
1798 if (!strncmpic(p, "Transfer-Encoding:", 18))
1801 * XXX: should be called through sed()
1802 * but currently can't.
1804 client_transfer_encoding(csp, &p);
1807 * We were able to read a complete
1808 * header and can finally enlist it.
1815 if (http->host == NULL)
1818 * If we still don't know the request destination,
1819 * the request is invalid or the client uses
1820 * Privoxy without its knowledge.
1822 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1825 * Our attempts to get the request destination
1826 * elsewhere failed or Privoxy is configured
1827 * to only accept proxy requests.
1829 * An error response has already been send
1830 * and we're done here.
1832 return JB_ERR_PARSE;
1836 #ifdef FEATURE_CLIENT_TAGS
1837 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1838 set_client_address(csp, headers);
1839 get_tag_list_for_client(csp->client_tags, csp->client_address);
1843 * Determine the actions for this URL
1845 #ifdef FEATURE_TOGGLE
1846 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1848 /* Most compatible set of actions (i.e. none) */
1849 init_current_action(csp->action);
1852 #endif /* ndef FEATURE_TOGGLE */
1854 get_url_actions(csp, http);
1857 enlist(csp->headers, http->cmd);
1859 /* Append the previously read headers */
1860 err = list_append_list_unique(csp->headers, headers);
1861 destroy_list(headers);
1868 /*********************************************************************
1870 * Function : parse_client_request
1872 * Description : Parses the client's request and decides what to do
1875 * Note that since we're not using select() we could get
1876 * blocked here if a client connected, then didn't say
1880 * 1 : csp = Current client state (buffers, headers, etc...)
1882 * Returns : JB_ERR_OK or JB_ERR_PARSE
1884 *********************************************************************/
1885 static jb_err parse_client_request(struct client_state *csp)
1887 struct http_request *http = csp->http;
1890 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1891 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1892 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1893 && (csp->http->ssl == 0))
1895 /* Assume persistence until further notice */
1896 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1899 if (csp->http->ssl == 0)
1902 * This whole block belongs to chat() but currently
1903 * has to be executed before sed().
1905 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1907 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1909 return JB_ERR_PARSE;
1914 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1916 verify_request_length(csp);
1920 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1922 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1924 err = sed(csp, FILTER_CLIENT_HEADERS);
1925 if (JB_ERR_OK != err)
1927 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1929 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1930 csp->ip_addr_str, csp->http->cmd);
1931 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1932 return JB_ERR_PARSE;
1934 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1936 /* Check request line for rewrites. */
1937 if ((NULL == csp->headers->first->str)
1938 || (strcmp(http->cmd, csp->headers->first->str) &&
1939 (JB_ERR_OK != change_request_destination(csp))))
1942 * A header filter broke the request line - bail out.
1944 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1945 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1946 /* XXX: Use correct size */
1947 log_error(LOG_LEVEL_CLF,
1948 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1949 log_error(LOG_LEVEL_ERROR,
1950 "Invalid request line after applying header filters.");
1951 free_http_request(http);
1953 return JB_ERR_PARSE;
1956 if (client_has_unsupported_expectations(csp))
1958 return JB_ERR_PARSE;
1966 /*********************************************************************
1968 * Function : send_http_request
1970 * Description : Sends the HTTP headers from the client request
1971 * and all the body data that has already been received.
1974 * 1 : csp = Current client state (buffers, headers, etc...)
1976 * Returns : 0 on success, anything else is an error.
1978 *********************************************************************/
1979 static int send_http_request(struct client_state *csp)
1984 hdr = list_to_text(csp->headers);
1987 /* FIXME Should handle error properly */
1988 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1990 list_remove_all(csp->headers);
1993 * Write the client's (modified) header to the server
1994 * (along with anything else that may be in the buffer)
1996 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2001 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2002 csp->http->hostport);
2004 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2005 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2008 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2009 csp->http->hostport);
2012 return write_failure;
2017 #ifdef FEATURE_HTTPS_INSPECTION
2018 /*********************************************************************
2020 * Function : receive_and_send_encrypted_post_data
2022 * Description : Reads remaining POST data from the client and sends
2026 * 1 : csp = Current client state (buffers, headers, etc...)
2028 * Returns : 0 on success, anything else is an error.
2030 *********************************************************************/
2031 static jb_err receive_and_send_encrypted_post_data(struct client_state *csp)
2033 unsigned char buf[BUFFER_SIZE];
2036 while (is_ssl_pending(&(csp->mbedtls_client_attr.ssl)))
2038 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl), buf, sizeof(buf));
2045 /* XXX: Does this actually happen? */
2048 log_error(LOG_LEVEL_HEADER, "Forwarding %d bytes of encrypted POST data",
2050 len = ssl_send_data(&(csp->mbedtls_server_attr.ssl), buf, (size_t)len);
2055 if (csp->expected_client_content_length != 0)
2057 if (csp->expected_client_content_length >= len)
2059 csp->expected_client_content_length -= (unsigned)len;
2064 log_error(LOG_LEVEL_HEADER, "Done forwarding encrypted POST data");
2071 /*********************************************************************
2073 * Function : send_https_request
2075 * Description : Sends the HTTP headers from the client request
2076 * and all the body data that has already been received.
2079 * 1 : csp = Current client state (buffers, headers, etc...)
2081 * Returns : 0 on success, anything else is an error.
2083 *********************************************************************/
2084 static int send_https_request(struct client_state *csp)
2090 hdr = list_to_text(csp->https_headers);
2093 /* FIXME Should handle error properly */
2094 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2096 list_remove_all(csp->https_headers);
2099 * Write the client's (modified) header to the server
2100 * (along with anything else that may be in the buffer)
2102 ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2103 (const unsigned char *)hdr, strlen(hdr));
2108 log_error(LOG_LEVEL_CONNECT,
2109 "Failed sending encrypted request headers to: %s: %E",
2110 csp->http->hostport);
2111 mark_server_socket_tainted(csp);
2112 close_client_and_server_ssl_connections(csp);
2116 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2117 && ((flushed = ssl_flush_socket(&(csp->mbedtls_server_attr.ssl),
2118 csp->client_iob)) < 0))
2120 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2121 csp->http->hostport);
2126 if (csp->expected_client_content_length != 0)
2128 if (csp->expected_client_content_length < flushed)
2130 log_error(LOG_LEVEL_ERROR,
2131 "Flushed %d bytes of request body while only expecting %llu",
2132 flushed, csp->expected_client_content_length);
2133 csp->expected_client_content_length = 0;
2137 log_error(LOG_LEVEL_CONNECT,
2138 "Flushed %d bytes of request body while expecting %llu",
2139 flushed, csp->expected_client_content_length);
2140 csp->expected_client_content_length -= (unsigned)flushed;
2141 if (receive_and_send_encrypted_post_data(csp))
2149 log_error(LOG_LEVEL_CONNECT,
2150 "Flushed %d bytes of request body", flushed);
2154 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2161 /*********************************************************************
2163 * Function : receive_encrypted_request
2165 * Description : Receives an encrypted request.
2168 * 1 : csp = Current client state (buffers, headers, etc...)
2170 * Returns : JB_ERR_OK on success,
2171 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2173 *********************************************************************/
2174 static jb_err receive_encrypted_request(struct client_state *csp)
2176 char buf[BUFFER_SIZE];
2182 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2183 if (!data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout))
2185 log_error(LOG_LEVEL_CONNECT,
2186 "Socket %d timed out while waiting for client headers", csp->cfd);
2187 return JB_ERR_PARSE;
2189 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2190 (unsigned char *)buf, sizeof(buf));
2193 return JB_ERR_PARSE;
2195 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2197 return JB_ERR_MEMORY;
2199 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2200 } while (p == NULL);
2202 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2208 /*********************************************************************
2210 * Function : process_encrypted_request
2212 * Description : Receives and parses an encrypted request.
2215 * 1 : csp = Current client state (buffers, headers, etc...)
2217 * Returns : JB_ERR_OK on success,
2218 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2220 *********************************************************************/
2221 static jb_err process_encrypted_request(struct client_state *csp)
2226 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2227 struct list header_list;
2228 struct list *headers = &header_list;
2230 err = receive_encrypted_request(csp);
2231 if (err != JB_ERR_OK)
2233 /* XXX: Also used for JB_ERR_MEMORY */
2234 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2235 (const unsigned char *)CHEADER, strlen(CHEADER));
2239 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2240 request_line = get_header(csp->client_iob);
2241 if (request_line == NULL)
2243 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2244 (const unsigned char *)CHEADER, strlen(CHEADER));
2245 return JB_ERR_PARSE;
2247 assert(*request_line != '\0');
2249 if (client_protocol_is_unsupported(csp, request_line))
2251 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2252 (const unsigned char *)CHEADER, strlen(CHEADER));
2253 return JB_ERR_PARSE;
2256 #ifdef FEATURE_FORCE_LOAD
2257 if (force_required(csp, request_line))
2259 csp->flags |= CSP_FLAG_FORCED;
2261 #endif /* def FEATURE_FORCE_LOAD */
2263 free_http_request(csp->http);
2265 err = parse_http_request(request_line, csp->http);
2266 /* XXX: Restore ssl setting. This is ugly */
2267 csp->http->client_ssl = 1;
2268 csp->http->server_ssl = 1;
2270 freez(request_line);
2271 if (JB_ERR_OK != err)
2273 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2274 (const unsigned char *)CHEADER, strlen(CHEADER));
2275 /* XXX: Use correct size */
2276 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2277 log_error(LOG_LEVEL_ERROR,
2278 "Couldn't parse request line received from %s: %s",
2279 csp->ip_addr_str, jb_err_to_string(err));
2281 free_http_request(csp->http);
2282 return JB_ERR_PARSE;
2285 /* Parse the rest of the client's headers. */
2289 p = get_header(csp->client_iob);
2293 /* There are no additional headers to read. */
2300 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2303 * Our attempts to get the request destination
2306 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2307 (const unsigned char *)CHEADER, strlen(CHEADER));
2308 return JB_ERR_PARSE;
2311 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
2312 /* Split the domain we just got for pattern matching */
2313 init_domain_components(csp->http);
2316 #ifdef FEATURE_TOGGLE
2317 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2320 /* Determine the actions for this URL */
2321 get_url_actions(csp, csp->http);
2324 enlist(csp->https_headers, csp->http->cmd);
2326 /* Append the previously read headers */
2327 err = list_append_list_unique(csp->https_headers, headers);
2328 destroy_list(headers);
2329 if (JB_ERR_OK != err)
2331 /* XXX: Send error message */
2335 /* XXX: Work around crash */
2336 csp->error_message = NULL;
2338 /* XXX: Why do this here? */
2341 err = sed_https(csp);
2342 if (JB_ERR_OK != err)
2344 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2345 (const unsigned char *)CHEADER, strlen(CHEADER));
2346 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2348 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2349 csp->ip_addr_str, csp->http->cmd);
2350 return JB_ERR_PARSE;
2353 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2354 log_applied_actions(csp->action);
2362 /*********************************************************************
2364 * Function : handle_established_connection
2366 * Description : Shuffle data between client and server once the
2367 * connection has been established.
2370 * 1 : csp = Current client state (buffers, headers, etc...)
2372 * Returns : Nothing.
2374 *********************************************************************/
2375 static void handle_established_connection(struct client_state *csp)
2381 struct pollfd poll_fds[2];
2385 struct timeval timeout;
2388 int ms_iis5_hack = 0;
2389 unsigned long long byte_count = 0;
2390 struct http_request *http;
2391 long len = 0; /* for buffer sizes (and negative error codes) */
2392 int buffer_and_filter_content = 0;
2393 unsigned int write_delay;
2394 #ifdef FEATURE_HTTPS_INSPECTION
2396 int use_ssl_tunnel = 0;
2397 csp->dont_verify_certificate = 0;
2400 * Preset flags informing if SSL connections with server or client
2401 * are opened or closed
2403 csp->ssl_with_server_is_opened = 0;
2404 csp->ssl_with_client_is_opened = 0;
2406 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2408 /* Pass encrypted content without filtering. */
2413 /* Skeleton for HTTP response, if we should intercept the request */
2414 struct http_response *rsp;
2415 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2416 int watch_client_socket;
2419 csp->receive_buffer_size = csp->config->receive_buffer_size;
2420 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2421 if (csp->receive_buffer == NULL)
2423 log_error(LOG_LEVEL_ERROR,
2424 "Out of memory. Failed to allocate the receive buffer.");
2425 rsp = cgi_error_memory();
2426 send_crunch_response(csp, rsp);
2433 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2434 csp->cfd : csp->server_connection.sfd;
2437 /* pass data between the client and server
2438 * until one or the other shuts down the connection.
2443 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2444 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2446 write_delay = get_write_delay(csp);
2453 * FD_ZERO here seems to point to an errant macro which crashes.
2454 * So do this by hand for now...
2456 memset(&rfds,0x00,sizeof(fd_set));
2460 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2461 if (!watch_client_socket)
2463 maxfd = csp->server_connection.sfd;
2466 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2468 FD_SET(csp->cfd, &rfds);
2471 FD_SET(csp->server_connection.sfd, &rfds);
2472 #endif /* ndef HAVE_POLL */
2474 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2475 if ((csp->flags & CSP_FLAG_CHUNKED)
2476 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2477 && ((csp->iob->eod - csp->iob->cur) >= 5)
2478 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2481 * XXX: This check should be obsolete now,
2482 * but let's wait a while to be sure.
2484 log_error(LOG_LEVEL_CONNECT,
2485 "Looks like we got the last chunk together with "
2486 "the server headers but didn't detect it earlier. "
2487 "We better stop reading.");
2488 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2489 csp->expected_content_length = byte_count;
2490 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2492 if (server_body && server_response_is_complete(csp, byte_count))
2494 if (csp->expected_content_length == byte_count)
2496 log_error(LOG_LEVEL_CONNECT,
2497 "Done reading from server. Content length: %llu as expected. "
2498 "Bytes most recently read: %d.",
2503 log_error(LOG_LEVEL_CONNECT,
2504 "Done reading from server. Expected content length: %llu. "
2505 "Actual content length: %llu. Bytes most recently read: %d.",
2506 csp->expected_content_length, byte_count, len);
2510 * XXX: Should not jump around, handle_established_connection()
2511 * is complicated enough already.
2515 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2517 #ifdef FEATURE_HTTPS_INSPECTION
2519 * Test if some data from client or destination server are pending
2520 * on TLS/SSL. We must work with them preferably. TLS/SSL data can
2521 * be pending because of maximal fragment size.
2523 int read_ssl_server = 0;
2524 int read_ssl_client = 0;
2526 if (client_use_ssl(csp))
2528 read_ssl_client = is_ssl_pending(&(csp->mbedtls_client_attr.ssl)) != 0;
2531 if (server_use_ssl(csp))
2533 read_ssl_server = is_ssl_pending(&(csp->mbedtls_server_attr.ssl)) != 0;
2536 if (!read_ssl_server && !read_ssl_client)
2540 poll_fds[0].fd = csp->cfd;
2541 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2542 if (!watch_client_socket)
2545 * Ignore incoming data, but still watch out
2546 * for disconnects etc. These flags are always
2547 * implied anyway but explicitly setting them
2550 poll_fds[0].events = POLLERR|POLLHUP;
2555 poll_fds[0].events = POLLIN;
2557 poll_fds[1].fd = csp->server_connection.sfd;
2558 poll_fds[1].events = POLLIN;
2559 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2561 timeout.tv_sec = csp->config->socket_timeout;
2562 timeout.tv_usec = 0;
2563 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
2564 #endif /* def HAVE_POLL */
2566 /*server or client not responding in timeout */
2569 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2570 csp->config->socket_timeout, http->url);
2571 if ((byte_count == 0) && (http->ssl == 0))
2573 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2575 mark_server_socket_tainted(csp);
2576 #ifdef FEATURE_HTTPS_INSPECTION
2577 close_client_and_server_ssl_connections(csp);
2584 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2586 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2588 mark_server_socket_tainted(csp);
2589 #ifdef FEATURE_HTTPS_INSPECTION
2590 close_client_and_server_ssl_connections(csp);
2595 #ifdef FEATURE_HTTPS_INSPECTION
2598 /* set FD if some data are pending on TLS/SSL connections */
2602 if (read_ssl_client)
2605 poll_fds[0].fd = csp->cfd;
2606 poll_fds[0].events = POLLIN;
2608 FD_SET(csp->cfd, &rfds);
2613 if (read_ssl_server)
2616 poll_fds[1].fd = csp->server_connection.sfd;
2617 poll_fds[1].events = POLLIN;
2619 FD_SET(csp->server_connection.sfd, &rfds);
2626 * This is the body of the browser's request,
2627 * just read and write it.
2629 * Receives data from browser and sends it to server
2631 * XXX: Make sure the client doesn't use pipelining
2632 * behind Privoxy's back.
2635 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2637 log_error(LOG_LEVEL_CONNECT,
2638 "The client socket %d has become unusable while "
2639 "the server socket %d is still open.",
2640 csp->cfd, csp->server_connection.sfd);
2641 mark_server_socket_tainted(csp);
2645 if (poll_fds[0].revents != 0)
2647 if (FD_ISSET(csp->cfd, &rfds))
2648 #endif /* def HAVE_POLL*/
2650 int max_bytes_to_read = (int)csp->receive_buffer_size;
2652 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2653 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2655 if (data_is_available(csp->cfd, 0))
2658 * If the next request is already waiting, we have
2659 * to stop select()ing the client socket. Otherwise
2660 * we would always return right away and get nothing
2663 watch_client_socket = 0;
2664 log_error(LOG_LEVEL_CONNECT,
2665 "Stop watching client socket %d. "
2666 "There's already another request waiting.",
2671 * If the client socket is set, but there's no data
2672 * available on the socket, the client went fishing
2673 * and continuing talking to the server makes no sense.
2675 log_error(LOG_LEVEL_CONNECT,
2676 "The client closed socket %d while "
2677 "the server socket %d is still open.",
2678 csp->cfd, csp->server_connection.sfd);
2679 mark_server_socket_tainted(csp);
2682 if (csp->expected_client_content_length != 0)
2684 if (csp->expected_client_content_length < csp->receive_buffer_size)
2686 max_bytes_to_read = (int)csp->expected_client_content_length;
2688 log_error(LOG_LEVEL_CONNECT,
2689 "Waiting for up to %d bytes from the client.",
2692 assert(max_bytes_to_read <= csp->receive_buffer_size);
2693 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2695 #ifdef FEATURE_HTTPS_INSPECTION
2697 * Reading data from standard or secured connection (HTTP/HTTPS)
2699 if (client_use_ssl(csp))
2702 * Receiving HTTP request from client over TLS/SSL and sending
2703 * it to server over TLS/SSL.
2705 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2706 (unsigned char *)csp->receive_buffer, (size_t)max_bytes_to_read);
2710 mark_server_socket_tainted(csp);
2714 ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2715 (const unsigned char *)csp->receive_buffer, (size_t)len);
2719 log_error(LOG_LEVEL_ERROR,
2720 "Send request over TLS/SSL to: %s failed", http->host);
2721 mark_server_socket_tainted(csp);
2722 close_client_and_server_ssl_connections(csp);
2727 #endif /* def FEATURE_HTTPS_INSPECTION */
2729 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2733 /* XXX: not sure if this is necessary. */
2734 mark_server_socket_tainted(csp);
2735 break; /* "game over, man" */
2738 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2739 if (csp->expected_client_content_length != 0)
2741 assert(len <= max_bytes_to_read);
2742 csp->expected_client_content_length -= (unsigned)len;
2743 log_error(LOG_LEVEL_CONNECT,
2744 "Expected client content length set to %llu "
2745 "after reading %d bytes.",
2746 csp->expected_client_content_length, len);
2747 if (csp->expected_client_content_length == 0)
2749 log_error(LOG_LEVEL_CONNECT,
2750 "Done reading from the client.");
2751 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2754 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2756 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2758 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2759 mark_server_socket_tainted(csp);
2760 #ifdef FEATURE_HTTPS_INSPECTION
2761 close_client_and_server_ssl_connections(csp);
2770 * The server wants to talk. It could be the header or the body.
2771 * If `hdr' is null, then it's the header otherwise it's the body.
2772 * FIXME: Does `hdr' really mean `host'? No.
2775 if (poll_fds[1].revents != 0)
2777 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2778 #endif /* HAVE_POLL */
2780 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2782 * If we are buffering content, we don't want to eat up to
2783 * buffer-limit bytes if the client no longer cares about them.
2784 * If we aren't buffering, however, a dead client socket will be
2785 * noticed pretty much right away anyway, so we can reduce the
2786 * overhead by skipping the check.
2788 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2791 log_error(LOG_LEVEL_CONNECT,
2792 "The server still wants to talk, but the client may already have hung up on us.");
2794 log_error(LOG_LEVEL_CONNECT,
2795 "The server still wants to talk, but the client hung up on us.");
2796 mark_server_socket_tainted(csp);
2797 #ifdef FEATURE_HTTPS_INSPECTION
2798 close_client_and_server_ssl_connections(csp);
2801 #endif /* def _WIN32 */
2803 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2805 #ifdef FEATURE_HTTPS_INSPECTION
2807 * Reading data from standard or secured connection (HTTP/HTTPS)
2809 if (server_use_ssl(csp))
2811 len = ssl_recv_data(&(csp->mbedtls_server_attr.ssl),
2812 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2817 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2818 (int)csp->receive_buffer_size);
2823 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2825 if ((http->ssl && (csp->fwd == NULL))
2826 #ifdef FEATURE_HTTPS_INSPECTION
2832 * Just hang up. We already confirmed the client's CONNECT
2833 * request with status code 200 and unencrypted content is
2834 * no longer welcome.
2836 log_error(LOG_LEVEL_ERROR,
2837 "CONNECT already confirmed. Unable to tell the client about the problem.");
2840 else if (byte_count)
2843 * Just hang up. We already transmitted the original headers
2844 * and parts of the original content and therefore missed the
2845 * chance to send an error message (without risking data corruption).
2847 * XXX: we could retry with a fancy range request here.
2849 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2850 "Unable to tell the client about the problem.");
2851 mark_server_socket_tainted(csp);
2852 #ifdef FEATURE_HTTPS_INSPECTION
2853 close_client_and_server_ssl_connections(csp);
2858 * XXX: Consider handling the cases above the same.
2860 mark_server_socket_tainted(csp);
2864 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2865 if (csp->flags & CSP_FLAG_CHUNKED)
2867 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2869 /* XXX: this is a temporary hack */
2870 log_error(LOG_LEVEL_CONNECT,
2871 "Looks like we reached the end of the last chunk. "
2872 "We better stop reading.");
2873 csp->expected_content_length = byte_count + (unsigned long long)len;
2874 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2878 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2881 * This is guaranteed by allocating with zalloc_or_die()
2882 * and never (intentionally) writing to the last byte.
2884 * csp->receive_buffer_size is the size of the part of the
2885 * buffer we intentionally write to, but we actually
2886 * allocated csp->receive_buffer_size+1 bytes so the assertion
2887 * stays within the allocated range.
2889 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2892 * Add a trailing zero to let be able to use string operations.
2893 * XXX: do we still need this with filter_popups gone?
2895 assert(len <= csp->receive_buffer_size);
2896 csp->receive_buffer[len] = '\0';
2899 * Normally, this would indicate that we've read
2900 * as much as the server has sent us and we can
2901 * close the client connection. However, Microsoft
2902 * in its wisdom has released IIS/5 with a bug that
2903 * prevents it from sending the trailing \r\n in
2904 * a 302 redirect header (and possibly other headers).
2905 * To work around this if we've haven't parsed
2906 * a full header we'll append a trailing \r\n
2907 * and see if this now generates a valid one.
2909 * This hack shouldn't have any impacts. If we've
2910 * already transmitted the header or if this is a
2911 * SSL connection, then we won't bother with this
2912 * hack. So we only work on partially received
2913 * headers. If we append a \r\n and this still
2914 * doesn't generate a valid header, then we won't
2915 * transmit anything to the client.
2920 if (server_body || (http->ssl
2921 #ifdef FEATURE_HTTPS_INSPECTION
2927 * If we have been buffering up the document,
2928 * now is the time to apply content modification
2929 * and send the result to the client.
2931 if (buffer_and_filter_content)
2933 p = execute_content_filters(csp);
2935 * If content filtering fails, use the original
2936 * buffer and length.
2937 * (see p != NULL ? p : csp->iob->cur below)
2941 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2943 #ifdef FEATURE_COMPRESSION
2944 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2945 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2947 char *compressed_content = compress_buffer(p,
2948 (size_t *)&csp->content_length, csp->config->compression_level);
2949 if (compressed_content != NULL)
2952 p = compressed_content;
2953 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2958 if (JB_ERR_OK != update_server_headers(csp))
2960 log_error(LOG_LEVEL_FATAL,
2961 "Failed to update server headers. after filtering.");
2964 hdr = list_to_text(csp->headers);
2967 /* FIXME Should handle error properly */
2968 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2971 #ifdef FEATURE_HTTPS_INSPECTION
2973 * Sending data with standard or secured connection (HTTP/HTTPS)
2975 if (client_use_ssl(csp))
2977 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2978 (const unsigned char *)hdr, strlen(hdr)) < 0)
2979 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2980 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
2981 csp->content_length) < 0))
2983 log_error(LOG_LEVEL_ERROR, "write modified content to "
2984 "client over TLS/SSL failed");
2987 mark_server_socket_tainted(csp);
2988 close_client_and_server_ssl_connections(csp);
2993 #endif /* def FEATURE_HTTPS_INSPECTION */
2995 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2996 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
2997 (size_t)csp->content_length, write_delay))
2999 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3002 mark_server_socket_tainted(csp);
3003 #ifdef FEATURE_HTTPS_INSPECTION
3004 close_client_and_server_ssl_connections(csp);
3014 break; /* "game over, man" */
3018 * This is NOT the body, so
3019 * Let's pretend the server just sent us a blank line.
3021 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3022 len = (int)strlen(csp->receive_buffer);
3025 * Now, let the normal header parsing algorithm below do its
3026 * job. If it fails, we'll exit instead of continuing.
3033 * If we're in the body of the server document, just write it to
3034 * the client, unless we need to buffer the body for later
3035 * content-filtering.
3037 if (server_body || (http->ssl
3038 #ifdef FEATURE_HTTPS_INSPECTION
3043 if (buffer_and_filter_content)
3046 * If there is no memory left for buffering the content, or the buffer limit
3047 * has been reached, switch to non-filtering mode, i.e. make & write the
3048 * header, flush the iob and buf, and get out of the way.
3050 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3055 log_error(LOG_LEVEL_INFO,
3056 "Flushing header and buffers. Stepping back from filtering.");
3058 hdr = list_to_text(csp->headers);
3062 * Memory is too tight to even generate the header.
3063 * Send our static "Out-of-memory" page.
3065 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3066 rsp = cgi_error_memory();
3067 send_crunch_response(csp, rsp);
3068 mark_server_socket_tainted(csp);
3069 #ifdef FEATURE_HTTPS_INSPECTION
3070 close_client_and_server_ssl_connections(csp);
3074 hdrlen = strlen(hdr);
3076 #ifdef FEATURE_HTTPS_INSPECTION
3078 * Sending data with standard or secured connection (HTTP/HTTPS)
3080 if (client_use_ssl(csp))
3082 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3083 (const unsigned char *)hdr, hdrlen) < 0)
3084 || ((flushed = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3086 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3087 (const unsigned char *)csp->receive_buffer, (size_t)len) < 0))
3089 log_error(LOG_LEVEL_CONNECT,
3090 "Flush header and buffers to client failed");
3092 mark_server_socket_tainted(csp);
3093 close_client_and_server_ssl_connections(csp);
3098 #endif /* def FEATURE_HTTPS_INSPECTION */
3100 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3101 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3102 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3105 log_error(LOG_LEVEL_CONNECT,
3106 "Flush header and buffers to client failed: %E");
3108 mark_server_socket_tainted(csp);
3109 #ifdef FEATURE_HTTPS_INSPECTION
3110 close_client_and_server_ssl_connections(csp);
3117 * Reset the byte_count to the amount of bytes
3118 * we just flushed. len will be added a few lines below,
3119 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3121 byte_count = (unsigned long long)flushed;
3123 buffer_and_filter_content = 0;
3129 #ifdef FEATURE_HTTPS_INSPECTION
3131 * Sending data with standard or secured connection (HTTP/HTTPS)
3133 if (client_use_ssl(csp))
3135 ret = ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3136 (const unsigned char *)csp->receive_buffer, (size_t)len);
3139 log_error(LOG_LEVEL_ERROR,
3140 "Sending data to client failed");
3141 mark_server_socket_tainted(csp);
3142 close_client_and_server_ssl_connections(csp);
3147 #endif /* def FEATURE_HTTPS_INSPECTION */
3149 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3150 (size_t)len, write_delay))
3152 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3153 mark_server_socket_tainted(csp);
3154 #ifdef FEATURE_HTTPS_INSPECTION
3155 close_client_and_server_ssl_connections(csp);
3161 byte_count += (unsigned long long)len;
3167 * We're still looking for the end of the server's header.
3168 * Buffer up the data we just read. If that fails, there's
3169 * little we can do but send our static out-of-memory page.
3171 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3173 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3174 rsp = cgi_error_memory();
3175 send_crunch_response(csp, rsp);
3176 mark_server_socket_tainted(csp);
3177 #ifdef FEATURE_HTTPS_INSPECTION
3178 close_client_and_server_ssl_connections(csp);
3183 /* Convert iob into something sed() can digest */
3184 if (JB_ERR_PARSE == get_server_headers(csp))
3189 * Well, we tried our MS IIS/5 hack and it didn't work.
3190 * The header is incomplete and there isn't anything
3191 * we can do about it.
3193 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3194 "Applying the MS IIS5 hack didn't help.");
3195 log_error(LOG_LEVEL_CLF,
3196 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3197 #ifdef FEATURE_HTTPS_INSPECTION
3199 * Sending data with standard or secured connection (HTTP/HTTPS)
3201 if (client_use_ssl(csp))
3203 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3204 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3205 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3208 #endif /* def FEATURE_HTTPS_INSPECTION */
3210 write_socket_delayed(csp->cfd,
3211 INVALID_SERVER_HEADERS_RESPONSE,
3212 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3214 mark_server_socket_tainted(csp);
3215 #ifdef FEATURE_HTTPS_INSPECTION
3216 close_client_and_server_ssl_connections(csp);
3223 * Since we have to wait for more from the server before
3224 * we can parse the headers we just continue here.
3226 log_error(LOG_LEVEL_CONNECT,
3227 "Continuing buffering server headers from socket %d. "
3228 "Bytes most recently read: %d.", csp->cfd, len);
3235 * Account for the content bytes we
3236 * might have gotten with the headers.
3238 assert(csp->iob->eod >= csp->iob->cur);
3239 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3242 /* Did we actually get anything? */
3243 if (NULL == csp->headers->first)
3245 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3247 log_error(LOG_LEVEL_ERROR,
3248 "No server or forwarder response received on socket %d. "
3249 "Closing client socket %d without sending data.",
3250 csp->server_connection.sfd, csp->cfd);
3251 log_error(LOG_LEVEL_CLF,
3252 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3256 log_error(LOG_LEVEL_ERROR,
3257 "No server or forwarder response received on socket %d.",
3258 csp->server_connection.sfd);
3259 send_crunch_response(csp, error_response(csp, "no-server-data"));
3261 free_http_request(http);
3262 mark_server_socket_tainted(csp);
3263 #ifdef FEATURE_HTTPS_INSPECTION
3264 close_client_and_server_ssl_connections(csp);
3269 if (!csp->headers->first->str)
3271 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3273 assert(csp->headers->first->str);
3275 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3276 strncmpic(csp->headers->first->str, "ICY", 3))
3279 * It doesn't look like a HTTP (or Shoutcast) response:
3280 * tell the client and log the problem.
3282 if (strlen(csp->headers->first->str) > 30)
3284 csp->headers->first->str[30] = '\0';
3286 log_error(LOG_LEVEL_ERROR,
3287 "Invalid server or forwarder response. Starts with: %s",
3288 csp->headers->first->str);
3289 log_error(LOG_LEVEL_CLF,
3290 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3291 #ifdef FEATURE_HTTPS_INSPECTION
3293 * Sending data with standard or secured connection (HTTP/HTTPS)
3295 if (client_use_ssl(csp))
3297 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3298 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3299 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3302 #endif /* def FEATURE_HTTPS_INSPECTION */
3304 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3305 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3307 free_http_request(http);
3308 mark_server_socket_tainted(csp);
3309 #ifdef FEATURE_HTTPS_INSPECTION
3310 close_client_and_server_ssl_connections(csp);
3316 * We have now received the entire server header,
3317 * filter it and send the result to the client
3319 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3321 log_error(LOG_LEVEL_CLF,
3322 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3323 #ifdef FEATURE_HTTPS_INSPECTION
3325 * Sending data with standard or secured connection (HTTP/HTTPS)
3327 if (client_use_ssl(csp))
3329 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3330 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3331 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3336 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3337 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3339 free_http_request(http);
3340 mark_server_socket_tainted(csp);
3341 #ifdef FEATURE_HTTPS_INSPECTION
3342 close_client_and_server_ssl_connections(csp);
3346 hdr = list_to_text(csp->headers);
3349 /* FIXME Should handle error properly */
3350 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3353 if ((csp->flags & CSP_FLAG_CHUNKED)
3354 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3355 && ((csp->iob->eod - csp->iob->cur) >= 5)
3356 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3358 log_error(LOG_LEVEL_CONNECT,
3359 "Looks like we got the last chunk together with "
3360 "the server headers. We better stop reading.");
3361 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3362 csp->expected_content_length = byte_count;
3363 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3366 csp->server_connection.response_received = time(NULL);
3368 if (crunch_response_triggered(csp, crunchers_light))
3371 * One of the tags created by a server-header
3372 * tagger triggered a crunch. We already
3373 * delivered the crunch response to the client
3374 * and are done here after cleaning up.
3377 mark_server_socket_tainted(csp);
3378 #ifdef FEATURE_HTTPS_INSPECTION
3379 close_client_and_server_ssl_connections(csp);
3384 /* Buffer and pcrs filter this if appropriate. */
3385 buffer_and_filter_content = content_requires_filtering(csp);
3387 if (!buffer_and_filter_content)
3390 * Write the server's (modified) header to
3391 * the client (along with anything else that
3392 * may be in the buffer). Use standard or secured
3395 #ifdef FEATURE_HTTPS_INSPECTION
3396 if (client_use_ssl(csp))
3398 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3399 (const unsigned char *)hdr, strlen(hdr)) < 0)
3400 || (len = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3403 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3406 * The write failed, so don't bother mentioning it
3407 * to the client... it probably can't hear us anyway.
3410 mark_server_socket_tainted(csp);
3411 #ifdef FEATURE_HTTPS_INSPECTION
3412 close_client_and_server_ssl_connections(csp);
3418 #endif /* def FEATURE_HTTPS_INSPECTION */
3420 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3421 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3423 log_error(LOG_LEVEL_ERROR,
3424 "write header to client failed");
3426 * The write failed, so don't bother mentioning it
3427 * to the client... it probably can't hear us anyway.
3430 mark_server_socket_tainted(csp);
3431 #ifdef FEATURE_HTTPS_INSPECTION
3432 close_client_and_server_ssl_connections(csp);
3439 /* we're finished with the server's header */
3445 * If this was a MS IIS/5 hack then it means the server
3446 * has already closed the connection. Nothing more to read.
3451 log_error(LOG_LEVEL_ERROR,
3452 "Closed server connection detected. "
3453 "Applying the MS IIS5 hack didn't help.");
3454 log_error(LOG_LEVEL_CLF,
3455 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3456 #ifdef FEATURE_HTTPS_INSPECTION
3458 * Sending data with standard or secured connection (HTTP/HTTPS)
3460 if (client_use_ssl(csp))
3462 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3463 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3464 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3467 #endif /* def FEATURE_HTTPS_INSPECTION */
3469 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3470 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3472 mark_server_socket_tainted(csp);
3473 #ifdef FEATURE_HTTPS_INSPECTION
3474 close_client_and_server_ssl_connections(csp);
3481 mark_server_socket_tainted(csp);
3482 #ifdef FEATURE_HTTPS_INSPECTION
3483 close_client_and_server_ssl_connections(csp);
3485 return; /* huh? we should never get here */
3487 #ifdef FEATURE_HTTPS_INSPECTION
3488 close_client_and_server_ssl_connections(csp);
3490 if (csp->content_length == 0)
3493 * If Privoxy didn't recalculate the Content-Length,
3494 * byte_count is still correct.
3496 csp->content_length = byte_count;
3499 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3500 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3501 && (csp->expected_content_length != byte_count))
3503 log_error(LOG_LEVEL_CONNECT,
3504 "Received %llu bytes while expecting %llu.",
3505 byte_count, csp->expected_content_length);
3506 mark_server_socket_tainted(csp);
3510 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3511 csp->ip_addr_str, http->ocmd, csp->content_length);
3513 csp->server_connection.timestamp = time(NULL);
3517 /*********************************************************************
3521 * Description : Once a connection from the client has been accepted,
3522 * this function is called (via serve()) to handle the
3523 * main business of the communication. This function
3524 * returns after dealing with a single request. It can
3525 * be called multiple times with the same client socket
3526 * if the client is keeping the connection alive.
3528 * The decision whether or not a client connection will
3529 * be kept alive is up to the caller which also must
3530 * close the client socket when done.
3532 * FIXME: chat is nearly thousand lines long.
3536 * 1 : csp = Current client state (buffers, headers, etc...)
3538 * Returns : Nothing.
3540 *********************************************************************/
3541 static void chat(struct client_state *csp)
3543 const struct forward_spec *fwd;
3544 struct http_request *http;
3545 /* Skeleton for HTTP response, if we should intercept the request */
3546 struct http_response *rsp;
3547 #ifdef FEATURE_HTTPS_INSPECTION
3548 int use_ssl_tunnel = 0;
3553 if (receive_client_request(csp) != JB_ERR_OK)
3557 if (parse_client_request(csp) != JB_ERR_OK)
3562 /* decide how to route the HTTP request */
3563 fwd = forward_url(csp, http);
3566 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
3567 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3571 #ifdef FEATURE_HTTPS_INSPECTION
3573 * Setting flags to use old solution with SSL tunnel and to disable
3574 * certificates verification.
3576 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3581 if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3583 csp->dont_verify_certificate = 1;
3588 * build the http request to send to the server
3589 * we have to do one of the following:
3591 * create = use the original HTTP request to create a new
3592 * HTTP request that has either the path component
3593 * without the http://domainspec (w/path) or the
3594 * full orininal URL (w/url)
3595 * Note that the path and/or the HTTP version may
3596 * have been altered by now.
3598 * SSL proxy = Open a socket to the host:port of the server
3599 * and create TLS/SSL connection with server and
3600 * with client. Then behave like mediator between
3601 * client and server over TLS/SSL.
3603 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3604 * with request to a parent proxy. Note that we'll be sending
3605 * forwarding the CFAIL message ourselves if connecting to the parent
3606 * fails, but we won't send a CSUCCEED message if it works,
3607 * since that would result in a double message (ours and the
3608 * parent's). After sending the request to the parent, we
3609 * must parse answer and send it to client. If connection
3610 * with server is established, we do TLS/SSL proxy. Otherwise
3611 * we send parent response to client and close connections.
3613 * here's the matrix:
3616 * +--------+--------+
3618 * 0 | create | SSL |
3619 * | w/path | proxy |
3620 * Forwarding +--------+--------+
3622 * 1 | create | proxy |
3623 * | w/url |+forward|
3624 * +--------+--------+
3628 #ifdef FEATURE_HTTPS_INSPECTION
3630 * Presetting SSL client and server flags
3632 if (http->ssl && !use_ssl_tunnel)
3634 http->client_ssl = 1;
3635 http->server_ssl = 1;
3639 http->client_ssl = 0;
3640 http->server_ssl = 0;
3644 if (http->ssl && connect_port_is_forbidden(csp))
3646 const char *acceptable_connect_ports =
3647 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3648 assert(NULL != acceptable_connect_ports);
3649 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3650 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3651 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3652 csp->action->flags |= ACTION_BLOCK;
3654 #ifdef FEATURE_HTTPS_INSPECTION
3655 http->client_ssl = 0;
3656 http->server_ssl = 0;
3661 freez(csp->headers->first->str);
3662 build_request_line(csp, fwd, &csp->headers->first->str);
3665 * We have a request. Check if one of the crunchers wants it
3666 * unless the client wants to use TLS/SSL in which case we
3667 * haven't setup the TLS context yet and will send the crunch
3671 #ifdef FEATURE_HTTPS_INSPECTION
3672 !client_use_ssl(csp) &&
3674 crunch_response_triggered(csp, crunchers_all))
3677 * Yes. The client got the crunch response and we're done here.
3682 log_applied_actions(csp->action);
3683 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
3685 if (fwd->forward_host)
3687 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3688 fwd->forward_host, fwd->forward_port, http->hostport);
3692 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3695 /* here we connect to the server, gateway, or the forwarder */
3697 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3698 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3699 && socket_is_still_alive(csp->server_connection.sfd)
3700 && connection_destination_matches(&csp->server_connection, http, fwd))
3702 log_error(LOG_LEVEL_CONNECT,
3703 "Reusing server socket %d connected to %s. Total requests: %u.",
3704 csp->server_connection.sfd, csp->server_connection.host,
3705 csp->server_connection.requests_sent_total);
3709 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3711 #ifdef FEATURE_CONNECTION_SHARING
3712 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3714 remember_connection(&csp->server_connection);
3717 #endif /* def FEATURE_CONNECTION_SHARING */
3719 log_error(LOG_LEVEL_CONNECT,
3720 "Closing server socket %d connected to %s. Total requests: %u.",
3721 csp->server_connection.sfd, csp->server_connection.host,
3722 csp->server_connection.requests_sent_total);
3723 close_socket(csp->server_connection.sfd);
3725 mark_connection_closed(&csp->server_connection);
3727 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3728 #ifdef FEATURE_HTTPS_INSPECTION
3729 if (http->ssl && !use_ssl_tunnel)
3733 * Creating an SSL proxy. If forwarding is disabled, we must send
3734 * CSUCCEED mesage to client. Then TLS/SSL connection with client
3738 if (fwd->forward_host == NULL)
3741 * We're lying to the client as the connection hasn't actually
3742 * been established yet. We don't establish the connection until
3743 * we have seen and parsed the encrypted client headers.
3745 if (write_socket_delayed(csp->cfd, CSUCCEED,
3746 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3748 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3753 ret = create_client_ssl_connection(csp);
3756 log_error(LOG_LEVEL_ERROR,
3757 "Can't open secure connection with client");
3758 close_client_ssl_connection(csp); /* XXX: Is this needed? */
3761 if (JB_ERR_OK != process_encrypted_request(csp))
3763 log_error(LOG_LEVEL_ERROR, "Failed to parse encrypted request.");
3764 close_client_ssl_connection(csp);
3768 * We have an encrypted request. Check if one of the crunchers now
3769 * wants it (for example because the previously invisible path was
3770 * required to match).
3772 if (crunch_response_triggered(csp, crunchers_all))
3775 * Yes. The client got the crunch response and we're done here.
3777 close_client_ssl_connection(csp);
3783 * Connecting to destination server
3785 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3787 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3789 if (fwd->type != SOCKS_NONE)
3792 rsp = error_response(csp, "forwarding-failed");
3794 else if (errno == EINVAL)
3796 rsp = error_response(csp, "no-such-domain");
3800 rsp = error_response(csp, "connect-failed");
3803 /* Write the answer to the client */
3806 send_crunch_response(csp, rsp);
3810 * Temporary workaround to prevent already-read client
3811 * bodies from being parsed as new requests. For now we
3812 * err on the safe side and throw all the following
3813 * requests under the bus, even if no client body has been
3814 * buffered. A compliant client will repeat the dropped
3815 * requests on an untainted connection.
3817 * The proper fix is to discard the no longer needed
3818 * client body in the buffer (if there is one) and to
3819 * continue parsing the bytes that follow.
3821 drain_and_close_socket(csp->cfd);
3822 csp->cfd = JB_INVALID_SOCKET;
3827 #ifdef FEATURE_HTTPS_INSPECTION
3829 * Creating TLS/SSL connections with destination server or parent
3830 * proxy. If forwarding is enabled, we must send client request to
3831 * parent proxy and receive, parse and resend parent proxy answer.
3833 if (http->ssl && !use_ssl_tunnel)
3835 if (fwd->forward_host != NULL)
3837 char server_response[BUFFER_SIZE];
3840 char *hdr = list_to_text(csp->headers);
3841 memset(server_response, 0, sizeof(server_response));
3845 log_error(LOG_LEVEL_FATAL,
3846 "Out of memory parsing client header");
3848 list_remove_all(csp->headers);
3851 * Sending client's CONNECT request to the parent proxy
3853 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
3859 log_error(LOG_LEVEL_CONNECT,
3860 "Sending request headers to: %s failed", http->hostport);
3861 mark_server_socket_tainted(csp);
3862 close_client_ssl_connection(csp);
3866 /* Waiting for parent proxy server response */
3867 len = read_socket(csp->server_connection.sfd, server_response,
3868 sizeof(server_response)-1);
3872 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
3873 "server on socket %d.", csp->server_connection.sfd);
3875 rsp = error_response(csp, "no-server-data");
3878 send_crunch_response(csp, rsp);
3880 mark_server_socket_tainted(csp);
3881 close_client_ssl_connection(csp);
3886 * Test if connection with destination server was established
3887 * successfully by parent proxy. Then we can send response to
3888 * the client and continue or stop.
3890 if (!tunnel_established_successfully(server_response, (unsigned int)len))
3892 log_error(LOG_LEVEL_ERROR, "Forwarder hasn't established "
3893 "connection with destination server.");
3895 write_socket(csp->cfd, server_response, (size_t)len);
3896 mark_server_socket_tainted(csp);
3897 close_client_ssl_connection(csp);
3902 * Parent proxy has established connection with destination server.
3903 * Now we must create TLS/SSL connection with parent proxy.
3905 ret = create_server_ssl_connection(csp);
3908 * If TLS/SSL connection wasn't created and invalid certificate
3909 * wasn't detected, we can interrupt this function. Otherwise, we
3910 * must inform the client about invalid server certificate.
3913 && (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3914 || csp->server_cert_verification_result == SSL_CERT_VALID))
3916 rsp = error_response(csp, "connect-failed");
3919 send_crunch_response(csp, rsp);
3925 * TLS/SSL connection with parent proxy is established, we can
3926 * inform client about success.
3928 ret = write_socket(csp->cfd, server_response, (size_t)len);
3931 log_error(LOG_LEVEL_ERROR,
3932 "Sending parent proxy response to client failed");
3933 mark_server_socket_tainted(csp);
3934 close_client_ssl_connection(csp);
3937 }/* -END- if (fwd->forward_host != NULL) */
3941 * Parent proxy is not used, we can just create TLS/SSL connection
3942 * with destination server
3944 int ret = create_server_ssl_connection(csp);
3947 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
3948 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
3951 * If the server certificate is invalid, we must inform
3952 * the client and then close connection to the client.
3954 ssl_send_certificate_error(csp);
3955 close_client_and_server_ssl_connections(csp);
3958 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3959 || csp->server_cert_verification_result == SSL_CERT_VALID)
3962 * The TLS/SSL connection wasn't created but an invalid
3963 * certificate wasn't detected. Report it as connection
3966 rsp = error_response(csp, "connect-failed");
3969 send_crunch_response(csp, rsp);
3975 }/* -END- if (http->ssl) */
3976 #endif /* def FEATURE_HTTPS_INSPECTION */
3978 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3979 save_connection_destination(csp->server_connection.sfd,
3980 http, fwd, &csp->server_connection);
3981 csp->server_connection.keep_alive_timeout =
3982 (unsigned)csp->config->keep_alive_timeout;
3984 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3986 csp->server_connection.requests_sent_total++;
3988 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
3990 /* Client headers have been sent optimistically */
3991 assert(csp->headers->last == NULL);
3993 else if (http->ssl == 0 || (fwd->forward_host
3994 #ifdef FEATURE_HTTPS_INSPECTION
3999 if (send_http_request(csp))
4001 rsp = error_response(csp, "connect-failed");
4004 send_crunch_response(csp, rsp);
4012 * Using old solution with SSL tunnel or new solution with SSL proxy
4014 list_remove_all(csp->headers);
4015 #ifdef FEATURE_HTTPS_INSPECTION
4020 * We're running an SSL tunnel and we're not forwarding,
4021 * so just ditch the client headers, send the "connect succeeded"
4022 * message to the client, flush the rest, and get out of the way.
4024 if (write_socket_delayed(csp->cfd, CSUCCEED,
4025 strlen(CSUCCEED), get_write_delay(csp)))
4030 #ifdef FEATURE_HTTPS_INSPECTION
4034 * If server certificate is invalid, we must inform client and then
4035 * close connection with client.
4037 if (csp->server_cert_verification_result != SSL_CERT_VALID)
4039 ssl_send_certificate_error(csp);
4040 close_client_and_server_ssl_connections(csp);
4043 if (send_https_request(csp))
4045 rsp = error_response(csp, "connect-failed");
4048 send_crunch_response(csp, rsp);
4050 close_client_and_server_ssl_connections(csp);
4054 #endif /* def FEATURE_HTTPS_INSPECTION */
4055 clear_iob(csp->client_iob);
4056 }/* -END- else ... if (http->ssl == 1) */
4058 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4060 /* XXX: should the time start earlier for optimistically sent data? */
4061 csp->server_connection.request_sent = time(NULL);
4063 handle_established_connection(csp);
4064 freez(csp->receive_buffer);
4069 /*********************************************************************
4071 * Function : fuzz_server_response
4073 * Description : Treat the input as a whole server response.
4076 * 1 : csp = Current client state (buffers, headers, etc...)
4077 * 2 : fuzz_input_file = File to read the input from.
4081 *********************************************************************/
4082 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4084 static struct forward_spec fwd; /* Zero'd due to being static */
4087 if (strcmp(fuzz_input_file, "-") == 0)
4089 /* XXX: Doesn'T work yet. */
4090 csp->server_connection.sfd = 0;
4094 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4095 if (csp->server_connection.sfd == -1)
4097 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4102 csp->content_type |= CT_GIF;
4103 csp->action->flags |= ACTION_DEANIMATE;
4104 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4106 csp->http->path = strdup_or_die("/");
4107 csp->http->host = strdup_or_die("fuzz.example.org");
4108 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4109 /* Prevent client socket monitoring */
4110 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4111 csp->flags |= CSP_FLAG_CHUNKED;
4113 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4114 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4116 csp->content_type |= CT_DECLARED|CT_GIF;
4118 csp->config->socket_timeout = 0;
4120 cgi_init_error_messages();
4122 handle_established_connection(csp);
4123 freez(csp->receive_buffer);
4130 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4131 /*********************************************************************
4133 * Function : prepare_csp_for_next_request
4135 * Description : Put the csp in a mostly vergin state.
4138 * 1 : csp = Current client state (buffers, headers, etc...)
4142 *********************************************************************/
4143 static void prepare_csp_for_next_request(struct client_state *csp)
4145 csp->content_type = 0;
4146 csp->content_length = 0;
4147 csp->expected_content_length = 0;
4148 csp->expected_client_content_length = 0;
4149 list_remove_all(csp->headers);
4150 clear_iob(csp->iob);
4151 freez(csp->error_message);
4152 free_http_request(csp->http);
4153 destroy_list(csp->headers);
4154 destroy_list(csp->tags);
4155 #ifdef FEATURE_CLIENT_TAGS
4156 destroy_list(csp->client_tags);
4157 freez(csp->client_address);
4159 free_current_action(csp->action);
4160 if (NULL != csp->fwd)
4162 unload_forward_spec(csp->fwd);
4165 /* XXX: Store per-connection flags someplace else. */
4166 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4167 #ifdef FEATURE_TOGGLE
4168 if (global_toggle_state)
4169 #endif /* def FEATURE_TOGGLE */
4171 csp->flags |= CSP_FLAG_TOGGLED_ON;
4174 if (csp->client_iob->eod > csp->client_iob->cur)
4176 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4177 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4179 assert(bytes_to_shift > 0);
4180 assert(data_length > 0);
4182 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
4183 data_length, bytes_to_shift);
4184 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4185 csp->client_iob->cur = csp->client_iob->buf;
4186 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4187 csp->client_iob->eod = csp->client_iob->buf + data_length;
4188 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4190 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4195 * We mainly care about resetting client_iob->cur so we don't
4196 * waste buffer space at the beginning and don't mess up the
4197 * request restoration done by cgi_show_request().
4199 * Freeing the buffer itself isn't technically necessary,
4200 * but makes debugging more convenient.
4202 clear_iob(csp->client_iob);
4205 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4208 /*********************************************************************
4212 * Description : This is little more than chat. We only "serve" to
4213 * to close (or remember) any socket that chat may have
4217 * 1 : csp = Current client state (buffers, headers, etc...)
4221 *********************************************************************/
4222 static void serve(struct client_state *csp)
4224 int config_file_change_detected = 0; /* Only used for debugging */
4225 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4226 #ifdef FEATURE_CONNECTION_SHARING
4227 static int monitor_thread_running = 0;
4228 #endif /* def FEATURE_CONNECTION_SHARING */
4229 int continue_chatting = 0;
4231 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4232 csp->ip_addr_str, csp->cfd);
4236 unsigned int latency;
4241 * If the request has been crunched,
4242 * the calculated latency is zero.
4244 latency = (unsigned)(csp->server_connection.response_received -
4245 csp->server_connection.request_sent) / 2;
4247 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4248 && (csp->flags & CSP_FLAG_CRUNCHED)
4249 && (csp->expected_client_content_length != 0))
4251 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4252 log_error(LOG_LEVEL_CONNECT,
4253 "Tainting client socket %d due to unread data.", csp->cfd);
4256 continue_chatting = (csp->config->feature_flags
4257 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4258 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4259 && (csp->cfd != JB_INVALID_SOCKET)
4260 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4261 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4262 || (csp->flags & CSP_FLAG_CHUNKED));
4264 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4265 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4267 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4269 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4271 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4272 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4273 || !socket_is_still_alive(csp->server_connection.sfd)
4274 || !(latency < csp->server_connection.keep_alive_timeout))
4276 log_error(LOG_LEVEL_CONNECT,
4277 "Closing server socket %d connected to %s. "
4278 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
4279 csp->server_connection.sfd, csp->server_connection.host,
4280 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4281 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4282 socket_is_still_alive(csp->server_connection.sfd),
4283 csp->server_connection.keep_alive_timeout);
4284 #ifdef FEATURE_CONNECTION_SHARING
4285 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4287 forget_connection(csp->server_connection.sfd);
4289 #endif /* def FEATURE_CONNECTION_SHARING */
4290 close_socket(csp->server_connection.sfd);
4291 mark_connection_closed(&csp->server_connection);
4295 if (continue_chatting && any_loaded_file_changed(csp))
4297 continue_chatting = 0;
4298 config_file_change_detected = 1;
4301 if (continue_chatting)
4303 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4304 && socket_is_still_alive(csp->cfd))
4306 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4307 "pipelined on socket %d and the socket is still alive.",
4308 csp->requests_received_total+1, csp->cfd);
4309 prepare_csp_for_next_request(csp);
4313 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4315 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4317 log_error(LOG_LEVEL_CONNECT,
4318 "Waiting for the next client request on socket %d. "
4319 "Keeping the server socket %d to %s open.",
4320 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4324 log_error(LOG_LEVEL_CONNECT,
4325 "Waiting for the next client request on socket %d. "
4326 "No server socket to keep open.", csp->cfd);
4330 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4331 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4332 && socket_is_still_alive(csp->cfd))
4334 log_error(LOG_LEVEL_CONNECT,
4335 "Client request %u arrived in time on socket %d.",
4336 csp->requests_received_total+1, csp->cfd);
4337 prepare_csp_for_next_request(csp);
4341 #ifdef FEATURE_CONNECTION_SHARING
4342 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4343 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4344 && (socket_is_still_alive(csp->server_connection.sfd)))
4346 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4348 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4353 remember_connection(&csp->server_connection);
4354 csp->server_connection.sfd = JB_INVALID_SOCKET;
4355 drain_and_close_socket(csp->cfd);
4356 csp->cfd = JB_INVALID_SOCKET;
4357 privoxy_mutex_lock(&connection_reuse_mutex);
4358 if (!monitor_thread_running)
4360 monitor_thread_running = 1;
4361 privoxy_mutex_unlock(&connection_reuse_mutex);
4362 wait_for_alive_connections();
4363 privoxy_mutex_lock(&connection_reuse_mutex);
4364 monitor_thread_running = 0;
4366 privoxy_mutex_unlock(&connection_reuse_mutex);
4368 #endif /* def FEATURE_CONNECTION_SHARING */
4372 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4374 log_error(LOG_LEVEL_CONNECT,
4375 "Closing server socket %d connected to %s. Keep-alive: %u. "
4376 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4377 "Configuration file change detected: %u",
4378 csp->server_connection.sfd, csp->server_connection.host,
4379 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4380 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4381 socket_is_still_alive(csp->server_connection.sfd),
4382 csp->server_connection.keep_alive_timeout,
4383 config_file_change_detected);
4385 } while (continue_chatting);
4389 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4391 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4393 #ifdef FEATURE_CONNECTION_SHARING
4394 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4396 forget_connection(csp->server_connection.sfd);
4398 #endif /* def FEATURE_CONNECTION_SHARING */
4399 close_socket(csp->server_connection.sfd);
4402 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4403 mark_connection_closed(&csp->server_connection);
4406 if (csp->cfd != JB_INVALID_SOCKET)
4408 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4409 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4410 "Configuration file change detected: %u. Requests received: %u.",
4411 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4412 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4413 config_file_change_detected, csp->requests_received_total);
4414 drain_and_close_socket(csp->cfd);
4417 free_csp_resources(csp);
4419 csp->flags &= ~CSP_FLAG_ACTIVE;
4425 /*********************************************************************
4427 * Function : server_thread
4429 * Description : We only exist to call `serve' in a threaded environment.
4432 * 1 : data = Current client state (buffers, headers, etc...)
4434 * Returns : Always 0.
4436 *********************************************************************/
4437 static int32 server_thread(void *data)
4439 serve((struct client_state *) data);
4446 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4447 /*********************************************************************
4451 * Description : Print usage info & exit.
4453 * Parameters : Pointer to argv[0] for identifying ourselves
4457 *********************************************************************/
4458 static void usage(const char *name)
4460 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4461 "Usage: %s [--config-test] "
4464 #endif /* defined(unix) */
4467 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4468 #endif /* defined(unix) */
4469 "[--version] [configfile]\n",
4473 show_fuzz_usage(name);
4476 printf("Aborting\n");
4481 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4484 #ifdef MUTEX_LOCKS_AVAILABLE
4485 /*********************************************************************
4487 * Function : privoxy_mutex_lock
4489 * Description : Locks a mutex.
4492 * 1 : mutex = The mutex to lock.
4494 * Returns : Void. May exit in case of errors.
4496 *********************************************************************/
4497 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4499 #ifdef FEATURE_PTHREAD
4500 int err = pthread_mutex_lock(mutex);
4503 if (mutex != &log_mutex)
4505 log_error(LOG_LEVEL_FATAL,
4506 "Mutex locking failed: %s.\n", strerror(err));
4511 EnterCriticalSection(mutex);
4512 #endif /* def FEATURE_PTHREAD */
4516 /*********************************************************************
4518 * Function : privoxy_mutex_unlock
4520 * Description : Unlocks a mutex.
4523 * 1 : mutex = The mutex to unlock.
4525 * Returns : Void. May exit in case of errors.
4527 *********************************************************************/
4528 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4530 #ifdef FEATURE_PTHREAD
4531 int err = pthread_mutex_unlock(mutex);
4534 if (mutex != &log_mutex)
4536 log_error(LOG_LEVEL_FATAL,
4537 "Mutex unlocking failed: %s.\n", strerror(err));
4542 LeaveCriticalSection(mutex);
4543 #endif /* def FEATURE_PTHREAD */
4547 /*********************************************************************
4549 * Function : privoxy_mutex_init
4551 * Description : Prepares a mutex.
4554 * 1 : mutex = The mutex to initialize.
4556 * Returns : Void. May exit in case of errors.
4558 *********************************************************************/
4559 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4561 #ifdef FEATURE_PTHREAD
4562 int err = pthread_mutex_init(mutex, 0);
4565 printf("Fatal error. Mutex initialization failed: %s.\n",
4570 InitializeCriticalSection(mutex);
4571 #endif /* def FEATURE_PTHREAD */
4573 #endif /* def MUTEX_LOCKS_AVAILABLE */
4575 /*********************************************************************
4577 * Function : initialize_mutexes
4579 * Description : Prepares mutexes if mutex support is available.
4583 * Returns : Void, exits in case of errors.
4585 *********************************************************************/
4586 static void initialize_mutexes(void)
4588 #ifdef MUTEX_LOCKS_AVAILABLE
4590 * Prepare global mutex semaphores
4593 #ifdef LIMIT_MUTEX_NUMBER
4595 for (i = 0; i < 32; i++)
4598 for (i = 0; i < 65536; i++)
4599 #endif /* LIMIT_MUTEX_NUMBER */
4601 privoxy_mutex_init(&(certificates_mutexes[i]));
4603 privoxy_mutex_init(&rng_mutex);
4605 privoxy_mutex_init(&log_mutex);
4606 privoxy_mutex_init(&log_init_mutex);
4607 privoxy_mutex_init(&connection_reuse_mutex);
4608 #ifdef FEATURE_EXTERNAL_FILTERS
4609 privoxy_mutex_init(&external_filter_mutex);
4611 #ifdef FEATURE_CLIENT_TAGS
4612 privoxy_mutex_init(&client_tags_mutex);
4616 * XXX: The assumptions below are a bit naive
4617 * and can cause locks that aren't necessary.
4619 * For example older FreeBSD versions (< 6.x?)
4620 * have no gethostbyname_r, but gethostbyname is
4623 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4624 privoxy_mutex_init(&resolver_mutex);
4625 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4627 * XXX: should we use a single mutex for
4628 * localtime() and gmtime() as well?
4630 #ifndef HAVE_GMTIME_R
4631 privoxy_mutex_init(&gmtime_mutex);
4632 #endif /* ndef HAVE_GMTIME_R */
4634 #ifndef HAVE_LOCALTIME_R
4635 privoxy_mutex_init(&localtime_mutex);
4636 #endif /* ndef HAVE_GMTIME_R */
4638 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4639 privoxy_mutex_init(&rand_mutex);
4640 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4642 #endif /* def MUTEX_LOCKS_AVAILABLE */
4645 /*********************************************************************
4649 * Description : Load the config file and start the listen loop.
4650 * This function is a lot more *sane* with the `load_config'
4651 * and `listen_loop' functions; although it stills does
4652 * a *little* too much for my taste.
4655 * 1 : argc = Number of parameters (including $0).
4656 * 2 : argv = Array of (char *)'s to the parameters.
4658 * Returns : 1 if : can't open config file, unrecognized directive,
4659 * stats requested in multi-thread mode, can't open the
4660 * log file, can't open the jar file, listen port is invalid,
4661 * any load fails, and can't bind port.
4663 * Else main never returns, the process must be signaled
4664 * to terminate execution. Or, on Windows, use the
4665 * "File", "Exit" menu option.
4667 *********************************************************************/
4669 int real_main(int argc, char **argv)
4671 int main(int argc, char **argv)
4675 int do_config_test = 0;
4676 #ifndef HAVE_ARC4RANDOM
4677 unsigned int random_seed;
4680 struct passwd *pw = NULL;
4681 struct group *grp = NULL;
4683 char *pre_chroot_nslookup_to_load_resolver = NULL;
4686 char *fuzz_input_type = NULL;
4687 char *fuzz_input_file = NULL;
4694 #if !defined(_WIN32)
4701 /* Prepare mutexes if supported and necessary. */
4702 initialize_mutexes();
4704 /* Enable logging until further notice. */
4708 * Parse the command line arguments
4710 * XXX: simply printing usage information in case of
4711 * invalid arguments isn't particularly user friendly.
4713 while (++argc_pos < argc)
4716 /* Check to see if the service must be installed or uninstalled */
4717 if (strncmp(argv[argc_pos], "--install", 9) == 0)
4719 const char *pName = argv[argc_pos] + 9;
4722 exit((install_service(pName)) ? 0 : 1);
4724 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4726 const char *pName = argv[argc_pos] + 11;
4729 exit((uninstall_service(pName)) ? 0 : 1);
4731 else if (strcmp(argv[argc_pos], "--service") == 0)
4733 bRunAsService = TRUE;
4734 w32_set_service_cwd();
4735 atexit(w32_service_exit_notify);
4738 #endif /* defined(_WIN32) */
4741 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4743 if (strcmp(argv[argc_pos], "--help") == 0)
4748 else if (strcmp(argv[argc_pos], "--version") == 0)
4750 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4756 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4758 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4762 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4764 if (++argc_pos == argc) usage(argv[0]);
4765 pidfile = strdup_or_die(argv[argc_pos]);
4768 else if (strcmp(argv[argc_pos], "--user") == 0)
4773 if (++argc_pos == argc) usage(argv[argc_pos]);
4775 user_arg = strdup_or_die(argv[argc_pos]);
4776 group_name = strchr(user_arg, '.');
4777 if (NULL != group_name)
4779 /* Nul-terminate the user name */
4782 /* Skip the former delimiter to actually reach the group name */
4785 grp = getgrnam(group_name);
4788 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4791 pw = getpwnam(user_arg);
4794 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4800 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4802 if (++argc_pos == argc) usage(argv[0]);
4803 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4806 else if (strcmp(argv[argc_pos], "--chroot") == 0)
4810 #endif /* defined(unix) */
4812 else if (strcmp(argv[argc_pos], "--config-test") == 0)
4817 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4820 if (argc < argc_pos + 2) usage(argv[0]);
4821 fuzz_input_type = argv[argc_pos];
4823 fuzz_input_file = argv[argc_pos];
4825 else if (strcmp(argv[argc_pos], "--stfu") == 0)
4827 set_debug_level(LOG_LEVEL_STFU);
4830 else if (argc_pos + 1 != argc)
4833 * This is neither the last command line
4834 * option, nor was it recognized before,
4835 * therefore it must be invalid.
4841 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4843 configfile = argv[argc_pos];
4846 } /* -END- while (more arguments) */
4848 show_version(Argv[0]);
4851 if (*configfile != '/')
4853 char cwd[BUFFER_SIZE];
4855 size_t abs_file_size;
4857 /* make config-filename absolute here */
4858 if (NULL == getcwd(cwd, sizeof(cwd)))
4860 perror("failed to get current working directory");
4864 basedir = strdup_or_die(cwd);
4866 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4867 abs_file = malloc_or_die(abs_file_size);
4868 strlcpy(abs_file, basedir, abs_file_size);
4869 strlcat(abs_file, "/", abs_file_size);
4870 strlcat(abs_file, configfile, abs_file_size);
4871 configfile = abs_file;
4873 #endif /* defined unix */
4877 clients->next = NULL;
4879 /* XXX: factor out initialising after the next stable release. */
4884 #ifndef HAVE_ARC4RANDOM
4885 random_seed = (unsigned int)time(NULL);
4887 srandom(random_seed);
4890 #endif /* ifdef HAVE_RANDOM */
4891 #endif /* ifndef HAVE_ARC4RANDOM */
4894 * Unix signal handling
4896 * Catch the abort, interrupt and terminate signals for a graceful exit
4897 * Catch the hangup signal so the errlog can be reopened.
4899 * Ignore the broken pipe signal as connection failures
4900 * are handled when and where they occur without relying
4903 #if !defined(_WIN32) && !defined(__OS2__)
4906 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
4908 for (idx = 0; idx < SZ(catched_signals); idx++)
4910 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
4911 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
4913 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
4914 #endif /* ifdef sun */
4916 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
4920 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4922 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
4926 #else /* ifdef _WIN32 */
4927 # ifdef _WIN_CONSOLE
4929 * We *are* in a windows console app.
4930 * Print a verbose messages about FAQ's and such
4932 printf("%s", win32_blurb);
4933 # endif /* def _WIN_CONSOLE */
4934 #endif /* def _WIN32 */
4937 if (fuzz_input_type != NULL)
4939 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
4941 log_error(LOG_LEVEL_FATAL,
4942 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
4943 "Various data structures are static which is unsafe when using threads.");
4948 exit(NULL == load_config());
4951 /* Initialize the CGI subsystem */
4952 cgi_init_error_messages();
4955 * If running on unix and without the --no-daemon
4956 * option, become a daemon. I.e. fork, detach
4957 * from tty and get process group leadership
4966 if (pid < 0) /* error */
4971 else if (pid != 0) /* parent */
4976 * must check for errors
4977 * child died due to missing files aso
4980 wpid = waitpid(pid, &status, WNOHANG);
4992 * stderr (fd 2) will be closed later on,
4993 * when the config file has been parsed.
4999 * Reserve fd 0 and 1 to prevent abort() and friends
5000 * from sending stuff to the clients or servers.
5002 fd = open("/dev/null", O_RDONLY);
5005 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5009 if (dup2(fd, 0) == -1)
5011 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5015 fd = open("/dev/null", O_WRONLY);
5018 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5022 if (dup2(fd, 1) == -1)
5024 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5029 #ifdef FEATURE_EXTERNAL_FILTERS
5030 for (fd = 0; fd < 3; fd++)
5032 mark_socket_for_close_on_execute(fd);
5038 } /* -END- if (daemon_mode) */
5041 * As soon as we have written the PID file, we can switch
5042 * to the user and group ID indicated by the --user option
5044 if (pidfile != NULL)
5046 write_pid_file(pidfile);
5050 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5052 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5056 if (setgroups(1, &grp->gr_gid))
5058 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5061 else if (initgroups(pw->pw_name, pw->pw_gid))
5063 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5069 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5071 /* Read the time zone file from /etc before doing chroot. */
5073 if (NULL != pre_chroot_nslookup_to_load_resolver
5074 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5076 /* Initialize resolver library. */
5077 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5079 if (chroot(pw->pw_dir) < 0)
5081 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5085 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5088 if (setuid(pw->pw_uid))
5090 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5094 char putenv_dummy[64];
5096 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5097 if (putenv(putenv_dummy) != 0)
5099 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5102 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5103 if (putenv(putenv_dummy) != 0)
5105 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5111 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5114 #endif /* defined unix */
5117 /* This will be FALSE unless the command line specified --service
5121 /* Yup, so now we must attempt to establish a connection
5122 * with the service dispatcher. This will only work if this
5123 * process was launched by the service control manager to
5124 * actually run as a service. If this isn't the case, i've
5125 * known it take around 30 seconds or so for the call to return.
5128 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5129 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5131 /* Service has run, and at this point is now being stopped, so just return */
5136 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5138 /* An error occurred. Usually it's because --service was wrongly specified
5139 * and we were unable to connect to the Service Control Dispatcher because
5140 * it wasn't expecting us and is therefore not listening.
5142 * For now, just continue below to call the listen_loop function.
5145 #endif /* def _WIN32 */
5155 /*********************************************************************
5157 * Function : bind_port_helper
5159 * Description : Bind the listen port. Handles logging, and aborts
5163 * 1 : haddr = Host address to bind to. Use NULL to bind to
5165 * 2 : hport = Specifies port to bind to.
5166 * 3 : backlog = Listen backlog.
5168 * Returns : Port that was opened.
5170 *********************************************************************/
5171 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5176 result = bind_port(haddr, hport, backlog, &bfd);
5180 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5184 log_error(LOG_LEVEL_FATAL,
5185 "can't bind to %s:%d: There may be another Privoxy "
5186 "or some other proxy running on port %d",
5187 bind_address, hport, hport);
5190 log_error(LOG_LEVEL_FATAL,
5191 "can't bind to %s:%d: The hostname is not resolvable",
5192 bind_address, hport);
5195 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5196 bind_address, hport);
5199 /* shouldn't get here */
5200 return JB_INVALID_SOCKET;
5205 if (bfd >= FD_SETSIZE)
5207 log_error(LOG_LEVEL_FATAL,
5208 "Bind socket number too high to use select(): %d >= %d",
5216 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5221 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5229 /*********************************************************************
5231 * Function : bind_ports_helper
5233 * Description : Bind the listen ports. Handles logging, and aborts
5237 * 1 : config = Privoxy configuration. Specifies ports
5239 * 2 : sockets = Preallocated array of opened sockets
5240 * corresponding to specification in config.
5241 * All non-opened sockets will be set to
5242 * JB_INVALID_SOCKET.
5244 * Returns : Nothing. Inspect sockets argument.
5246 *********************************************************************/
5247 static void bind_ports_helper(struct configuration_spec * config,
5248 jb_socket sockets[])
5252 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5254 if (config->hport[i])
5256 sockets[i] = bind_port_helper(config->haddr[i],
5257 config->hport[i], config->listen_backlog);
5258 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5259 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5261 struct accept_filter_arg af_options;
5262 bzero(&af_options, sizeof(af_options));
5263 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5264 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5265 sizeof(af_options)))
5267 log_error(LOG_LEVEL_ERROR,
5268 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5275 sockets[i] = JB_INVALID_SOCKET;
5278 config->need_bind = 0;
5282 /*********************************************************************
5284 * Function : close_ports_helper
5286 * Description : Close listenings ports.
5289 * 1 : sockets = Array of opened and non-opened sockets to
5290 * close. All sockets will be set to
5291 * JB_INVALID_SOCKET.
5293 * Returns : Nothing.
5295 *********************************************************************/
5296 static void close_ports_helper(jb_socket sockets[])
5300 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5302 if (JB_INVALID_SOCKET != sockets[i])
5304 close_socket(sockets[i]);
5306 sockets[i] = JB_INVALID_SOCKET;
5312 /* Without this simple workaround we get this compiler warning from _beginthread
5313 * warning C4028: formal parameter 1 different from declaration
5315 void w32_service_listen_loop(void *p)
5319 #endif /* def _WIN32 */
5322 /*********************************************************************
5324 * Function : listen_loop
5326 * Description : bind the listen port and enter a "FOREVER" listening loop.
5332 *********************************************************************/
5333 static void listen_loop(void)
5335 struct client_states *csp_list = NULL;
5336 struct client_state *csp = NULL;
5337 jb_socket bfds[MAX_LISTENING_SOCKETS];
5338 struct configuration_spec *config;
5339 unsigned int active_threads = 0;
5340 #if defined(FEATURE_PTHREAD)
5341 pthread_attr_t attrs;
5343 pthread_attr_init(&attrs);
5344 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5347 config = load_config();
5349 #ifdef FEATURE_CONNECTION_SHARING
5351 * XXX: Should be relocated once it no
5352 * longer needs to emit log messages.
5354 initialize_reusable_connections();
5355 #endif /* def FEATURE_CONNECTION_SHARING */
5357 bind_ports_helper(config, bfds);
5359 #ifdef FEATURE_GRACEFUL_TERMINATION
5360 while (!g_terminate)
5365 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
5366 while (waitpid(-1, NULL, WNOHANG) > 0)
5368 /* zombie children */
5370 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5373 * Free data that was used by died threads
5375 active_threads = sweep();
5379 * Re-open the errlog after HUP signal
5381 if (received_hup_signal)
5383 if (NULL != config->logfile)
5385 init_error_log(Argv[0], config->logfile);
5387 received_hup_signal = 0;
5391 csp_list = zalloc_or_die(sizeof(*csp_list));
5392 csp = &csp_list->csp;
5394 log_error(LOG_LEVEL_CONNECT,
5395 "Waiting for the next client connection. Currently active threads: %d",
5399 * This config may be outdated, but for accept_connection()
5400 * it's fresh enough.
5402 csp->config = config;
5404 if (!accept_connection(csp, bfds))
5406 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5411 csp->flags |= CSP_FLAG_ACTIVE;
5412 csp->server_connection.sfd = JB_INVALID_SOCKET;
5414 csp->config = config = load_config();
5416 if (config->need_bind)
5419 * Since we were listening to the "old port", we will not see
5420 * a "listen" param change until the next request. So, at
5421 * least 1 more request must be made for us to find the new
5422 * setting. I am simply closing the old socket and binding the
5425 * Which-ever is correct, we will serve 1 more page via the
5426 * old settings. This should probably be a "show-status"
5427 * request. This should not be a so common of an operation
5428 * that this will hurt people's feelings.
5431 close_ports_helper(bfds);
5433 bind_ports_helper(config, bfds);
5436 #ifdef FEATURE_TOGGLE
5437 if (global_toggle_state)
5438 #endif /* def FEATURE_TOGGLE */
5440 csp->flags |= CSP_FLAG_TOGGLED_ON;
5443 if (run_loader(csp))
5445 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5446 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5450 if (block_acl(NULL,csp))
5452 log_error(LOG_LEVEL_CONNECT,
5453 "Connection from %s on %s (socket %d) dropped due to ACL",
5454 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5455 close_socket(csp->cfd);
5456 freez(csp->ip_addr_str);
5457 freez(csp->listen_addr_str);
5461 #endif /* def FEATURE_ACL */
5463 if ((0 != config->max_client_connections)
5464 && (active_threads >= config->max_client_connections))
5466 log_error(LOG_LEVEL_CONNECT,
5467 "Rejecting connection from %s. Maximum number of connections reached.",
5469 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5470 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5471 close_socket(csp->cfd);
5472 freez(csp->ip_addr_str);
5473 freez(csp->listen_addr_str);
5478 /* add it to the list of clients */
5479 csp_list->next = clients->next;
5480 clients->next = csp_list;
5482 if (config->multi_threaded)
5486 /* this is a switch () statement in the C preprocessor - ugh */
5487 #undef SELECTED_ONE_OPTION
5489 /* Use Pthreads in preference to native code */
5490 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5491 #define SELECTED_ONE_OPTION
5493 pthread_t the_thread;
5495 errno = pthread_create(&the_thread, &attrs,
5496 (void * (*)(void *))serve, csp);
5497 child_id = errno ? -1 : 0;
5501 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5502 #define SELECTED_ONE_OPTION
5503 child_id = _beginthread(
5504 (void (*)(void *))serve,
5509 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
5510 #define SELECTED_ONE_OPTION
5511 child_id = _beginthread(
5512 (void(* _Optlink)(void*))serve,
5518 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5519 #define SELECTED_ONE_OPTION
5521 thread_id tid = spawn_thread
5522 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5524 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5526 child_id = (int) tid;
5535 #if !defined(SELECTED_ONE_OPTION)
5538 /* This block is only needed when using fork().
5539 * When using threads, the server thread was
5540 * created and run by the call to _beginthread().
5542 if (child_id == 0) /* child */
5545 #ifdef FEATURE_TOGGLE
5546 int inherited_toggle_state = global_toggle_state;
5547 #endif /* def FEATURE_TOGGLE */
5552 * If we've been toggled or we've blocked the request, tell Mom
5555 #ifdef FEATURE_TOGGLE
5556 if (inherited_toggle_state != global_toggle_state)
5558 rc |= RC_FLAG_TOGGLED;
5560 #endif /* def FEATURE_TOGGLE */
5562 #ifdef FEATURE_STATISTICS
5563 if (csp->flags & CSP_FLAG_REJECTED)
5565 rc |= RC_FLAG_BLOCKED;
5567 #endif /* ndef FEATURE_STATISTICS */
5571 else if (child_id > 0) /* parent */
5573 /* in a fork()'d environment, the parent's
5574 * copy of the client socket and the CSP
5578 #if !defined(_WIN32) && !defined(__CYGWIN__)
5580 wait(&child_status);
5583 * Evaluate child's return code: If the child has
5584 * - been toggled, toggle ourselves
5585 * - blocked its request, bump up the stats counter
5588 #ifdef FEATURE_TOGGLE
5589 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5591 global_toggle_state = !global_toggle_state;
5593 #endif /* def FEATURE_TOGGLE */
5595 #ifdef FEATURE_STATISTICS
5597 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5601 #endif /* def FEATURE_STATISTICS */
5603 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5604 close_socket(csp->cfd);
5605 csp->flags &= ~CSP_FLAG_ACTIVE;
5609 #undef SELECTED_ONE_OPTION
5610 /* end of cpp switch () */
5615 * Spawning the child failed, assume it's because
5616 * there are too many children running already.
5617 * XXX: If you assume ...
5619 log_error(LOG_LEVEL_ERROR,
5620 "Unable to take any additional connections: %E. Active threads: %d",
5622 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5623 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5624 close_socket(csp->cfd);
5625 csp->flags &= ~CSP_FLAG_ACTIVE;
5634 #if defined(FEATURE_PTHREAD)
5635 pthread_attr_destroy(&attrs);
5638 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5640 #ifdef FEATURE_HTTPS_INSPECTION
5641 /* Clean up. Aim: free all memory (no leaks) */
5642 if (rng_seeded == 1)
5644 mbedtls_ctr_drbg_free(&ctr_drbg);
5645 mbedtls_entropy_free(&entropy);
5649 #ifdef FEATURE_GRACEFUL_TERMINATION
5651 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
5653 unload_current_config_file();
5654 unload_current_actions_file();
5655 unload_current_re_filterfile();
5656 #ifdef FEATURE_TRUST
5657 unload_current_trust_file();
5660 if (config->multi_threaded)
5667 } while ((clients->next != NULL) && (--i > 0));
5671 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5681 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5682 /* Cleanup - remove taskbar icon etc. */
5687 #endif /* FEATURE_GRACEFUL_TERMINATION */