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(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 FEATURE_HTTPS_INSPECTION
197 privoxy_mutex_t certificate_mutex;
198 privoxy_mutex_t rng_mutex;
201 #ifdef FEATURE_EXTERNAL_FILTERS
202 privoxy_mutex_t external_filter_mutex;
204 #ifdef FEATURE_CLIENT_TAGS
205 privoxy_mutex_t client_tags_mutex;
208 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
209 privoxy_mutex_t resolver_mutex;
210 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
212 #ifndef HAVE_GMTIME_R
213 privoxy_mutex_t gmtime_mutex;
214 #endif /* ndef HAVE_GMTIME_R */
216 #ifndef HAVE_LOCALTIME_R
217 privoxy_mutex_t localtime_mutex;
218 #endif /* ndef HAVE_GMTIME_R */
220 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
221 privoxy_mutex_t rand_mutex;
222 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
224 #endif /* def MUTEX_LOCKS_AVAILABLE */
227 const char *basedir = NULL;
228 const char *pidfile = NULL;
229 static int received_hup_signal = 0;
230 #endif /* defined unix */
232 /* HTTP snipplets. */
233 static const char CSUCCEED[] =
234 "HTTP/1.1 200 Connection established\r\n\r\n";
236 static const char CHEADER[] =
237 "HTTP/1.1 400 Invalid header received from client\r\n"
238 "Content-Type: text/plain\r\n"
239 "Connection: close\r\n\r\n"
240 "Invalid header received from client.\r\n";
242 static const char FTP_RESPONSE[] =
243 "HTTP/1.1 400 Invalid request received from client\r\n"
244 "Content-Type: text/plain\r\n"
245 "Connection: close\r\n\r\n"
246 "Invalid request. Privoxy doesn't support FTP.\r\n";
248 static const char GOPHER_RESPONSE[] =
249 "HTTP/1.1 400 Invalid request received from client\r\n"
250 "Content-Type: text/plain\r\n"
251 "Connection: close\r\n\r\n"
252 "Invalid request. Privoxy doesn't support gopher.\r\n";
254 /* XXX: should be a template */
255 static const char MISSING_DESTINATION_RESPONSE[] =
256 "HTTP/1.1 400 Bad request received from client\r\n"
257 "Content-Type: text/plain\r\n"
258 "Connection: close\r\n\r\n"
259 "Bad request. Privoxy was unable to extract the destination.\r\n";
261 /* XXX: should be a template */
262 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
263 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
264 "Content-Type: text/plain\r\n"
265 "Connection: close\r\n\r\n"
266 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
268 /* XXX: should be a template */
269 static const char MESSED_UP_REQUEST_RESPONSE[] =
270 "HTTP/1.1 400 Malformed request after rewriting\r\n"
271 "Content-Type: text/plain\r\n"
272 "Connection: close\r\n\r\n"
273 "Bad request. Messed up with header filters.\r\n";
275 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
276 "HTTP/1.1 503 Too many open connections\r\n"
277 "Content-Type: text/plain\r\n"
278 "Connection: close\r\n\r\n"
279 "Maximum number of open connections reached.\r\n";
281 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
282 "HTTP/1.1 504 Connection timeout\r\n"
283 "Content-Type: text/plain\r\n"
284 "Connection: close\r\n\r\n"
285 "The connection timed out because the client request didn't arrive in time.\r\n";
287 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
288 "HTTP/1.1 400 Failed reading client body\r\n"
289 "Content-Type: text/plain\r\n"
290 "Connection: close\r\n\r\n"
291 "Failed parsing or buffering the chunk-encoded client body.\r\n";
293 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
294 "HTTP/1.1 417 Expecting too much\r\n"
295 "Content-Type: text/plain\r\n"
296 "Connection: close\r\n\r\n"
297 "Privoxy detected an unsupported Expect header value.\r\n";
299 /* A function to crunch a response */
300 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
302 /* Crunch function flags */
303 #define CF_NO_FLAGS 0
304 /* Cruncher applies to forced requests as well */
305 #define CF_IGNORE_FORCE 1
306 /* Crunched requests are counted for the block statistics */
307 #define CF_COUNT_AS_REJECT 2
309 /* A crunch function and its flags */
312 const crunch_func_ptr cruncher;
316 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
318 /* Complete list of cruncher functions */
319 static const struct cruncher crunchers_all[] = {
320 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
321 { block_url, CF_COUNT_AS_REJECT },
323 { trust_url, CF_COUNT_AS_REJECT },
324 #endif /* def FEATURE_TRUST */
325 { redirect_url, CF_NO_FLAGS },
326 { dispatch_cgi, CF_IGNORE_FORCE},
330 /* Light version, used after tags are applied */
331 static const struct cruncher crunchers_light[] = {
332 { block_url, CF_COUNT_AS_REJECT },
333 { redirect_url, CF_NO_FLAGS },
339 * XXX: Don't we really mean
345 #if !defined(_WIN32) && !defined(__OS2__)
346 /*********************************************************************
348 * Function : sig_handler
350 * Description : Signal handler for different signals.
351 * Exit gracefully on TERM and INT
352 * or set a flag that will cause the errlog
353 * to be reopened by the main thread on HUP.
356 * 1 : the_signal = the signal cause this function to call
360 *********************************************************************/
361 static void sig_handler(int the_signal)
367 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
379 received_hup_signal = 1;
385 * We shouldn't be here, unless we catch signals
386 * in main() that we can't handle here!
388 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
396 /*********************************************************************
398 * Function : get_write_delay
400 * Description : Parse the delay-response parameter.
403 * 1 : csp = Current client state (buffers, headers, etc...)
405 * Returns : Number of milliseconds to delay writes.
407 *********************************************************************/
408 static unsigned int get_write_delay(const struct client_state *csp)
414 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
418 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
420 delay = (unsigned)strtol(newval, &endptr, 0);
423 log_error(LOG_LEVEL_FATAL,
424 "Invalid delay-response{} parameter: '%s'", newval);
432 /*********************************************************************
434 * Function : client_protocol_is_unsupported
436 * Description : Checks if the client used a known unsupported
437 * protocol and deals with it by sending an error
441 * 1 : csp = Current client state (buffers, headers, etc...)
442 * 2 : req = the first request line send by the client
444 * Returns : TRUE if an error response has been generated, or
445 * FALSE if the request doesn't look invalid.
447 *********************************************************************/
448 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
451 * If it's a FTP or gopher request, we don't support it.
453 * These checks are better than nothing, but they might
454 * not work in all configurations and some clients might
455 * have problems digesting the answer.
457 * They should, however, never cause more problems than
458 * Privoxy's old behaviour (returning the misleading HTML
461 * "Could not resolve http://(ftp|gopher)://example.org").
463 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
465 const char *response = NULL;
466 const char *protocol = NULL;
468 if (!strncmpic(req, "GET ftp://", 10))
470 response = FTP_RESPONSE;
475 response = GOPHER_RESPONSE;
478 log_error(LOG_LEVEL_ERROR,
479 "%s tried to use Privoxy as %s proxy: %s",
480 csp->ip_addr_str, protocol, req);
481 log_error(LOG_LEVEL_CLF,
482 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
485 #ifdef FEATURE_HTTPS_INSPECTION
486 if (client_use_ssl(csp))
488 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
489 (const unsigned char *)response, strlen(response));
494 write_socket_delayed(csp->cfd, response, strlen(response),
495 get_write_delay(csp));
505 /*********************************************************************
507 * Function : client_has_unsupported_expectations
509 * Description : Checks if the client used an unsupported expectation
510 * in which case an error message is delivered.
513 * 1 : csp = Current client state (buffers, headers, etc...)
515 * Returns : TRUE if an error response has been generated, or
516 * FALSE if the request doesn't look invalid.
518 *********************************************************************/
519 static int client_has_unsupported_expectations(const struct client_state *csp)
521 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
523 log_error(LOG_LEVEL_ERROR,
524 "Rejecting request from client %s with unsupported Expect header value",
526 log_error(LOG_LEVEL_CLF,
527 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
528 write_socket_delayed(csp->cfd,
529 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
530 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
531 get_write_delay(csp));
541 /*********************************************************************
543 * Function : get_request_destination_elsewhere
545 * Description : If the client's request was redirected into
546 * Privoxy without the client's knowledge,
547 * the request line lacks the destination host.
549 * This function tries to get it elsewhere,
550 * provided accept-intercepted-requests is enabled.
552 * "Elsewhere" currently only means "Host: header",
553 * but in the future we may ask the redirecting
554 * packet filter to look the destination up.
556 * If the destination stays unknown, an error
557 * response is send to the client and headers
558 * are freed so that chat() can return directly.
561 * 1 : csp = Current client state (buffers, headers, etc...)
562 * 2 : headers = a header list
564 * Returns : JB_ERR_OK if the destination is now known, or
565 * JB_ERR_PARSE if it isn't.
567 *********************************************************************/
568 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
572 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
574 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
575 " Privoxy isn't configured to accept intercepted requests.",
576 csp->ip_addr_str, csp->http->cmd);
577 /* XXX: Use correct size */
578 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
579 csp->ip_addr_str, csp->http->cmd);
581 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
582 get_write_delay(csp));
583 destroy_list(headers);
587 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
589 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
590 /* Split the domain we just got for pattern matching */
591 init_domain_components(csp->http);
598 /* We can't work without destination. Go spread the news.*/
600 req = list_to_text(headers);
602 /* XXX: Use correct size */
603 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
604 csp->ip_addr_str, csp->http->cmd);
605 log_error(LOG_LEVEL_ERROR,
606 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
607 csp->ip_addr_str, csp->http->cmd, req);
610 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
611 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
612 destroy_list(headers);
617 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
618 * to get the destination IP address, use it as host directly
619 * or do a reverse DNS lookup first.
624 /*********************************************************************
626 * Function : get_server_headers
628 * Description : Parses server headers in iob and fills them
629 * into csp->headers so that they can later be
633 * 1 : csp = Current client state (buffers, headers, etc...)
635 * Returns : JB_ERR_OK if everything went fine, or
636 * JB_ERR_PARSE if the headers were incomplete.
638 *********************************************************************/
639 static jb_err get_server_headers(struct client_state *csp)
641 int continue_hack_in_da_house = 0;
644 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
649 * continue hack in da house. Ignore the ending of
650 * this head and continue enlisting header lines.
651 * The reason is described below.
653 enlist(csp->headers, "");
654 continue_hack_in_da_house = 0;
657 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
660 * It's a bodyless continue response, don't
661 * stop header parsing after reaching its end.
663 * As a result Privoxy will concatenate the
664 * next response's head and parse and deliver
665 * the headers as if they belonged to one request.
667 * The client will separate them because of the
668 * empty line between them.
670 * XXX: What we're doing here is clearly against
671 * the intended purpose of the continue header,
672 * and under some conditions (HTTP/1.0 client request)
673 * it's a standard violation.
675 * Anyway, "sort of against the spec" is preferable
676 * to "always getting confused by Continue responses"
677 * (Privoxy's behaviour before this hack was added)
679 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
680 continue_hack_in_da_house = 1;
682 else if (*header == '\0')
685 * If the header is empty, but the Continue hack
686 * isn't active, we can assume that we reached the
687 * end of the buffer before we hit the end of the
690 * Inform the caller an let it decide how to handle it.
695 if (JB_ERR_MEMORY == enlist(csp->headers, header))
698 * XXX: Should we quit the request and return a
699 * out of memory error page instead?
701 log_error(LOG_LEVEL_ERROR,
702 "Out of memory while enlisting server headers. %s lost.",
712 /*********************************************************************
714 * Function : crunch_reason
716 * Description : Translates the crunch reason code into a string.
719 * 1 : rsp = a http_response
721 * Returns : A string with the crunch reason or an error description.
723 *********************************************************************/
724 static const char *crunch_reason(const struct http_response *rsp)
726 char * reason = NULL;
731 return "Internal error while searching for crunch reason";
734 switch (rsp->crunch_reason)
737 reason = "Unsupported HTTP feature";
743 reason = "Untrusted";
746 reason = "Redirected";
752 reason = "DNS failure";
754 case FORWARDING_FAILED:
755 reason = "Forwarding failed";
758 reason = "Connection failure";
761 reason = "Out of memory (may mask other reasons)";
763 case CONNECTION_TIMEOUT:
764 reason = "Connection timeout";
767 reason = "No server data received";
770 reason = "No reason recorded";
778 /*********************************************************************
780 * Function : log_applied_actions
782 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
786 * 1 : actions = Current action spec to log
790 *********************************************************************/
791 static void log_applied_actions(const struct current_action_spec *actions)
794 * The conversion to text requires lots of memory allocations so
795 * we only do the conversion if the user is actually interested.
797 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
799 char *actions_as_text = actions_to_line_of_text(actions);
800 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
801 freez(actions_as_text);
806 /*********************************************************************
808 * Function : send_crunch_response
810 * Description : Delivers already prepared response for
811 * intercepted requests, logs the interception
812 * and frees the response.
815 * 1 : csp = Current client state (buffers, headers, etc...)
816 * 2 : rsp = Fully prepared response. Will be freed on exit.
820 *********************************************************************/
821 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
823 const struct http_request *http = csp->http;
827 assert(rsp->head != NULL);
831 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
835 * Extract the status code from the actual head
836 * that will be send to the client. It is the only
837 * way to get it right for all requests, including
838 * the fixed ones for out-of-memory problems.
840 * A head starts like this: 'HTTP/1.1 200...'
844 status_code[0] = rsp->head[9];
845 status_code[1] = rsp->head[10];
846 status_code[2] = rsp->head[11];
847 status_code[3] = '\0';
849 /* Log that the request was crunched and why. */
850 log_applied_actions(csp->action);
851 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
852 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
853 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
855 /* Write the answer to the client */
856 #ifdef FEATURE_HTTPS_INSPECTION
857 if (client_use_ssl(csp))
859 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
860 (const unsigned char *)rsp->head, rsp->head_length) < 0)
861 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
862 (const unsigned char *)rsp->body, rsp->content_length) < 0))
864 /* There is nothing we can do about it. */
865 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
866 "for %s through client socket %d using TLS/SSL",
867 http->url, csp->cfd);
873 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
874 get_write_delay(csp))
875 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
876 get_write_delay(csp)))
878 /* There is nothing we can do about it. */
879 log_error(LOG_LEVEL_CONNECT,
880 "Couldn't deliver the error message for %s through client socket %d: %E",
881 http->url, csp->cfd);
885 /* Clean up and return */
886 if (cgi_error_memory() != rsp)
888 free_http_response(rsp);
894 /*********************************************************************
896 * Function : crunch_response_triggered
898 * Description : Checks if the request has to be crunched,
899 * and delivers the crunch response if necessary.
902 * 1 : csp = Current client state (buffers, headers, etc...)
903 * 2 : crunchers = list of cruncher functions to run
905 * Returns : TRUE if the request was answered with a crunch response
908 *********************************************************************/
909 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
911 struct http_response *rsp = NULL;
912 const struct cruncher *c;
915 * If CGI request crunching is disabled,
916 * check the CGI dispatcher out of order to
917 * prevent unintentional blocks or redirects.
919 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
920 && (NULL != (rsp = dispatch_cgi(csp))))
922 /* Deliver, log and free the interception response. */
923 send_crunch_response(csp, rsp);
924 csp->flags |= CSP_FLAG_CRUNCHED;
928 for (c = crunchers; c->cruncher != NULL; c++)
931 * Check the cruncher if either Privoxy is toggled
932 * on and the request isn't forced, or if the cruncher
933 * applies to forced requests as well.
935 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
936 !(csp->flags & CSP_FLAG_FORCED)) ||
937 (c->flags & CF_IGNORE_FORCE))
939 rsp = c->cruncher(csp);
942 /* Deliver, log and free the interception response. */
943 send_crunch_response(csp, rsp);
944 csp->flags |= CSP_FLAG_CRUNCHED;
945 #ifdef FEATURE_STATISTICS
946 if (c->flags & CF_COUNT_AS_REJECT)
948 csp->flags |= CSP_FLAG_REJECTED;
950 #endif /* def FEATURE_STATISTICS */
961 /*********************************************************************
963 * Function : build_request_line
965 * Description : Builds the HTTP request line.
967 * If a HTTP forwarder is used it expects the whole URL,
968 * web servers only get the path.
971 * 1 : csp = Current client state (buffers, headers, etc...)
972 * 2 : fwd = The forwarding spec used for the request
973 * XXX: Should use http->fwd instead.
974 * 3 : request_line = The old request line which will be replaced.
976 * Returns : Nothing. Terminates in case of memory problems.
978 *********************************************************************/
979 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
981 struct http_request *http = csp->http;
984 * Downgrade http version from 1.1 to 1.0
985 * if +downgrade action applies.
987 if ((csp->action->flags & ACTION_DOWNGRADE)
988 && (!strcmpic(http->ver, "HTTP/1.1")))
991 http->ver = strdup_or_die("HTTP/1.0");
995 * Rebuild the request line.
997 freez(*request_line);
998 *request_line = strdup(http->gpc);
999 string_append(request_line, " ");
1001 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1003 string_append(request_line, http->url);
1007 string_append(request_line, http->path);
1009 string_append(request_line, " ");
1010 string_append(request_line, http->ver);
1012 if (*request_line == NULL)
1014 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1016 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1020 /*********************************************************************
1022 * Function : change_request_destination
1024 * Description : Parse a (rewritten) request line and regenerate
1025 * the http request data.
1028 * 1 : csp = Current client state (buffers, headers, etc...)
1030 * Returns : Forwards the parse_http_request() return code.
1031 * Terminates in case of memory problems.
1033 *********************************************************************/
1034 static jb_err change_request_destination(struct client_state *csp)
1036 struct http_request *http = csp->http;
1039 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1040 csp->headers->first->str);
1041 free_http_request(http);
1042 err = parse_http_request(csp->headers->first->str, http);
1043 if (JB_ERR_OK != err)
1045 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1046 jb_err_to_string(err));
1053 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1054 /*********************************************************************
1056 * Function : server_response_is_complete
1058 * Description : Determines whether we should stop reading
1059 * from the server socket.
1062 * 1 : csp = Current client state (buffers, headers, etc...)
1063 * 2 : content_length = Length of content received so far.
1065 * Returns : TRUE if the response is complete,
1068 *********************************************************************/
1069 static int server_response_is_complete(struct client_state *csp,
1070 unsigned long long content_length)
1072 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1074 if (!strcmpic(csp->http->gpc, "HEAD"))
1077 * "HEAD" implies no body, we are thus expecting
1078 * no content. XXX: incomplete "list" of methods?
1080 csp->expected_content_length = 0;
1081 content_length_known = TRUE;
1082 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1085 if (csp->http->status == 204 || csp->http->status == 304)
1088 * Expect no body. XXX: incomplete "list" of status codes?
1090 csp->expected_content_length = 0;
1091 content_length_known = TRUE;
1092 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1095 return (content_length_known && ((0 == csp->expected_content_length)
1096 || (csp->expected_content_length <= content_length)));
1100 #ifdef FEATURE_CONNECTION_SHARING
1101 /*********************************************************************
1103 * Function : wait_for_alive_connections
1105 * Description : Waits for alive connections to timeout.
1111 *********************************************************************/
1112 static void wait_for_alive_connections(void)
1114 int connections_alive = close_unusable_connections();
1116 while (0 < connections_alive)
1118 log_error(LOG_LEVEL_CONNECT,
1119 "Waiting for %d connections to timeout.",
1122 connections_alive = close_unusable_connections();
1125 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1128 #endif /* def FEATURE_CONNECTION_SHARING */
1131 /*********************************************************************
1133 * Function : save_connection_destination
1135 * Description : Remembers a connection for reuse later on.
1138 * 1 : sfd = Open socket to remember.
1139 * 2 : http = The destination for the connection.
1140 * 3 : fwd = The forwarder settings used.
1141 * 4 : server_connection = storage.
1145 *********************************************************************/
1146 void save_connection_destination(jb_socket sfd,
1147 const struct http_request *http,
1148 const struct forward_spec *fwd,
1149 struct reusable_connection *server_connection)
1151 assert(sfd != JB_INVALID_SOCKET);
1152 assert(NULL != http->host);
1154 server_connection->sfd = sfd;
1155 server_connection->host = strdup_or_die(http->host);
1156 server_connection->port = http->port;
1158 assert(NULL != fwd);
1159 assert(server_connection->gateway_host == NULL);
1160 assert(server_connection->gateway_port == 0);
1161 assert(server_connection->forwarder_type == 0);
1162 assert(server_connection->forward_host == NULL);
1163 assert(server_connection->forward_port == 0);
1165 server_connection->forwarder_type = fwd->type;
1166 if (NULL != fwd->gateway_host)
1168 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1172 server_connection->gateway_host = NULL;
1174 server_connection->gateway_port = fwd->gateway_port;
1176 if (NULL != fwd->forward_host)
1178 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1182 server_connection->forward_host = NULL;
1184 server_connection->forward_port = fwd->forward_port;
1188 /*********************************************************************
1190 * Function : verify_request_length
1192 * Description : Checks if we already got the whole client requests
1193 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1196 * Data that doesn't belong to the current request is
1197 * either thrown away to let the client retry on a clean
1198 * socket, or stashed to be dealt with after the current
1199 * request is served.
1202 * 1 : csp = Current client state (buffers, headers, etc...)
1206 *********************************************************************/
1207 static void verify_request_length(struct client_state *csp)
1209 unsigned long long buffered_request_bytes =
1210 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1212 if ((csp->expected_client_content_length != 0)
1213 && (buffered_request_bytes != 0))
1215 if (csp->expected_client_content_length >= buffered_request_bytes)
1217 csp->expected_client_content_length -= buffered_request_bytes;
1218 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1219 "to account for the %llu ones we already got.",
1220 csp->expected_client_content_length, buffered_request_bytes);
1224 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1225 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1226 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1227 "Marking the server socket tainted after throwing %llu bytes away.",
1228 buffered_request_bytes - csp->expected_client_content_length);
1229 csp->expected_client_content_length = 0;
1230 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1233 if (csp->expected_client_content_length == 0)
1235 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1239 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1240 && ((csp->client_iob->cur < csp->client_iob->eod)
1241 || (csp->expected_client_content_length != 0)))
1243 if (strcmpic(csp->http->gpc, "GET")
1244 && strcmpic(csp->http->gpc, "HEAD")
1245 && strcmpic(csp->http->gpc, "TRACE")
1246 && strcmpic(csp->http->gpc, "OPTIONS")
1247 && strcmpic(csp->http->gpc, "DELETE"))
1249 /* XXX: this is an incomplete hack */
1250 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1251 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1255 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1257 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1259 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1260 log_error(LOG_LEVEL_CONNECT,
1261 "Possible pipeline attempt detected. The connection will not "
1262 "be kept alive and we will only serve the first request.");
1263 /* Nuke the pipelined requests from orbit, just to be sure. */
1264 clear_iob(csp->client_iob);
1269 * Keep the pipelined data around for now, we'll deal with
1270 * it once we're done serving the current request.
1272 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1273 assert(csp->client_iob->eod >= csp->client_iob->cur);
1274 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1275 "%d bytes of pipelined data received.",
1276 (int)(csp->client_iob->eod - csp->client_iob->cur));
1282 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1283 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1286 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1289 /*********************************************************************
1291 * Function : mark_server_socket_tainted
1293 * Description : Makes sure we don't reuse a server socket
1294 * (if we didn't read everything the server sent
1295 * us reusing the socket would lead to garbage).
1298 * 1 : csp = Current client state (buffers, headers, etc...)
1302 *********************************************************************/
1303 static void mark_server_socket_tainted(struct client_state *csp)
1306 * For consistency we always mark the server socket
1307 * tainted, however, to reduce the log noise we only
1308 * emit a log message if the server socket could have
1309 * actually been reused.
1311 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1312 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1314 log_error(LOG_LEVEL_CONNECT,
1315 "Marking the server socket %d tainted.",
1316 csp->server_connection.sfd);
1318 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1321 /*********************************************************************
1323 * Function : get_request_line
1325 * Description : Read the client request line.
1328 * 1 : csp = Current client state (buffers, headers, etc...)
1330 * Returns : Pointer to request line or NULL in case of errors.
1332 *********************************************************************/
1333 static char *get_request_line(struct client_state *csp)
1335 char buf[BUFFER_SIZE];
1336 char *request_line = NULL;
1339 memset(buf, 0, sizeof(buf));
1341 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1344 * If there are multiple pipelined requests waiting,
1345 * the flag will be set again once the next request
1348 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1350 request_line = get_header(csp->client_iob);
1351 if ((NULL != request_line) && ('\0' != *request_line))
1353 return request_line;
1357 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1358 "received yet. Continuing reading from %d.", csp->cfd);
1366 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1368 !data_is_available(csp->cfd, csp->config->socket_timeout)
1371 if (socket_is_still_alive(csp->cfd))
1373 log_error(LOG_LEVEL_CONNECT,
1374 "No request line on socket %d received in time. Timeout: %d.",
1375 csp->cfd, csp->config->socket_timeout);
1376 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1377 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1378 get_write_delay(csp));
1382 log_error(LOG_LEVEL_CONNECT,
1383 "The client side of the connection on socket %d got "
1384 "closed without sending a complete request line.", csp->cfd);
1389 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1391 if (len <= 0) return NULL;
1394 * If there is no memory left for buffering the
1395 * request, there is nothing we can do but hang up
1397 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1402 request_line = get_header(csp->client_iob);
1404 } while ((NULL != request_line) && ('\0' == *request_line));
1406 return request_line;
1412 CHUNK_STATUS_MISSING_DATA,
1413 CHUNK_STATUS_BODY_COMPLETE,
1414 CHUNK_STATUS_PARSE_ERROR
1418 /*********************************************************************
1420 * Function : chunked_body_is_complete
1422 * Description : Figures out whether or not a chunked body is complete.
1424 * Currently it always starts at the beginning of the
1425 * buffer which is somewhat wasteful and prevents Privoxy
1426 * from starting to forward the correctly parsed chunks
1427 * as soon as theoretically possible.
1429 * Should be modified to work with a common buffer,
1430 * and allow the caller to skip already parsed chunks.
1432 * This would allow the function to be used for unbuffered
1433 * response bodies as well.
1436 * 1 : iob = Buffer with the body to check.
1437 * 2 : length = Length of complete body
1439 * Returns : Enum with the result of the check.
1441 *********************************************************************/
1442 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1444 unsigned int chunksize;
1450 * We need at least a single digit, followed by "\r\n",
1451 * followed by an unknown amount of data, followed by "\r\n".
1453 if (p + 5 > iob->eod)
1455 return CHUNK_STATUS_MISSING_DATA;
1457 if (sscanf(p, "%x", &chunksize) != 1)
1459 return CHUNK_STATUS_PARSE_ERROR;
1463 * We want at least a single digit, followed by "\r\n",
1464 * followed by the specified amount of data, followed by "\r\n".
1466 if (p + chunksize + 5 > iob->eod)
1468 return CHUNK_STATUS_MISSING_DATA;
1471 /* Skip chunk-size. */
1472 p = strstr(p, "\r\n");
1475 return CHUNK_STATUS_PARSE_ERROR;
1477 /* Move beyond the chunkdata. */
1480 /* There should be another "\r\n" to skip */
1481 if (memcmp(p, "\r\n", 2))
1483 return CHUNK_STATUS_PARSE_ERROR;
1486 } while (chunksize > 0U);
1488 *length = (size_t)(p - iob->cur);
1489 assert(*length <= (size_t)(iob->eod - iob->cur));
1490 assert(p <= iob->eod);
1492 return CHUNK_STATUS_BODY_COMPLETE;
1497 /*********************************************************************
1499 * Function : receive_chunked_client_request_body
1501 * Description : Read the chunk-encoded client request body.
1502 * Failures are dealt with.
1505 * 1 : csp = Current client state (buffers, headers, etc...)
1507 * Returns : JB_ERR_OK or JB_ERR_PARSE
1509 *********************************************************************/
1510 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1513 enum chunk_status status;
1515 while (CHUNK_STATUS_MISSING_DATA ==
1516 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1518 char buf[BUFFER_SIZE];
1521 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1523 log_error(LOG_LEVEL_ERROR,
1524 "Timeout while waiting for the client body.");
1527 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1530 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1533 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1538 if (status != CHUNK_STATUS_BODY_COMPLETE)
1540 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1541 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1542 log_error(LOG_LEVEL_CLF,
1543 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1544 return JB_ERR_PARSE;
1546 log_error(LOG_LEVEL_CONNECT,
1547 "Chunked client body completely read. Length: %d", body_length);
1548 csp->expected_client_content_length = body_length;
1556 /*********************************************************************
1558 * Function : fuzz_chunked_transfer_encoding
1560 * Description : Treat the fuzzed input as chunked transfer encoding
1561 * to check and dechunk.
1564 * 1 : csp = Used to store the data.
1565 * 2 : fuzz_input_file = File to read the input from.
1567 * Returns : Result of dechunking
1569 *********************************************************************/
1570 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1573 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1574 enum chunk_status status;
1576 status = chunked_body_is_complete(csp->iob, &length);
1577 if (CHUNK_STATUS_BODY_COMPLETE != status)
1579 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1582 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1587 /*********************************************************************
1589 * Function : fuzz_client_request
1591 * Description : Try to get a client request from the fuzzed input.
1594 * 1 : csp = Current client state (buffers, headers, etc...)
1595 * 2 : fuzz_input_file = File to read the input from.
1597 * Returns : Result of fuzzing.
1599 *********************************************************************/
1600 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1605 csp->ip_addr_str = "fuzzer";
1607 if (strcmp(fuzz_input_file, "-") != 0)
1609 log_error(LOG_LEVEL_FATAL,
1610 "Fuzzed client requests can currenty only be read from stdin (-).");
1612 err = receive_client_request(csp);
1613 if (err != JB_ERR_OK)
1617 err = parse_client_request(csp);
1618 if (err != JB_ERR_OK)
1626 #endif /* def FUZZ */
1629 #ifdef FEATURE_FORCE_LOAD
1630 /*********************************************************************
1632 * Function : force_required
1634 * Description : Checks a request line to see if it contains
1635 * the FORCE_PREFIX. If it does, it is removed
1636 * unless enforcing requests has beend disabled.
1639 * 1 : request_line = HTTP request line
1641 * Returns : TRUE if force is required, FALSE otherwise.
1643 *********************************************************************/
1644 static int force_required(const struct client_state *csp, char *request_line)
1648 p = strstr(request_line, "http://");
1652 p += strlen("http://");
1656 /* Intercepted request usually don't specify the protocol. */
1660 /* Go to the beginning of the path */
1665 * If the path is missing the request line is invalid and we
1666 * are done here. The client-visible rejection happens later on.
1671 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1673 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1675 /* XXX: Should clean more carefully */
1676 strclean(request_line, FORCE_PREFIX);
1677 log_error(LOG_LEVEL_FORCE,
1678 "Enforcing request: \"%s\".", request_line);
1682 log_error(LOG_LEVEL_FORCE,
1683 "Ignored force prefix in request: \"%s\".", request_line);
1689 #endif /* def FEATURE_FORCE_LOAD */
1692 /*********************************************************************
1694 * Function : receive_client_request
1696 * Description : Read the client's request (more precisely the
1697 * client headers) and answer it if necessary.
1700 * 1 : csp = Current client state (buffers, headers, etc...)
1702 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1704 *********************************************************************/
1705 static jb_err receive_client_request(struct client_state *csp)
1707 char buf[BUFFER_SIZE];
1710 struct http_request *http;
1714 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1715 struct list header_list;
1716 struct list *headers = &header_list;
1718 /* We don't care if the arriving data is a valid HTTP request or not. */
1719 csp->requests_received_total++;
1723 memset(buf, 0, sizeof(buf));
1725 req = get_request_line(csp);
1728 mark_server_socket_tainted(csp);
1729 return JB_ERR_PARSE;
1731 assert(*req != '\0');
1733 if (client_protocol_is_unsupported(csp, req))
1735 return JB_ERR_PARSE;
1738 #ifdef FEATURE_FORCE_LOAD
1739 if (force_required(csp, req))
1741 csp->flags |= CSP_FLAG_FORCED;
1743 #endif /* def FEATURE_FORCE_LOAD */
1745 err = parse_http_request(req, http);
1747 if (JB_ERR_OK != err)
1749 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1750 get_write_delay(csp));
1751 /* XXX: Use correct size */
1752 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1753 log_error(LOG_LEVEL_ERROR,
1754 "Couldn't parse request line received from %s: %s",
1755 csp->ip_addr_str, jb_err_to_string(err));
1757 free_http_request(http);
1758 return JB_ERR_PARSE;
1761 /* grab the rest of the client's headers */
1765 p = get_header(csp->client_iob);
1769 /* There are no additional headers to read. */
1776 * We didn't receive a complete header
1777 * line yet, get the rest of it.
1779 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1781 log_error(LOG_LEVEL_ERROR,
1782 "Stopped grabbing the client headers.");
1783 destroy_list(headers);
1784 return JB_ERR_PARSE;
1787 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1790 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1791 destroy_list(headers);
1792 return JB_ERR_PARSE;
1795 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1798 * If there is no memory left for buffering the
1799 * request, there is nothing we can do but hang up
1801 destroy_list(headers);
1802 return JB_ERR_MEMORY;
1807 if (!strncmpic(p, "Transfer-Encoding:", 18))
1810 * XXX: should be called through sed()
1811 * but currently can't.
1813 client_transfer_encoding(csp, &p);
1816 * We were able to read a complete
1817 * header and can finally enlist it.
1824 if (http->host == NULL)
1827 * If we still don't know the request destination,
1828 * the request is invalid or the client uses
1829 * Privoxy without its knowledge.
1831 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1834 * Our attempts to get the request destination
1835 * elsewhere failed or Privoxy is configured
1836 * to only accept proxy requests.
1838 * An error response has already been send
1839 * and we're done here.
1841 return JB_ERR_PARSE;
1845 #ifdef FEATURE_CLIENT_TAGS
1846 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1847 set_client_address(csp, headers);
1848 get_tag_list_for_client(csp->client_tags, csp->client_address);
1852 * Determine the actions for this URL
1854 #ifdef FEATURE_TOGGLE
1855 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1857 /* Most compatible set of actions (i.e. none) */
1858 init_current_action(csp->action);
1861 #endif /* ndef FEATURE_TOGGLE */
1863 get_url_actions(csp, http);
1866 enlist(csp->headers, http->cmd);
1868 /* Append the previously read headers */
1869 err = list_append_list_unique(csp->headers, headers);
1870 destroy_list(headers);
1877 /*********************************************************************
1879 * Function : parse_client_request
1881 * Description : Parses the client's request and decides what to do
1884 * Note that since we're not using select() we could get
1885 * blocked here if a client connected, then didn't say
1889 * 1 : csp = Current client state (buffers, headers, etc...)
1891 * Returns : JB_ERR_OK or JB_ERR_PARSE
1893 *********************************************************************/
1894 static jb_err parse_client_request(struct client_state *csp)
1896 struct http_request *http = csp->http;
1899 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1900 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1901 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1902 && (csp->http->ssl == 0))
1904 /* Assume persistence until further notice */
1905 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1908 if (csp->http->ssl == 0)
1911 * This whole block belongs to chat() but currently
1912 * has to be executed before sed().
1914 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1916 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1918 return JB_ERR_PARSE;
1923 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1925 verify_request_length(csp);
1929 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1931 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1933 err = sed(csp, FILTER_CLIENT_HEADERS);
1934 if (JB_ERR_OK != err)
1936 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1938 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1939 csp->ip_addr_str, csp->http->cmd);
1940 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1941 return JB_ERR_PARSE;
1943 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1945 /* Check request line for rewrites. */
1946 if ((NULL == csp->headers->first->str)
1947 || (strcmp(http->cmd, csp->headers->first->str) &&
1948 (JB_ERR_OK != change_request_destination(csp))))
1951 * A header filter broke the request line - bail out.
1953 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1954 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1955 /* XXX: Use correct size */
1956 log_error(LOG_LEVEL_CLF,
1957 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1958 log_error(LOG_LEVEL_ERROR,
1959 "Invalid request line after applying header filters.");
1960 free_http_request(http);
1962 return JB_ERR_PARSE;
1965 if (client_has_unsupported_expectations(csp))
1967 return JB_ERR_PARSE;
1975 /*********************************************************************
1977 * Function : send_http_request
1979 * Description : Sends the HTTP headers from the client request
1980 * and all the body data that has already been received.
1983 * 1 : csp = Current client state (buffers, headers, etc...)
1985 * Returns : 0 on success, anything else is an error.
1987 *********************************************************************/
1988 static int send_http_request(struct client_state *csp)
1993 hdr = list_to_text(csp->headers);
1996 /* FIXME Should handle error properly */
1997 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1999 list_remove_all(csp->headers);
2002 * Write the client's (modified) header to the server
2003 * (along with anything else that may be in the buffer)
2005 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2010 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2011 csp->http->hostport);
2013 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2014 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2017 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2018 csp->http->hostport);
2021 return write_failure;
2026 #ifdef FEATURE_HTTPS_INSPECTION
2027 /*********************************************************************
2029 * Function : receive_and_send_encrypted_post_data
2031 * Description : Reads remaining POST data from the client and sends
2035 * 1 : csp = Current client state (buffers, headers, etc...)
2037 * Returns : 0 on success, anything else is an error.
2039 *********************************************************************/
2040 static jb_err receive_and_send_encrypted_post_data(struct client_state *csp)
2042 int content_length_known = csp->expected_client_content_length != 0;
2044 while (is_ssl_pending(&(csp->mbedtls_client_attr.ssl)))
2046 unsigned char buf[BUFFER_SIZE];
2048 int max_bytes_to_read = sizeof(buf);
2050 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2052 max_bytes_to_read = (int)csp->expected_client_content_length;
2054 log_error(LOG_LEVEL_CONNECT,
2055 "Waiting for up to %d bytes of POST data from the client.",
2057 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl), buf,
2058 (unsigned)max_bytes_to_read);
2065 /* XXX: Does this actually happen? */
2068 log_error(LOG_LEVEL_HEADER, "Forwarding %d bytes of encrypted POST data",
2070 len = ssl_send_data(&(csp->mbedtls_server_attr.ssl), buf, (size_t)len);
2075 if (csp->expected_client_content_length != 0)
2077 if (csp->expected_client_content_length >= len)
2079 csp->expected_client_content_length -= (unsigned)len;
2081 if (csp->expected_client_content_length == 0)
2083 log_error(LOG_LEVEL_HEADER, "Forwarded the last %d bytes", len);
2089 log_error(LOG_LEVEL_HEADER, "Done forwarding encrypted POST data");
2096 /*********************************************************************
2098 * Function : send_https_request
2100 * Description : Sends the HTTP headers from the client request
2101 * and all the body data that has already been received.
2104 * 1 : csp = Current client state (buffers, headers, etc...)
2106 * Returns : 0 on success, anything else is an error.
2108 *********************************************************************/
2109 static int send_https_request(struct client_state *csp)
2115 hdr = list_to_text(csp->https_headers);
2118 /* FIXME Should handle error properly */
2119 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2121 list_remove_all(csp->https_headers);
2124 * Write the client's (modified) header to the server
2125 * (along with anything else that may be in the buffer)
2127 ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2128 (const unsigned char *)hdr, strlen(hdr));
2133 log_error(LOG_LEVEL_CONNECT,
2134 "Failed sending encrypted request headers to: %s: %E",
2135 csp->http->hostport);
2136 mark_server_socket_tainted(csp);
2140 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2141 && ((flushed = ssl_flush_socket(&(csp->mbedtls_server_attr.ssl),
2142 csp->client_iob)) < 0))
2144 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2145 csp->http->hostport);
2150 if (csp->expected_client_content_length != 0)
2152 if (csp->expected_client_content_length < flushed)
2154 log_error(LOG_LEVEL_ERROR,
2155 "Flushed %d bytes of request body while only expecting %llu",
2156 flushed, csp->expected_client_content_length);
2157 csp->expected_client_content_length = 0;
2161 log_error(LOG_LEVEL_CONNECT,
2162 "Flushed %d bytes of request body while expecting %llu",
2163 flushed, csp->expected_client_content_length);
2164 csp->expected_client_content_length -= (unsigned)flushed;
2165 if (receive_and_send_encrypted_post_data(csp))
2173 log_error(LOG_LEVEL_CONNECT,
2174 "Flushed %d bytes of request body", flushed);
2178 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2185 /*********************************************************************
2187 * Function : receive_encrypted_request
2189 * Description : Receives an encrypted request.
2192 * 1 : csp = Current client state (buffers, headers, etc...)
2194 * Returns : JB_ERR_OK on success,
2195 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2197 *********************************************************************/
2198 static jb_err receive_encrypted_request(struct client_state *csp)
2200 char buf[BUFFER_SIZE];
2206 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2207 if (!data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout))
2209 log_error(LOG_LEVEL_CONNECT,
2210 "Socket %d timed out while waiting for client headers", csp->cfd);
2211 return JB_ERR_PARSE;
2213 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2214 (unsigned char *)buf, sizeof(buf));
2217 return JB_ERR_PARSE;
2219 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2221 return JB_ERR_MEMORY;
2223 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2224 } while (p == NULL);
2226 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2232 /*********************************************************************
2234 * Function : process_encrypted_request
2236 * Description : Receives and parses an encrypted request.
2239 * 1 : csp = Current client state (buffers, headers, etc...)
2241 * Returns : JB_ERR_OK on success,
2242 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2244 *********************************************************************/
2245 static jb_err process_encrypted_request(struct client_state *csp)
2250 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2251 struct list header_list;
2252 struct list *headers = &header_list;
2254 err = receive_encrypted_request(csp);
2255 if (err != JB_ERR_OK)
2257 /* XXX: Also used for JB_ERR_MEMORY */
2258 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2259 jb_err_to_string(err));
2260 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2261 (const unsigned char *)CHEADER, strlen(CHEADER));
2265 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2266 request_line = get_header(csp->client_iob);
2267 if (request_line == NULL)
2269 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2270 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2271 (const unsigned char *)CHEADER, strlen(CHEADER));
2272 return JB_ERR_PARSE;
2274 assert(*request_line != '\0');
2276 if (client_protocol_is_unsupported(csp, request_line))
2278 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2279 (const unsigned char *)CHEADER, strlen(CHEADER));
2280 return JB_ERR_PARSE;
2283 #ifdef FEATURE_FORCE_LOAD
2284 if (force_required(csp, request_line))
2286 csp->flags |= CSP_FLAG_FORCED;
2288 #endif /* def FEATURE_FORCE_LOAD */
2290 free_http_request(csp->http);
2292 err = parse_http_request(request_line, csp->http);
2293 /* XXX: Restore ssl setting. This is ugly */
2294 csp->http->client_ssl = 1;
2295 csp->http->server_ssl = 1;
2297 freez(request_line);
2298 if (JB_ERR_OK != err)
2300 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2301 (const unsigned char *)CHEADER, strlen(CHEADER));
2302 /* XXX: Use correct size */
2303 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2304 log_error(LOG_LEVEL_ERROR,
2305 "Couldn't parse request line received from %s: %s",
2306 csp->ip_addr_str, jb_err_to_string(err));
2308 free_http_request(csp->http);
2309 return JB_ERR_PARSE;
2312 /* Parse the rest of the client's headers. */
2316 p = get_header(csp->client_iob);
2320 /* There are no additional headers to read. */
2327 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2330 * Our attempts to get the request destination
2333 log_error(LOG_LEVEL_ERROR,
2334 "Failed to get the encrypted request destination");
2335 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2336 (const unsigned char *)CHEADER, strlen(CHEADER));
2337 return JB_ERR_PARSE;
2340 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
2341 /* Split the domain we just got for pattern matching */
2342 init_domain_components(csp->http);
2345 #ifdef FEATURE_TOGGLE
2346 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2349 /* Determine the actions for this URL */
2350 get_url_actions(csp, csp->http);
2353 enlist(csp->https_headers, csp->http->cmd);
2355 /* Append the previously read headers */
2356 err = list_append_list_unique(csp->https_headers, headers);
2357 destroy_list(headers);
2358 if (JB_ERR_OK != err)
2360 /* XXX: Send error message */
2364 /* XXX: Work around crash */
2365 csp->error_message = NULL;
2367 /* XXX: Why do this here? */
2370 err = sed_https(csp);
2371 if (JB_ERR_OK != err)
2373 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2374 (const unsigned char *)CHEADER, strlen(CHEADER));
2375 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2377 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2378 csp->ip_addr_str, csp->http->cmd);
2379 return JB_ERR_PARSE;
2382 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2383 log_applied_actions(csp->action);
2391 /*********************************************************************
2393 * Function : handle_established_connection
2395 * Description : Shuffle data between client and server once the
2396 * connection has been established.
2399 * 1 : csp = Current client state (buffers, headers, etc...)
2401 * Returns : Nothing.
2403 *********************************************************************/
2404 static void handle_established_connection(struct client_state *csp)
2410 struct pollfd poll_fds[2];
2414 struct timeval timeout;
2417 int ms_iis5_hack = 0;
2418 unsigned long long byte_count = 0;
2419 struct http_request *http;
2420 long len = 0; /* for buffer sizes (and negative error codes) */
2421 int buffer_and_filter_content = 0;
2422 unsigned int write_delay;
2423 #ifdef FEATURE_HTTPS_INSPECTION
2425 int use_ssl_tunnel = 0;
2426 csp->dont_verify_certificate = 0;
2428 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2430 /* Pass encrypted content without filtering. */
2435 /* Skeleton for HTTP response, if we should intercept the request */
2436 struct http_response *rsp;
2437 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2438 int watch_client_socket;
2441 csp->receive_buffer_size = csp->config->receive_buffer_size;
2442 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2443 if (csp->receive_buffer == NULL)
2445 log_error(LOG_LEVEL_ERROR,
2446 "Out of memory. Failed to allocate the receive buffer.");
2447 rsp = cgi_error_memory();
2448 send_crunch_response(csp, rsp);
2455 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2456 csp->cfd : csp->server_connection.sfd;
2459 /* pass data between the client and server
2460 * until one or the other shuts down the connection.
2465 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2466 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2468 write_delay = get_write_delay(csp);
2475 * FD_ZERO here seems to point to an errant macro which crashes.
2476 * So do this by hand for now...
2478 memset(&rfds,0x00,sizeof(fd_set));
2482 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2483 if (!watch_client_socket)
2485 maxfd = csp->server_connection.sfd;
2488 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2490 FD_SET(csp->cfd, &rfds);
2493 FD_SET(csp->server_connection.sfd, &rfds);
2494 #endif /* ndef HAVE_POLL */
2496 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2497 if ((csp->flags & CSP_FLAG_CHUNKED)
2498 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2499 && ((csp->iob->eod - csp->iob->cur) >= 5)
2500 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2503 * XXX: This check should be obsolete now,
2504 * but let's wait a while to be sure.
2506 log_error(LOG_LEVEL_CONNECT,
2507 "Looks like we got the last chunk together with "
2508 "the server headers but didn't detect it earlier. "
2509 "We better stop reading.");
2510 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2511 csp->expected_content_length = byte_count;
2512 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2514 if (server_body && server_response_is_complete(csp, byte_count))
2516 if (csp->expected_content_length == byte_count)
2518 log_error(LOG_LEVEL_CONNECT,
2519 "Done reading from server. Content length: %llu as expected. "
2520 "Bytes most recently read: %d.",
2525 log_error(LOG_LEVEL_CONNECT,
2526 "Done reading from server. Expected content length: %llu. "
2527 "Actual content length: %llu. Bytes most recently read: %d.",
2528 csp->expected_content_length, byte_count, len);
2532 * XXX: Should not jump around, handle_established_connection()
2533 * is complicated enough already.
2537 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
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);
2596 * This is the body of the browser's request,
2597 * just read and write it.
2599 * Receives data from browser and sends it to server
2601 * XXX: Make sure the client doesn't use pipelining
2602 * behind Privoxy's back.
2605 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2607 log_error(LOG_LEVEL_CONNECT,
2608 "The client socket %d has become unusable while "
2609 "the server socket %d is still open.",
2610 csp->cfd, csp->server_connection.sfd);
2611 mark_server_socket_tainted(csp);
2615 if (poll_fds[0].revents != 0)
2617 if (FD_ISSET(csp->cfd, &rfds))
2618 #endif /* def HAVE_POLL*/
2620 int max_bytes_to_read = (int)csp->receive_buffer_size;
2622 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2623 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2625 if (data_is_available(csp->cfd, 0))
2628 * If the next request is already waiting, we have
2629 * to stop select()ing the client socket. Otherwise
2630 * we would always return right away and get nothing
2633 watch_client_socket = 0;
2634 log_error(LOG_LEVEL_CONNECT,
2635 "Stop watching client socket %d. "
2636 "There's already another request waiting.",
2641 * If the client socket is set, but there's no data
2642 * available on the socket, the client went fishing
2643 * and continuing talking to the server makes no sense.
2645 log_error(LOG_LEVEL_CONNECT,
2646 "The client closed socket %d while "
2647 "the server socket %d is still open.",
2648 csp->cfd, csp->server_connection.sfd);
2649 mark_server_socket_tainted(csp);
2652 if (csp->expected_client_content_length != 0)
2654 if (csp->expected_client_content_length < csp->receive_buffer_size)
2656 max_bytes_to_read = (int)csp->expected_client_content_length;
2658 log_error(LOG_LEVEL_CONNECT,
2659 "Waiting for up to %d bytes from the client.",
2662 assert(max_bytes_to_read <= csp->receive_buffer_size);
2663 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2665 #ifdef FEATURE_HTTPS_INSPECTION
2667 * Reading data from standard or secured connection (HTTP/HTTPS)
2669 if (client_use_ssl(csp))
2672 * Receiving HTTP request from client over TLS/SSL and sending
2673 * it to server over TLS/SSL.
2675 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2676 (unsigned char *)csp->receive_buffer, (size_t)max_bytes_to_read);
2680 mark_server_socket_tainted(csp);
2684 ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2685 (const unsigned char *)csp->receive_buffer, (size_t)len);
2689 log_error(LOG_LEVEL_ERROR,
2690 "Send request over TLS/SSL to: %s failed", http->host);
2691 mark_server_socket_tainted(csp);
2692 close_client_and_server_ssl_connections(csp);
2697 #endif /* def FEATURE_HTTPS_INSPECTION */
2699 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2703 /* XXX: not sure if this is necessary. */
2704 mark_server_socket_tainted(csp);
2705 break; /* "game over, man" */
2708 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2709 if (csp->expected_client_content_length != 0)
2711 assert(len <= max_bytes_to_read);
2712 csp->expected_client_content_length -= (unsigned)len;
2713 log_error(LOG_LEVEL_CONNECT,
2714 "Expected client content length set to %llu "
2715 "after reading %d bytes.",
2716 csp->expected_client_content_length, len);
2717 if (csp->expected_client_content_length == 0)
2719 log_error(LOG_LEVEL_CONNECT,
2720 "Done reading from the client.");
2721 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2724 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2726 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2728 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2729 mark_server_socket_tainted(csp);
2737 * The server wants to talk. It could be the header or the body.
2738 * If `hdr' is null, then it's the header otherwise it's the body.
2739 * FIXME: Does `hdr' really mean `host'? No.
2742 if (poll_fds[1].revents != 0)
2744 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2745 #endif /* HAVE_POLL */
2747 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2749 * If we are buffering content, we don't want to eat up to
2750 * buffer-limit bytes if the client no longer cares about them.
2751 * If we aren't buffering, however, a dead client socket will be
2752 * noticed pretty much right away anyway, so we can reduce the
2753 * overhead by skipping the check.
2755 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2758 log_error(LOG_LEVEL_CONNECT,
2759 "The server still wants to talk, but the client may already have hung up on us.");
2761 log_error(LOG_LEVEL_CONNECT,
2762 "The server still wants to talk, but the client hung up on us.");
2763 mark_server_socket_tainted(csp);
2764 #ifdef FEATURE_HTTPS_INSPECTION
2765 close_client_and_server_ssl_connections(csp);
2768 #endif /* def _WIN32 */
2770 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2772 #ifdef FEATURE_HTTPS_INSPECTION
2774 * Reading data from standard or secured connection (HTTP/HTTPS)
2776 if (server_use_ssl(csp))
2778 len = ssl_recv_data(&(csp->mbedtls_server_attr.ssl),
2779 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2784 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2785 (int)csp->receive_buffer_size);
2790 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2792 if ((http->ssl && (csp->fwd == NULL))
2793 #ifdef FEATURE_HTTPS_INSPECTION
2799 * Just hang up. We already confirmed the client's CONNECT
2800 * request with status code 200 and unencrypted content is
2801 * no longer welcome.
2803 log_error(LOG_LEVEL_ERROR,
2804 "CONNECT already confirmed. Unable to tell the client about the problem.");
2807 else if (byte_count)
2810 * Just hang up. We already transmitted the original headers
2811 * and parts of the original content and therefore missed the
2812 * chance to send an error message (without risking data corruption).
2814 * XXX: we could retry with a fancy range request here.
2816 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2817 "Unable to tell the client about the problem.");
2818 mark_server_socket_tainted(csp);
2819 #ifdef FEATURE_HTTPS_INSPECTION
2820 close_client_and_server_ssl_connections(csp);
2825 * XXX: Consider handling the cases above the same.
2827 mark_server_socket_tainted(csp);
2831 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2832 if (csp->flags & CSP_FLAG_CHUNKED)
2834 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2836 /* XXX: this is a temporary hack */
2837 log_error(LOG_LEVEL_CONNECT,
2838 "Looks like we reached the end of the last chunk. "
2839 "We better stop reading.");
2840 csp->expected_content_length = byte_count + (unsigned long long)len;
2841 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2845 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2848 * This is guaranteed by allocating with zalloc_or_die()
2849 * and never (intentionally) writing to the last byte.
2851 * csp->receive_buffer_size is the size of the part of the
2852 * buffer we intentionally write to, but we actually
2853 * allocated csp->receive_buffer_size+1 bytes so the assertion
2854 * stays within the allocated range.
2856 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2859 * Add a trailing zero to let be able to use string operations.
2860 * XXX: do we still need this with filter_popups gone?
2862 assert(len <= csp->receive_buffer_size);
2863 csp->receive_buffer[len] = '\0';
2866 * Normally, this would indicate that we've read
2867 * as much as the server has sent us and we can
2868 * close the client connection. However, Microsoft
2869 * in its wisdom has released IIS/5 with a bug that
2870 * prevents it from sending the trailing \r\n in
2871 * a 302 redirect header (and possibly other headers).
2872 * To work around this if we've haven't parsed
2873 * a full header we'll append a trailing \r\n
2874 * and see if this now generates a valid one.
2876 * This hack shouldn't have any impacts. If we've
2877 * already transmitted the header or if this is a
2878 * SSL connection, then we won't bother with this
2879 * hack. So we only work on partially received
2880 * headers. If we append a \r\n and this still
2881 * doesn't generate a valid header, then we won't
2882 * transmit anything to the client.
2887 if (server_body || (http->ssl
2888 #ifdef FEATURE_HTTPS_INSPECTION
2894 * If we have been buffering up the document,
2895 * now is the time to apply content modification
2896 * and send the result to the client.
2898 if (buffer_and_filter_content)
2900 p = execute_content_filters(csp);
2902 * If content filtering fails, use the original
2903 * buffer and length.
2904 * (see p != NULL ? p : csp->iob->cur below)
2908 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2910 #ifdef FEATURE_COMPRESSION
2911 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2912 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2914 char *compressed_content = compress_buffer(p,
2915 (size_t *)&csp->content_length, csp->config->compression_level);
2916 if (compressed_content != NULL)
2919 p = compressed_content;
2920 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2925 if (JB_ERR_OK != update_server_headers(csp))
2927 log_error(LOG_LEVEL_FATAL,
2928 "Failed to update server headers. after filtering.");
2931 hdr = list_to_text(csp->headers);
2934 /* FIXME Should handle error properly */
2935 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2938 #ifdef FEATURE_HTTPS_INSPECTION
2940 * Sending data with standard or secured connection (HTTP/HTTPS)
2942 if (client_use_ssl(csp))
2944 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2945 (const unsigned char *)hdr, strlen(hdr)) < 0)
2946 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2947 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
2948 csp->content_length) < 0))
2950 log_error(LOG_LEVEL_ERROR, "write modified content to "
2951 "client over TLS/SSL failed");
2954 mark_server_socket_tainted(csp);
2955 close_client_and_server_ssl_connections(csp);
2960 #endif /* def FEATURE_HTTPS_INSPECTION */
2962 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2963 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
2964 (size_t)csp->content_length, write_delay))
2966 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2969 mark_server_socket_tainted(csp);
2978 break; /* "game over, man" */
2982 * This is NOT the body, so
2983 * Let's pretend the server just sent us a blank line.
2985 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
2986 len = (int)strlen(csp->receive_buffer);
2989 * Now, let the normal header parsing algorithm below do its
2990 * job. If it fails, we'll exit instead of continuing.
2997 * If we're in the body of the server document, just write it to
2998 * the client, unless we need to buffer the body for later
2999 * content-filtering.
3001 if (server_body || (http->ssl
3002 #ifdef FEATURE_HTTPS_INSPECTION
3007 if (buffer_and_filter_content)
3010 * If there is no memory left for buffering the content, or the buffer limit
3011 * has been reached, switch to non-filtering mode, i.e. make & write the
3012 * header, flush the iob and buf, and get out of the way.
3014 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3019 log_error(LOG_LEVEL_INFO,
3020 "Flushing header and buffers. Stepping back from filtering.");
3022 hdr = list_to_text(csp->headers);
3026 * Memory is too tight to even generate the header.
3027 * Send our static "Out-of-memory" page.
3029 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3030 rsp = cgi_error_memory();
3031 send_crunch_response(csp, rsp);
3032 mark_server_socket_tainted(csp);
3033 #ifdef FEATURE_HTTPS_INSPECTION
3034 close_client_and_server_ssl_connections(csp);
3038 hdrlen = strlen(hdr);
3040 #ifdef FEATURE_HTTPS_INSPECTION
3042 * Sending data with standard or secured connection (HTTP/HTTPS)
3044 if (client_use_ssl(csp))
3046 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3047 (const unsigned char *)hdr, hdrlen) < 0)
3048 || ((flushed = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3050 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3051 (const unsigned char *)csp->receive_buffer, (size_t)len) < 0))
3053 log_error(LOG_LEVEL_CONNECT,
3054 "Flush header and buffers to client failed");
3056 mark_server_socket_tainted(csp);
3057 close_client_and_server_ssl_connections(csp);
3062 #endif /* def FEATURE_HTTPS_INSPECTION */
3064 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3065 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3066 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3069 log_error(LOG_LEVEL_CONNECT,
3070 "Flush header and buffers to client failed: %E");
3072 mark_server_socket_tainted(csp);
3078 * Reset the byte_count to the amount of bytes
3079 * we just flushed. len will be added a few lines below,
3080 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3082 byte_count = (unsigned long long)flushed;
3084 buffer_and_filter_content = 0;
3090 #ifdef FEATURE_HTTPS_INSPECTION
3092 * Sending data with standard or secured connection (HTTP/HTTPS)
3094 if (client_use_ssl(csp))
3096 ret = ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3097 (const unsigned char *)csp->receive_buffer, (size_t)len);
3100 log_error(LOG_LEVEL_ERROR,
3101 "Sending data to client failed");
3102 mark_server_socket_tainted(csp);
3103 close_client_and_server_ssl_connections(csp);
3108 #endif /* def FEATURE_HTTPS_INSPECTION */
3110 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3111 (size_t)len, write_delay))
3113 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3114 mark_server_socket_tainted(csp);
3119 byte_count += (unsigned long long)len;
3125 * We're still looking for the end of the server's header.
3126 * Buffer up the data we just read. If that fails, there's
3127 * little we can do but send our static out-of-memory page.
3129 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3131 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3132 rsp = cgi_error_memory();
3133 send_crunch_response(csp, rsp);
3134 mark_server_socket_tainted(csp);
3135 #ifdef FEATURE_HTTPS_INSPECTION
3136 close_client_and_server_ssl_connections(csp);
3141 /* Convert iob into something sed() can digest */
3142 if (JB_ERR_PARSE == get_server_headers(csp))
3147 * Well, we tried our MS IIS/5 hack and it didn't work.
3148 * The header is incomplete and there isn't anything
3149 * we can do about it.
3151 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3152 "Applying the MS IIS5 hack didn't help.");
3153 log_error(LOG_LEVEL_CLF,
3154 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3155 #ifdef FEATURE_HTTPS_INSPECTION
3157 * Sending data with standard or secured connection (HTTP/HTTPS)
3159 if (client_use_ssl(csp))
3161 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3162 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3163 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3166 #endif /* def FEATURE_HTTPS_INSPECTION */
3168 write_socket_delayed(csp->cfd,
3169 INVALID_SERVER_HEADERS_RESPONSE,
3170 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3172 mark_server_socket_tainted(csp);
3173 #ifdef FEATURE_HTTPS_INSPECTION
3174 close_client_and_server_ssl_connections(csp);
3181 * Since we have to wait for more from the server before
3182 * we can parse the headers we just continue here.
3184 log_error(LOG_LEVEL_CONNECT,
3185 "Continuing buffering server headers from socket %d. "
3186 "Bytes most recently read: %d.", csp->cfd, len);
3193 * Account for the content bytes we
3194 * might have gotten with the headers.
3196 assert(csp->iob->eod >= csp->iob->cur);
3197 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3200 /* Did we actually get anything? */
3201 if (NULL == csp->headers->first)
3203 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3205 log_error(LOG_LEVEL_ERROR,
3206 "No server or forwarder response received on socket %d. "
3207 "Closing client socket %d without sending data.",
3208 csp->server_connection.sfd, csp->cfd);
3209 log_error(LOG_LEVEL_CLF,
3210 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3214 log_error(LOG_LEVEL_ERROR,
3215 "No server or forwarder response received on socket %d.",
3216 csp->server_connection.sfd);
3217 send_crunch_response(csp, error_response(csp, "no-server-data"));
3219 free_http_request(http);
3220 mark_server_socket_tainted(csp);
3221 #ifdef FEATURE_HTTPS_INSPECTION
3222 close_client_and_server_ssl_connections(csp);
3227 if (!csp->headers->first->str)
3229 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3231 assert(csp->headers->first->str);
3233 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3234 strncmpic(csp->headers->first->str, "ICY", 3))
3237 * It doesn't look like a HTTP (or Shoutcast) response:
3238 * tell the client and log the problem.
3240 if (strlen(csp->headers->first->str) > 30)
3242 csp->headers->first->str[30] = '\0';
3244 log_error(LOG_LEVEL_ERROR,
3245 "Invalid server or forwarder response. Starts with: %s",
3246 csp->headers->first->str);
3247 log_error(LOG_LEVEL_CLF,
3248 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3249 #ifdef FEATURE_HTTPS_INSPECTION
3251 * Sending data with standard or secured connection (HTTP/HTTPS)
3253 if (client_use_ssl(csp))
3255 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3256 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3257 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3260 #endif /* def FEATURE_HTTPS_INSPECTION */
3262 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3263 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3265 free_http_request(http);
3266 mark_server_socket_tainted(csp);
3267 #ifdef FEATURE_HTTPS_INSPECTION
3268 close_client_and_server_ssl_connections(csp);
3274 * We have now received the entire server header,
3275 * filter it and send the result to the client
3277 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3279 log_error(LOG_LEVEL_CLF,
3280 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3281 #ifdef FEATURE_HTTPS_INSPECTION
3283 * Sending data with standard or secured connection (HTTP/HTTPS)
3285 if (client_use_ssl(csp))
3287 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3288 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3289 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3294 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3295 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3297 free_http_request(http);
3298 mark_server_socket_tainted(csp);
3299 #ifdef FEATURE_HTTPS_INSPECTION
3300 close_client_and_server_ssl_connections(csp);
3304 hdr = list_to_text(csp->headers);
3307 /* FIXME Should handle error properly */
3308 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3311 if ((csp->flags & CSP_FLAG_CHUNKED)
3312 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3313 && ((csp->iob->eod - csp->iob->cur) >= 5)
3314 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3316 log_error(LOG_LEVEL_CONNECT,
3317 "Looks like we got the last chunk together with "
3318 "the server headers. We better stop reading.");
3319 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3320 csp->expected_content_length = byte_count;
3321 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3324 csp->server_connection.response_received = time(NULL);
3326 if (crunch_response_triggered(csp, crunchers_light))
3329 * One of the tags created by a server-header
3330 * tagger triggered a crunch. We already
3331 * delivered the crunch response to the client
3332 * and are done here after cleaning up.
3335 mark_server_socket_tainted(csp);
3336 #ifdef FEATURE_HTTPS_INSPECTION
3337 close_client_and_server_ssl_connections(csp);
3342 /* Buffer and pcrs filter this if appropriate. */
3343 buffer_and_filter_content = content_requires_filtering(csp);
3345 if (!buffer_and_filter_content)
3348 * Write the server's (modified) header to
3349 * the client (along with anything else that
3350 * may be in the buffer). Use standard or secured
3353 #ifdef FEATURE_HTTPS_INSPECTION
3354 if (client_use_ssl(csp))
3356 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3357 (const unsigned char *)hdr, strlen(hdr)) < 0)
3358 || (len = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3361 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3364 * The write failed, so don't bother mentioning it
3365 * to the client... it probably can't hear us anyway.
3368 mark_server_socket_tainted(csp);
3369 #ifdef FEATURE_HTTPS_INSPECTION
3370 close_client_and_server_ssl_connections(csp);
3376 #endif /* def FEATURE_HTTPS_INSPECTION */
3378 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3379 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3381 log_error(LOG_LEVEL_ERROR,
3382 "write header to client failed");
3384 * The write failed, so don't bother mentioning it
3385 * to the client... it probably can't hear us anyway.
3388 mark_server_socket_tainted(csp);
3394 /* we're finished with the server's header */
3400 * If this was a MS IIS/5 hack then it means the server
3401 * has already closed the connection. Nothing more to read.
3406 log_error(LOG_LEVEL_ERROR,
3407 "Closed server connection detected. "
3408 "Applying the MS IIS5 hack didn't help.");
3409 log_error(LOG_LEVEL_CLF,
3410 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3411 #ifdef FEATURE_HTTPS_INSPECTION
3413 * Sending data with standard or secured connection (HTTP/HTTPS)
3415 if (client_use_ssl(csp))
3417 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3418 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3419 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3422 #endif /* def FEATURE_HTTPS_INSPECTION */
3424 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3425 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3427 mark_server_socket_tainted(csp);
3428 #ifdef FEATURE_HTTPS_INSPECTION
3429 close_client_and_server_ssl_connections(csp);
3436 mark_server_socket_tainted(csp);
3437 #ifdef FEATURE_HTTPS_INSPECTION
3438 close_client_and_server_ssl_connections(csp);
3440 return; /* huh? we should never get here */
3442 #ifdef FEATURE_HTTPS_INSPECTION
3443 close_client_and_server_ssl_connections(csp);
3445 if (csp->content_length == 0)
3448 * If Privoxy didn't recalculate the Content-Length,
3449 * byte_count is still correct.
3451 csp->content_length = byte_count;
3454 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3455 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3456 && (csp->expected_content_length != byte_count))
3458 log_error(LOG_LEVEL_CONNECT,
3459 "Received %llu bytes while expecting %llu.",
3460 byte_count, csp->expected_content_length);
3461 mark_server_socket_tainted(csp);
3465 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3466 csp->ip_addr_str, http->ocmd, csp->content_length);
3468 csp->server_connection.timestamp = time(NULL);
3472 /*********************************************************************
3476 * Description : Once a connection from the client has been accepted,
3477 * this function is called (via serve()) to handle the
3478 * main business of the communication. This function
3479 * returns after dealing with a single request. It can
3480 * be called multiple times with the same client socket
3481 * if the client is keeping the connection alive.
3483 * The decision whether or not a client connection will
3484 * be kept alive is up to the caller which also must
3485 * close the client socket when done.
3487 * FIXME: chat is nearly thousand lines long.
3491 * 1 : csp = Current client state (buffers, headers, etc...)
3493 * Returns : Nothing.
3495 *********************************************************************/
3496 static void chat(struct client_state *csp)
3498 const struct forward_spec *fwd;
3499 struct http_request *http;
3500 /* Skeleton for HTTP response, if we should intercept the request */
3501 struct http_response *rsp;
3502 #ifdef FEATURE_HTTPS_INSPECTION
3503 int use_ssl_tunnel = 0;
3508 if (receive_client_request(csp) != JB_ERR_OK)
3512 if (parse_client_request(csp) != JB_ERR_OK)
3517 /* decide how to route the HTTP request */
3518 fwd = forward_url(csp, http);
3521 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
3522 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3526 #ifdef FEATURE_HTTPS_INSPECTION
3528 * Setting flags to use old solution with SSL tunnel and to disable
3529 * certificates verification.
3531 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3536 if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3538 csp->dont_verify_certificate = 1;
3543 * build the http request to send to the server
3544 * we have to do one of the following:
3546 * create = use the original HTTP request to create a new
3547 * HTTP request that has either the path component
3548 * without the http://domainspec (w/path) or the
3549 * full orininal URL (w/url)
3550 * Note that the path and/or the HTTP version may
3551 * have been altered by now.
3553 * SSL proxy = Open a socket to the host:port of the server
3554 * and create TLS/SSL connection with server and
3555 * with client. Then behave like mediator between
3556 * client and server over TLS/SSL.
3558 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3559 * with request to a parent proxy. Note that we'll be sending
3560 * forwarding the CFAIL message ourselves if connecting to the parent
3561 * fails, but we won't send a CSUCCEED message if it works,
3562 * since that would result in a double message (ours and the
3563 * parent's). After sending the request to the parent, we
3564 * must parse answer and send it to client. If connection
3565 * with server is established, we do TLS/SSL proxy. Otherwise
3566 * we send parent response to client and close connections.
3568 * here's the matrix:
3571 * +--------+--------+
3573 * 0 | create | SSL |
3574 * | w/path | proxy |
3575 * Forwarding +--------+--------+
3577 * 1 | create | proxy |
3578 * | w/url |+forward|
3579 * +--------+--------+
3583 #ifdef FEATURE_HTTPS_INSPECTION
3585 * Presetting SSL client and server flags
3587 if (http->ssl && !use_ssl_tunnel)
3589 http->client_ssl = 1;
3590 http->server_ssl = 1;
3594 http->client_ssl = 0;
3595 http->server_ssl = 0;
3599 if (http->ssl && connect_port_is_forbidden(csp))
3601 const char *acceptable_connect_ports =
3602 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3603 assert(NULL != acceptable_connect_ports);
3604 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3605 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3606 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3607 csp->action->flags |= ACTION_BLOCK;
3609 #ifdef FEATURE_HTTPS_INSPECTION
3610 http->client_ssl = 0;
3611 http->server_ssl = 0;
3616 freez(csp->headers->first->str);
3617 build_request_line(csp, fwd, &csp->headers->first->str);
3620 * We have a request. Check if one of the crunchers wants it
3621 * unless the client wants to use TLS/SSL in which case we
3622 * haven't setup the TLS context yet and will send the crunch
3626 #ifdef FEATURE_HTTPS_INSPECTION
3627 !client_use_ssl(csp) &&
3629 crunch_response_triggered(csp, crunchers_all))
3632 * Yes. The client got the crunch response and we're done here.
3637 log_applied_actions(csp->action);
3638 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
3640 if (fwd->forward_host)
3642 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3643 fwd->forward_host, fwd->forward_port, http->hostport);
3647 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3650 /* here we connect to the server, gateway, or the forwarder */
3652 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3653 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3654 && socket_is_still_alive(csp->server_connection.sfd)
3655 && connection_destination_matches(&csp->server_connection, http, fwd))
3657 log_error(LOG_LEVEL_CONNECT,
3658 "Reusing server socket %d connected to %s. Total requests: %u.",
3659 csp->server_connection.sfd, csp->server_connection.host,
3660 csp->server_connection.requests_sent_total);
3664 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3666 #ifdef FEATURE_CONNECTION_SHARING
3667 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3669 remember_connection(&csp->server_connection);
3672 #endif /* def FEATURE_CONNECTION_SHARING */
3674 log_error(LOG_LEVEL_CONNECT,
3675 "Closing server socket %d connected to %s. Total requests: %u.",
3676 csp->server_connection.sfd, csp->server_connection.host,
3677 csp->server_connection.requests_sent_total);
3678 close_socket(csp->server_connection.sfd);
3680 mark_connection_closed(&csp->server_connection);
3682 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3683 #ifdef FEATURE_HTTPS_INSPECTION
3684 if (http->ssl && !use_ssl_tunnel)
3688 * Creating an SSL proxy. If forwarding is disabled, we must send
3689 * CSUCCEED mesage to client. Then TLS/SSL connection with client
3693 if (fwd->forward_host == NULL)
3696 * We're lying to the client as the connection hasn't actually
3697 * been established yet. We don't establish the connection until
3698 * we have seen and parsed the encrypted client headers.
3700 if (write_socket_delayed(csp->cfd, CSUCCEED,
3701 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3703 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3708 ret = create_client_ssl_connection(csp);
3711 log_error(LOG_LEVEL_ERROR,
3712 "Can't open secure connection with client");
3713 close_client_ssl_connection(csp); /* XXX: Is this needed? */
3716 if (JB_ERR_OK != process_encrypted_request(csp))
3718 log_error(LOG_LEVEL_ERROR, "Failed to parse encrypted request.");
3719 close_client_ssl_connection(csp);
3723 * We have an encrypted request. Check if one of the crunchers now
3724 * wants it (for example because the previously invisible path was
3725 * required to match).
3727 if (crunch_response_triggered(csp, crunchers_all))
3730 * Yes. The client got the crunch response and we're done here.
3732 close_client_ssl_connection(csp);
3738 * Connecting to destination server
3740 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3742 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3744 if (fwd->type != SOCKS_NONE)
3747 rsp = error_response(csp, "forwarding-failed");
3749 else if (errno == EINVAL)
3751 rsp = error_response(csp, "no-such-domain");
3755 rsp = error_response(csp, "connect-failed");
3758 /* Write the answer to the client */
3761 send_crunch_response(csp, rsp);
3765 * Temporary workaround to prevent already-read client
3766 * bodies from being parsed as new requests. For now we
3767 * err on the safe side and throw all the following
3768 * requests under the bus, even if no client body has been
3769 * buffered. A compliant client will repeat the dropped
3770 * requests on an untainted connection.
3772 * The proper fix is to discard the no longer needed
3773 * client body in the buffer (if there is one) and to
3774 * continue parsing the bytes that follow.
3776 drain_and_close_socket(csp->cfd);
3777 csp->cfd = JB_INVALID_SOCKET;
3782 #ifdef FEATURE_HTTPS_INSPECTION
3784 * Creating TLS/SSL connections with destination server or parent
3785 * proxy. If forwarding is enabled, we must send client request to
3786 * parent proxy and receive, parse and resend parent proxy answer.
3788 if (http->ssl && !use_ssl_tunnel)
3790 if (fwd->forward_host != NULL)
3792 char server_response[BUFFER_SIZE];
3795 char *hdr = list_to_text(csp->headers);
3796 memset(server_response, 0, sizeof(server_response));
3800 log_error(LOG_LEVEL_FATAL,
3801 "Out of memory parsing client header");
3803 list_remove_all(csp->headers);
3806 * Sending client's CONNECT request to the parent proxy
3808 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
3814 log_error(LOG_LEVEL_CONNECT,
3815 "Sending request headers to: %s failed", http->hostport);
3816 mark_server_socket_tainted(csp);
3817 close_client_ssl_connection(csp);
3821 /* Waiting for parent proxy server response */
3822 len = read_socket(csp->server_connection.sfd, server_response,
3823 sizeof(server_response)-1);
3827 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
3828 "server on socket %d.", csp->server_connection.sfd);
3830 rsp = error_response(csp, "no-server-data");
3833 send_crunch_response(csp, rsp);
3835 mark_server_socket_tainted(csp);
3836 close_client_ssl_connection(csp);
3841 * Test if connection with destination server was established
3842 * successfully by parent proxy. Then we can send response to
3843 * the client and continue or stop.
3845 if (!tunnel_established_successfully(server_response, (unsigned int)len))
3847 log_error(LOG_LEVEL_ERROR, "Forwarder hasn't established "
3848 "connection with destination server.");
3850 write_socket(csp->cfd, server_response, (size_t)len);
3851 mark_server_socket_tainted(csp);
3852 close_client_ssl_connection(csp);
3857 * Parent proxy has established connection with destination server.
3858 * Now we must create TLS/SSL connection with parent proxy.
3860 ret = create_server_ssl_connection(csp);
3863 * If TLS/SSL connection wasn't created and invalid certificate
3864 * wasn't detected, we can interrupt this function. Otherwise, we
3865 * must inform the client about invalid server certificate.
3868 && (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3869 || csp->server_cert_verification_result == SSL_CERT_VALID))
3871 rsp = error_response(csp, "connect-failed");
3874 send_crunch_response(csp, rsp);
3880 * TLS/SSL connection with parent proxy is established, we can
3881 * inform client about success.
3883 ret = write_socket(csp->cfd, server_response, (size_t)len);
3886 log_error(LOG_LEVEL_ERROR,
3887 "Sending parent proxy response to client failed");
3888 mark_server_socket_tainted(csp);
3889 close_client_ssl_connection(csp);
3892 }/* -END- if (fwd->forward_host != NULL) */
3896 * Parent proxy is not used, we can just create TLS/SSL connection
3897 * with destination server
3899 int ret = create_server_ssl_connection(csp);
3902 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
3903 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
3906 * If the server certificate is invalid, we must inform
3907 * the client and then close connection to the client.
3909 ssl_send_certificate_error(csp);
3910 close_client_and_server_ssl_connections(csp);
3913 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3914 || csp->server_cert_verification_result == SSL_CERT_VALID)
3917 * The TLS/SSL connection wasn't created but an invalid
3918 * certificate wasn't detected. Report it as connection
3921 rsp = error_response(csp, "connect-failed");
3924 send_crunch_response(csp, rsp);
3926 close_client_and_server_ssl_connections(csp);
3931 }/* -END- if (http->ssl) */
3932 #endif /* def FEATURE_HTTPS_INSPECTION */
3934 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3935 save_connection_destination(csp->server_connection.sfd,
3936 http, fwd, &csp->server_connection);
3937 csp->server_connection.keep_alive_timeout =
3938 (unsigned)csp->config->keep_alive_timeout;
3940 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3942 csp->server_connection.requests_sent_total++;
3944 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
3946 /* Client headers have been sent optimistically */
3947 assert(csp->headers->last == NULL);
3949 else if (http->ssl == 0 || (fwd->forward_host
3950 #ifdef FEATURE_HTTPS_INSPECTION
3955 if (send_http_request(csp))
3957 rsp = error_response(csp, "connect-failed");
3960 send_crunch_response(csp, rsp);
3968 * Using old solution with SSL tunnel or new solution with SSL proxy
3970 list_remove_all(csp->headers);
3971 #ifdef FEATURE_HTTPS_INSPECTION
3976 * We're running an SSL tunnel and we're not forwarding,
3977 * so just ditch the client headers, send the "connect succeeded"
3978 * message to the client, flush the rest, and get out of the way.
3980 if (write_socket_delayed(csp->cfd, CSUCCEED,
3981 strlen(CSUCCEED), get_write_delay(csp)))
3986 #ifdef FEATURE_HTTPS_INSPECTION
3990 * If server certificate is invalid, we must inform client and then
3991 * close connection with client.
3993 if (csp->server_cert_verification_result != SSL_CERT_VALID)
3995 ssl_send_certificate_error(csp);
3996 close_client_and_server_ssl_connections(csp);
3999 if (send_https_request(csp))
4001 rsp = error_response(csp, "connect-failed");
4004 send_crunch_response(csp, rsp);
4006 close_client_and_server_ssl_connections(csp);
4010 #endif /* def FEATURE_HTTPS_INSPECTION */
4011 clear_iob(csp->client_iob);
4012 }/* -END- else ... if (http->ssl == 1) */
4014 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4016 /* XXX: should the time start earlier for optimistically sent data? */
4017 csp->server_connection.request_sent = time(NULL);
4019 handle_established_connection(csp);
4020 freez(csp->receive_buffer);
4025 /*********************************************************************
4027 * Function : fuzz_server_response
4029 * Description : Treat the input as a whole server response.
4032 * 1 : csp = Current client state (buffers, headers, etc...)
4033 * 2 : fuzz_input_file = File to read the input from.
4037 *********************************************************************/
4038 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4040 static struct forward_spec fwd; /* Zero'd due to being static */
4043 if (strcmp(fuzz_input_file, "-") == 0)
4045 /* XXX: Doesn'T work yet. */
4046 csp->server_connection.sfd = 0;
4050 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4051 if (csp->server_connection.sfd == -1)
4053 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4058 csp->content_type |= CT_GIF;
4059 csp->action->flags |= ACTION_DEANIMATE;
4060 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4062 csp->http->path = strdup_or_die("/");
4063 csp->http->host = strdup_or_die("fuzz.example.org");
4064 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4065 /* Prevent client socket monitoring */
4066 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4067 csp->flags |= CSP_FLAG_CHUNKED;
4069 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4070 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4072 csp->content_type |= CT_DECLARED|CT_GIF;
4074 csp->config->socket_timeout = 0;
4076 cgi_init_error_messages();
4078 handle_established_connection(csp);
4079 freez(csp->receive_buffer);
4086 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4087 /*********************************************************************
4089 * Function : prepare_csp_for_next_request
4091 * Description : Put the csp in a mostly vergin state.
4094 * 1 : csp = Current client state (buffers, headers, etc...)
4098 *********************************************************************/
4099 static void prepare_csp_for_next_request(struct client_state *csp)
4101 csp->content_type = 0;
4102 csp->content_length = 0;
4103 csp->expected_content_length = 0;
4104 csp->expected_client_content_length = 0;
4105 list_remove_all(csp->headers);
4106 clear_iob(csp->iob);
4107 freez(csp->error_message);
4108 free_http_request(csp->http);
4109 destroy_list(csp->headers);
4110 destroy_list(csp->tags);
4111 #ifdef FEATURE_CLIENT_TAGS
4112 destroy_list(csp->client_tags);
4113 freez(csp->client_address);
4115 free_current_action(csp->action);
4116 if (NULL != csp->fwd)
4118 unload_forward_spec(csp->fwd);
4121 /* XXX: Store per-connection flags someplace else. */
4122 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4123 #ifdef FEATURE_TOGGLE
4124 if (global_toggle_state)
4125 #endif /* def FEATURE_TOGGLE */
4127 csp->flags |= CSP_FLAG_TOGGLED_ON;
4130 if (csp->client_iob->eod > csp->client_iob->cur)
4132 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4133 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4135 assert(bytes_to_shift > 0);
4136 assert(data_length > 0);
4138 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
4139 data_length, bytes_to_shift);
4140 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4141 csp->client_iob->cur = csp->client_iob->buf;
4142 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4143 csp->client_iob->eod = csp->client_iob->buf + data_length;
4144 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4146 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4151 * We mainly care about resetting client_iob->cur so we don't
4152 * waste buffer space at the beginning and don't mess up the
4153 * request restoration done by cgi_show_request().
4155 * Freeing the buffer itself isn't technically necessary,
4156 * but makes debugging more convenient.
4158 clear_iob(csp->client_iob);
4161 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4164 /*********************************************************************
4168 * Description : This is little more than chat. We only "serve" to
4169 * to close (or remember) any socket that chat may have
4173 * 1 : csp = Current client state (buffers, headers, etc...)
4177 *********************************************************************/
4178 static void serve(struct client_state *csp)
4180 int config_file_change_detected = 0; /* Only used for debugging */
4181 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4182 #ifdef FEATURE_CONNECTION_SHARING
4183 static int monitor_thread_running = 0;
4184 #endif /* def FEATURE_CONNECTION_SHARING */
4185 int continue_chatting = 0;
4187 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4188 csp->ip_addr_str, csp->cfd);
4192 unsigned int latency;
4197 * If the request has been crunched,
4198 * the calculated latency is zero.
4200 latency = (unsigned)(csp->server_connection.response_received -
4201 csp->server_connection.request_sent) / 2;
4203 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4204 && (csp->flags & CSP_FLAG_CRUNCHED)
4205 && (csp->expected_client_content_length != 0))
4207 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4208 log_error(LOG_LEVEL_CONNECT,
4209 "Tainting client socket %d due to unread data.", csp->cfd);
4212 continue_chatting = (csp->config->feature_flags
4213 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4214 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4215 && (csp->cfd != JB_INVALID_SOCKET)
4216 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4217 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4218 || (csp->flags & CSP_FLAG_CHUNKED));
4220 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4221 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4223 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4225 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4227 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4228 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4229 || !socket_is_still_alive(csp->server_connection.sfd)
4230 || !(latency < csp->server_connection.keep_alive_timeout))
4232 log_error(LOG_LEVEL_CONNECT,
4233 "Closing server socket %d connected to %s. "
4234 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
4235 csp->server_connection.sfd, csp->server_connection.host,
4236 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4237 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4238 socket_is_still_alive(csp->server_connection.sfd),
4239 csp->server_connection.keep_alive_timeout);
4240 #ifdef FEATURE_CONNECTION_SHARING
4241 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4243 forget_connection(csp->server_connection.sfd);
4245 #endif /* def FEATURE_CONNECTION_SHARING */
4246 close_socket(csp->server_connection.sfd);
4247 mark_connection_closed(&csp->server_connection);
4251 if (continue_chatting && any_loaded_file_changed(csp))
4253 continue_chatting = 0;
4254 config_file_change_detected = 1;
4257 if (continue_chatting)
4259 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4260 && socket_is_still_alive(csp->cfd))
4262 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4263 "pipelined on socket %d and the socket is still alive.",
4264 csp->requests_received_total+1, csp->cfd);
4265 prepare_csp_for_next_request(csp);
4269 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4271 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4273 log_error(LOG_LEVEL_CONNECT,
4274 "Waiting for the next client request on socket %d. "
4275 "Keeping the server socket %d to %s open.",
4276 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4280 log_error(LOG_LEVEL_CONNECT,
4281 "Waiting for the next client request on socket %d. "
4282 "No server socket to keep open.", csp->cfd);
4286 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4287 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4288 && socket_is_still_alive(csp->cfd))
4290 log_error(LOG_LEVEL_CONNECT,
4291 "Client request %u arrived in time on socket %d.",
4292 csp->requests_received_total+1, csp->cfd);
4293 prepare_csp_for_next_request(csp);
4297 #ifdef FEATURE_CONNECTION_SHARING
4298 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4299 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4300 && (socket_is_still_alive(csp->server_connection.sfd)))
4302 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4304 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4309 remember_connection(&csp->server_connection);
4310 csp->server_connection.sfd = JB_INVALID_SOCKET;
4311 drain_and_close_socket(csp->cfd);
4312 csp->cfd = JB_INVALID_SOCKET;
4313 privoxy_mutex_lock(&connection_reuse_mutex);
4314 if (!monitor_thread_running)
4316 monitor_thread_running = 1;
4317 privoxy_mutex_unlock(&connection_reuse_mutex);
4318 wait_for_alive_connections();
4319 privoxy_mutex_lock(&connection_reuse_mutex);
4320 monitor_thread_running = 0;
4322 privoxy_mutex_unlock(&connection_reuse_mutex);
4324 #endif /* def FEATURE_CONNECTION_SHARING */
4328 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4330 log_error(LOG_LEVEL_CONNECT,
4331 "Closing server socket %d connected to %s. Keep-alive: %u. "
4332 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4333 "Configuration file change detected: %u",
4334 csp->server_connection.sfd, csp->server_connection.host,
4335 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4336 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4337 socket_is_still_alive(csp->server_connection.sfd),
4338 csp->server_connection.keep_alive_timeout,
4339 config_file_change_detected);
4341 } while (continue_chatting);
4345 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4347 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4349 #ifdef FEATURE_CONNECTION_SHARING
4350 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4352 forget_connection(csp->server_connection.sfd);
4354 #endif /* def FEATURE_CONNECTION_SHARING */
4355 close_socket(csp->server_connection.sfd);
4358 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4359 mark_connection_closed(&csp->server_connection);
4362 if (csp->cfd != JB_INVALID_SOCKET)
4364 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4365 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4366 "Configuration file change detected: %u. Requests received: %u.",
4367 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4368 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4369 config_file_change_detected, csp->requests_received_total);
4370 drain_and_close_socket(csp->cfd);
4373 free_csp_resources(csp);
4375 csp->flags &= ~CSP_FLAG_ACTIVE;
4381 /*********************************************************************
4383 * Function : server_thread
4385 * Description : We only exist to call `serve' in a threaded environment.
4388 * 1 : data = Current client state (buffers, headers, etc...)
4390 * Returns : Always 0.
4392 *********************************************************************/
4393 static int32 server_thread(void *data)
4395 serve((struct client_state *) data);
4402 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4403 /*********************************************************************
4407 * Description : Print usage info & exit.
4409 * Parameters : Pointer to argv[0] for identifying ourselves
4413 *********************************************************************/
4414 static void usage(const char *name)
4416 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4417 "Usage: %s [--config-test] "
4420 #endif /* defined(unix) */
4423 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4424 #endif /* defined(unix) */
4425 "[--version] [configfile]\n",
4429 show_fuzz_usage(name);
4432 printf("Aborting\n");
4437 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4440 #ifdef MUTEX_LOCKS_AVAILABLE
4441 /*********************************************************************
4443 * Function : privoxy_mutex_lock
4445 * Description : Locks a mutex.
4448 * 1 : mutex = The mutex to lock.
4450 * Returns : Void. May exit in case of errors.
4452 *********************************************************************/
4453 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4455 #ifdef FEATURE_PTHREAD
4456 int err = pthread_mutex_lock(mutex);
4459 if (mutex != &log_mutex)
4461 log_error(LOG_LEVEL_FATAL,
4462 "Mutex locking failed: %s.\n", strerror(err));
4467 EnterCriticalSection(mutex);
4468 #endif /* def FEATURE_PTHREAD */
4472 /*********************************************************************
4474 * Function : privoxy_mutex_unlock
4476 * Description : Unlocks a mutex.
4479 * 1 : mutex = The mutex to unlock.
4481 * Returns : Void. May exit in case of errors.
4483 *********************************************************************/
4484 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4486 #ifdef FEATURE_PTHREAD
4487 int err = pthread_mutex_unlock(mutex);
4490 if (mutex != &log_mutex)
4492 log_error(LOG_LEVEL_FATAL,
4493 "Mutex unlocking failed: %s.\n", strerror(err));
4498 LeaveCriticalSection(mutex);
4499 #endif /* def FEATURE_PTHREAD */
4503 /*********************************************************************
4505 * Function : privoxy_mutex_init
4507 * Description : Prepares a mutex.
4510 * 1 : mutex = The mutex to initialize.
4512 * Returns : Void. May exit in case of errors.
4514 *********************************************************************/
4515 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4517 #ifdef FEATURE_PTHREAD
4518 int err = pthread_mutex_init(mutex, 0);
4521 printf("Fatal error. Mutex initialization failed: %s.\n",
4526 InitializeCriticalSection(mutex);
4527 #endif /* def FEATURE_PTHREAD */
4529 #endif /* def MUTEX_LOCKS_AVAILABLE */
4531 /*********************************************************************
4533 * Function : initialize_mutexes
4535 * Description : Prepares mutexes if mutex support is available.
4539 * Returns : Void, exits in case of errors.
4541 *********************************************************************/
4542 static void initialize_mutexes(void)
4544 #ifdef MUTEX_LOCKS_AVAILABLE
4546 * Prepare global mutex semaphores
4549 #ifdef FEATURE_HTTPS_INSPECTION
4550 privoxy_mutex_init(&certificate_mutex);
4551 privoxy_mutex_init(&rng_mutex);
4554 privoxy_mutex_init(&log_mutex);
4555 privoxy_mutex_init(&log_init_mutex);
4556 privoxy_mutex_init(&connection_reuse_mutex);
4557 #ifdef FEATURE_EXTERNAL_FILTERS
4558 privoxy_mutex_init(&external_filter_mutex);
4560 #ifdef FEATURE_CLIENT_TAGS
4561 privoxy_mutex_init(&client_tags_mutex);
4565 * XXX: The assumptions below are a bit naive
4566 * and can cause locks that aren't necessary.
4568 * For example older FreeBSD versions (< 6.x?)
4569 * have no gethostbyname_r, but gethostbyname is
4572 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4573 privoxy_mutex_init(&resolver_mutex);
4574 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4576 * XXX: should we use a single mutex for
4577 * localtime() and gmtime() as well?
4579 #ifndef HAVE_GMTIME_R
4580 privoxy_mutex_init(&gmtime_mutex);
4581 #endif /* ndef HAVE_GMTIME_R */
4583 #ifndef HAVE_LOCALTIME_R
4584 privoxy_mutex_init(&localtime_mutex);
4585 #endif /* ndef HAVE_GMTIME_R */
4587 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4588 privoxy_mutex_init(&rand_mutex);
4589 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4591 #endif /* def MUTEX_LOCKS_AVAILABLE */
4594 /*********************************************************************
4598 * Description : Load the config file and start the listen loop.
4599 * This function is a lot more *sane* with the `load_config'
4600 * and `listen_loop' functions; although it stills does
4601 * a *little* too much for my taste.
4604 * 1 : argc = Number of parameters (including $0).
4605 * 2 : argv = Array of (char *)'s to the parameters.
4607 * Returns : 1 if : can't open config file, unrecognized directive,
4608 * stats requested in multi-thread mode, can't open the
4609 * log file, can't open the jar file, listen port is invalid,
4610 * any load fails, and can't bind port.
4612 * Else main never returns, the process must be signaled
4613 * to terminate execution. Or, on Windows, use the
4614 * "File", "Exit" menu option.
4616 *********************************************************************/
4618 int real_main(int argc, char **argv)
4620 int main(int argc, char **argv)
4624 int do_config_test = 0;
4625 #ifndef HAVE_ARC4RANDOM
4626 unsigned int random_seed;
4629 struct passwd *pw = NULL;
4630 struct group *grp = NULL;
4632 char *pre_chroot_nslookup_to_load_resolver = NULL;
4635 char *fuzz_input_type = NULL;
4636 char *fuzz_input_file = NULL;
4643 #if !defined(_WIN32)
4650 /* Prepare mutexes if supported and necessary. */
4651 initialize_mutexes();
4653 /* Enable logging until further notice. */
4657 * Parse the command line arguments
4659 * XXX: simply printing usage information in case of
4660 * invalid arguments isn't particularly user friendly.
4662 while (++argc_pos < argc)
4665 /* Check to see if the service must be installed or uninstalled */
4666 if (strncmp(argv[argc_pos], "--install", 9) == 0)
4668 const char *pName = argv[argc_pos] + 9;
4671 exit((install_service(pName)) ? 0 : 1);
4673 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4675 const char *pName = argv[argc_pos] + 11;
4678 exit((uninstall_service(pName)) ? 0 : 1);
4680 else if (strcmp(argv[argc_pos], "--service") == 0)
4682 bRunAsService = TRUE;
4683 w32_set_service_cwd();
4684 atexit(w32_service_exit_notify);
4687 #endif /* defined(_WIN32) */
4690 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4692 if (strcmp(argv[argc_pos], "--help") == 0)
4697 else if (strcmp(argv[argc_pos], "--version") == 0)
4699 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4705 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4707 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4711 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4713 if (++argc_pos == argc) usage(argv[0]);
4714 pidfile = strdup_or_die(argv[argc_pos]);
4717 else if (strcmp(argv[argc_pos], "--user") == 0)
4722 if (++argc_pos == argc) usage(argv[argc_pos]);
4724 user_arg = strdup_or_die(argv[argc_pos]);
4725 group_name = strchr(user_arg, '.');
4726 if (NULL != group_name)
4728 /* Nul-terminate the user name */
4731 /* Skip the former delimiter to actually reach the group name */
4734 grp = getgrnam(group_name);
4737 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4740 pw = getpwnam(user_arg);
4743 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4749 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4751 if (++argc_pos == argc) usage(argv[0]);
4752 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4755 else if (strcmp(argv[argc_pos], "--chroot") == 0)
4759 #endif /* defined(unix) */
4761 else if (strcmp(argv[argc_pos], "--config-test") == 0)
4766 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4769 if (argc < argc_pos + 2) usage(argv[0]);
4770 fuzz_input_type = argv[argc_pos];
4772 fuzz_input_file = argv[argc_pos];
4774 else if (strcmp(argv[argc_pos], "--stfu") == 0)
4776 set_debug_level(LOG_LEVEL_STFU);
4779 else if (argc_pos + 1 != argc)
4782 * This is neither the last command line
4783 * option, nor was it recognized before,
4784 * therefore it must be invalid.
4790 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4792 configfile = argv[argc_pos];
4795 } /* -END- while (more arguments) */
4797 show_version(Argv[0]);
4800 if (*configfile != '/')
4802 char cwd[BUFFER_SIZE];
4804 size_t abs_file_size;
4806 /* make config-filename absolute here */
4807 if (NULL == getcwd(cwd, sizeof(cwd)))
4809 perror("failed to get current working directory");
4813 basedir = strdup_or_die(cwd);
4815 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4816 abs_file = malloc_or_die(abs_file_size);
4817 strlcpy(abs_file, basedir, abs_file_size);
4818 strlcat(abs_file, "/", abs_file_size);
4819 strlcat(abs_file, configfile, abs_file_size);
4820 configfile = abs_file;
4822 #endif /* defined unix */
4826 clients->next = NULL;
4828 /* XXX: factor out initialising after the next stable release. */
4833 #ifndef HAVE_ARC4RANDOM
4834 random_seed = (unsigned int)time(NULL);
4836 srandom(random_seed);
4839 #endif /* ifdef HAVE_RANDOM */
4840 #endif /* ifndef HAVE_ARC4RANDOM */
4843 * Unix signal handling
4845 * Catch the abort, interrupt and terminate signals for a graceful exit
4846 * Catch the hangup signal so the errlog can be reopened.
4848 * Ignore the broken pipe signal as connection failures
4849 * are handled when and where they occur without relying
4852 #if !defined(_WIN32) && !defined(__OS2__)
4855 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
4857 for (idx = 0; idx < SZ(catched_signals); idx++)
4859 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
4860 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
4862 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
4863 #endif /* ifdef sun */
4865 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
4869 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4871 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
4875 #else /* ifdef _WIN32 */
4876 # ifdef _WIN_CONSOLE
4878 * We *are* in a windows console app.
4879 * Print a verbose messages about FAQ's and such
4881 printf("%s", win32_blurb);
4882 # endif /* def _WIN_CONSOLE */
4883 #endif /* def _WIN32 */
4886 if (fuzz_input_type != NULL)
4888 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
4890 log_error(LOG_LEVEL_FATAL,
4891 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
4892 "Various data structures are static which is unsafe when using threads.");
4897 exit(NULL == load_config());
4900 /* Initialize the CGI subsystem */
4901 cgi_init_error_messages();
4904 * If running on unix and without the --no-daemon
4905 * option, become a daemon. I.e. fork, detach
4906 * from tty and get process group leadership
4915 if (pid < 0) /* error */
4920 else if (pid != 0) /* parent */
4925 * must check for errors
4926 * child died due to missing files aso
4929 wpid = waitpid(pid, &status, WNOHANG);
4941 * stderr (fd 2) will be closed later on,
4942 * when the config file has been parsed.
4948 * Reserve fd 0 and 1 to prevent abort() and friends
4949 * from sending stuff to the clients or servers.
4951 fd = open("/dev/null", O_RDONLY);
4954 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4958 if (dup2(fd, 0) == -1)
4960 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
4964 fd = open("/dev/null", O_WRONLY);
4967 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4971 if (dup2(fd, 1) == -1)
4973 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
4978 #ifdef FEATURE_EXTERNAL_FILTERS
4979 for (fd = 0; fd < 3; fd++)
4981 mark_socket_for_close_on_execute(fd);
4987 } /* -END- if (daemon_mode) */
4990 * As soon as we have written the PID file, we can switch
4991 * to the user and group ID indicated by the --user option
4993 if (pidfile != NULL)
4995 write_pid_file(pidfile);
4999 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5001 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5005 if (setgroups(1, &grp->gr_gid))
5007 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5010 else if (initgroups(pw->pw_name, pw->pw_gid))
5012 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5018 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5020 /* Read the time zone file from /etc before doing chroot. */
5022 if (NULL != pre_chroot_nslookup_to_load_resolver
5023 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5025 /* Initialize resolver library. */
5026 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5028 if (chroot(pw->pw_dir) < 0)
5030 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5034 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5037 if (setuid(pw->pw_uid))
5039 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5043 char putenv_dummy[64];
5045 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5046 if (putenv(putenv_dummy) != 0)
5048 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5051 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5052 if (putenv(putenv_dummy) != 0)
5054 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5060 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5063 #endif /* defined unix */
5066 /* This will be FALSE unless the command line specified --service
5070 /* Yup, so now we must attempt to establish a connection
5071 * with the service dispatcher. This will only work if this
5072 * process was launched by the service control manager to
5073 * actually run as a service. If this isn't the case, i've
5074 * known it take around 30 seconds or so for the call to return.
5077 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5078 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5080 /* Service has run, and at this point is now being stopped, so just return */
5085 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5087 /* An error occurred. Usually it's because --service was wrongly specified
5088 * and we were unable to connect to the Service Control Dispatcher because
5089 * it wasn't expecting us and is therefore not listening.
5091 * For now, just continue below to call the listen_loop function.
5094 #endif /* def _WIN32 */
5104 /*********************************************************************
5106 * Function : bind_port_helper
5108 * Description : Bind the listen port. Handles logging, and aborts
5112 * 1 : haddr = Host address to bind to. Use NULL to bind to
5114 * 2 : hport = Specifies port to bind to.
5115 * 3 : backlog = Listen backlog.
5117 * Returns : Port that was opened.
5119 *********************************************************************/
5120 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5125 result = bind_port(haddr, hport, backlog, &bfd);
5129 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5133 log_error(LOG_LEVEL_FATAL,
5134 "can't bind to %s:%d: There may be another Privoxy "
5135 "or some other proxy running on port %d",
5136 bind_address, hport, hport);
5139 log_error(LOG_LEVEL_FATAL,
5140 "can't bind to %s:%d: The hostname is not resolvable",
5141 bind_address, hport);
5144 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5145 bind_address, hport);
5148 /* shouldn't get here */
5149 return JB_INVALID_SOCKET;
5154 if (bfd >= FD_SETSIZE)
5156 log_error(LOG_LEVEL_FATAL,
5157 "Bind socket number too high to use select(): %d >= %d",
5165 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5170 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5178 /*********************************************************************
5180 * Function : bind_ports_helper
5182 * Description : Bind the listen ports. Handles logging, and aborts
5186 * 1 : config = Privoxy configuration. Specifies ports
5188 * 2 : sockets = Preallocated array of opened sockets
5189 * corresponding to specification in config.
5190 * All non-opened sockets will be set to
5191 * JB_INVALID_SOCKET.
5193 * Returns : Nothing. Inspect sockets argument.
5195 *********************************************************************/
5196 static void bind_ports_helper(struct configuration_spec * config,
5197 jb_socket sockets[])
5201 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5203 if (config->hport[i])
5205 sockets[i] = bind_port_helper(config->haddr[i],
5206 config->hport[i], config->listen_backlog);
5207 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5208 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5210 struct accept_filter_arg af_options;
5211 bzero(&af_options, sizeof(af_options));
5212 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5213 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5214 sizeof(af_options)))
5216 log_error(LOG_LEVEL_ERROR,
5217 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5224 sockets[i] = JB_INVALID_SOCKET;
5227 config->need_bind = 0;
5231 /*********************************************************************
5233 * Function : close_ports_helper
5235 * Description : Close listenings ports.
5238 * 1 : sockets = Array of opened and non-opened sockets to
5239 * close. All sockets will be set to
5240 * JB_INVALID_SOCKET.
5242 * Returns : Nothing.
5244 *********************************************************************/
5245 static void close_ports_helper(jb_socket sockets[])
5249 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5251 if (JB_INVALID_SOCKET != sockets[i])
5253 close_socket(sockets[i]);
5255 sockets[i] = JB_INVALID_SOCKET;
5261 /* Without this simple workaround we get this compiler warning from _beginthread
5262 * warning C4028: formal parameter 1 different from declaration
5264 void w32_service_listen_loop(void *p)
5268 #endif /* def _WIN32 */
5271 /*********************************************************************
5273 * Function : listen_loop
5275 * Description : bind the listen port and enter a "FOREVER" listening loop.
5281 *********************************************************************/
5282 static void listen_loop(void)
5284 struct client_states *csp_list = NULL;
5285 struct client_state *csp = NULL;
5286 jb_socket bfds[MAX_LISTENING_SOCKETS];
5287 struct configuration_spec *config;
5288 unsigned int active_threads = 0;
5289 #if defined(FEATURE_PTHREAD)
5290 pthread_attr_t attrs;
5292 pthread_attr_init(&attrs);
5293 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5296 config = load_config();
5298 #ifdef FEATURE_CONNECTION_SHARING
5300 * XXX: Should be relocated once it no
5301 * longer needs to emit log messages.
5303 initialize_reusable_connections();
5304 #endif /* def FEATURE_CONNECTION_SHARING */
5306 bind_ports_helper(config, bfds);
5308 #ifdef FEATURE_GRACEFUL_TERMINATION
5309 while (!g_terminate)
5314 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
5315 while (waitpid(-1, NULL, WNOHANG) > 0)
5317 /* zombie children */
5319 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5322 * Free data that was used by died threads
5324 active_threads = sweep();
5328 * Re-open the errlog after HUP signal
5330 if (received_hup_signal)
5332 if (NULL != config->logfile)
5334 init_error_log(Argv[0], config->logfile);
5336 received_hup_signal = 0;
5340 csp_list = zalloc_or_die(sizeof(*csp_list));
5341 csp = &csp_list->csp;
5343 log_error(LOG_LEVEL_CONNECT,
5344 "Waiting for the next client connection. Currently active threads: %d",
5348 * This config may be outdated, but for accept_connection()
5349 * it's fresh enough.
5351 csp->config = config;
5353 if (!accept_connection(csp, bfds))
5355 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5360 csp->flags |= CSP_FLAG_ACTIVE;
5361 csp->server_connection.sfd = JB_INVALID_SOCKET;
5363 csp->config = config = load_config();
5365 if (config->need_bind)
5368 * Since we were listening to the "old port", we will not see
5369 * a "listen" param change until the next request. So, at
5370 * least 1 more request must be made for us to find the new
5371 * setting. I am simply closing the old socket and binding the
5374 * Which-ever is correct, we will serve 1 more page via the
5375 * old settings. This should probably be a "show-status"
5376 * request. This should not be a so common of an operation
5377 * that this will hurt people's feelings.
5380 close_ports_helper(bfds);
5382 bind_ports_helper(config, bfds);
5385 #ifdef FEATURE_TOGGLE
5386 if (global_toggle_state)
5387 #endif /* def FEATURE_TOGGLE */
5389 csp->flags |= CSP_FLAG_TOGGLED_ON;
5392 if (run_loader(csp))
5394 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5395 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5399 if (block_acl(NULL,csp))
5401 log_error(LOG_LEVEL_CONNECT,
5402 "Connection from %s on %s (socket %d) dropped due to ACL",
5403 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5404 close_socket(csp->cfd);
5405 freez(csp->ip_addr_str);
5406 freez(csp->listen_addr_str);
5410 #endif /* def FEATURE_ACL */
5412 if ((0 != config->max_client_connections)
5413 && (active_threads >= config->max_client_connections))
5415 log_error(LOG_LEVEL_CONNECT,
5416 "Rejecting connection from %s. Maximum number of connections reached.",
5418 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5419 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5420 close_socket(csp->cfd);
5421 freez(csp->ip_addr_str);
5422 freez(csp->listen_addr_str);
5427 /* add it to the list of clients */
5428 csp_list->next = clients->next;
5429 clients->next = csp_list;
5431 if (config->multi_threaded)
5435 /* this is a switch () statement in the C preprocessor - ugh */
5436 #undef SELECTED_ONE_OPTION
5438 /* Use Pthreads in preference to native code */
5439 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5440 #define SELECTED_ONE_OPTION
5442 pthread_t the_thread;
5444 errno = pthread_create(&the_thread, &attrs,
5445 (void * (*)(void *))serve, csp);
5446 child_id = errno ? -1 : 0;
5450 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5451 #define SELECTED_ONE_OPTION
5452 child_id = _beginthread(
5453 (void (*)(void *))serve,
5458 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
5459 #define SELECTED_ONE_OPTION
5460 child_id = _beginthread(
5461 (void(* _Optlink)(void*))serve,
5467 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5468 #define SELECTED_ONE_OPTION
5470 thread_id tid = spawn_thread
5471 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5473 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5475 child_id = (int) tid;
5484 #if !defined(SELECTED_ONE_OPTION)
5487 /* This block is only needed when using fork().
5488 * When using threads, the server thread was
5489 * created and run by the call to _beginthread().
5491 if (child_id == 0) /* child */
5494 #ifdef FEATURE_TOGGLE
5495 int inherited_toggle_state = global_toggle_state;
5496 #endif /* def FEATURE_TOGGLE */
5501 * If we've been toggled or we've blocked the request, tell Mom
5504 #ifdef FEATURE_TOGGLE
5505 if (inherited_toggle_state != global_toggle_state)
5507 rc |= RC_FLAG_TOGGLED;
5509 #endif /* def FEATURE_TOGGLE */
5511 #ifdef FEATURE_STATISTICS
5512 if (csp->flags & CSP_FLAG_REJECTED)
5514 rc |= RC_FLAG_BLOCKED;
5516 #endif /* ndef FEATURE_STATISTICS */
5520 else if (child_id > 0) /* parent */
5522 /* in a fork()'d environment, the parent's
5523 * copy of the client socket and the CSP
5527 #if !defined(_WIN32) && !defined(__CYGWIN__)
5529 wait(&child_status);
5532 * Evaluate child's return code: If the child has
5533 * - been toggled, toggle ourselves
5534 * - blocked its request, bump up the stats counter
5537 #ifdef FEATURE_TOGGLE
5538 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5540 global_toggle_state = !global_toggle_state;
5542 #endif /* def FEATURE_TOGGLE */
5544 #ifdef FEATURE_STATISTICS
5546 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5550 #endif /* def FEATURE_STATISTICS */
5552 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5553 close_socket(csp->cfd);
5554 csp->flags &= ~CSP_FLAG_ACTIVE;
5558 #undef SELECTED_ONE_OPTION
5559 /* end of cpp switch () */
5564 * Spawning the child failed, assume it's because
5565 * there are too many children running already.
5566 * XXX: If you assume ...
5568 log_error(LOG_LEVEL_ERROR,
5569 "Unable to take any additional connections: %E. Active threads: %d",
5571 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5572 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5573 close_socket(csp->cfd);
5574 csp->flags &= ~CSP_FLAG_ACTIVE;
5583 #if defined(FEATURE_PTHREAD)
5584 pthread_attr_destroy(&attrs);
5587 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5589 #ifdef FEATURE_HTTPS_INSPECTION
5590 /* Clean up. Aim: free all memory (no leaks) */
5591 if (rng_seeded == 1)
5593 mbedtls_ctr_drbg_free(&ctr_drbg);
5594 mbedtls_entropy_free(&entropy);
5598 #ifdef FEATURE_GRACEFUL_TERMINATION
5600 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
5602 unload_current_config_file();
5603 unload_current_actions_file();
5604 unload_current_re_filterfile();
5605 #ifdef FEATURE_TRUST
5606 unload_current_trust_file();
5609 if (config->multi_threaded)
5616 } while ((clients->next != NULL) && (--i > 0));
5620 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5630 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5631 /* Cleanup - remove taskbar icon etc. */
5636 #endif /* FEATURE_GRACEFUL_TERMINATION */