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 #ifdef FEATURE_HTTPS_INSPECTION
852 if (client_use_ssl(csp))
854 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
855 http->hostport, http->path);
856 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %llu",
857 csp->ip_addr_str, http->gpc, http->hostport, http->path,
858 http->version, status_code, rsp->content_length);
863 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
864 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
865 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
867 /* Write the answer to the client */
868 #ifdef FEATURE_HTTPS_INSPECTION
869 if (client_use_ssl(csp))
871 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
872 (const unsigned char *)rsp->head, rsp->head_length) < 0)
873 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
874 (const unsigned char *)rsp->body, rsp->content_length) < 0))
876 /* There is nothing we can do about it. */
877 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
878 "for %s through client socket %d using TLS/SSL",
879 http->url, csp->cfd);
885 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
886 get_write_delay(csp))
887 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
888 get_write_delay(csp)))
890 /* There is nothing we can do about it. */
891 log_error(LOG_LEVEL_CONNECT,
892 "Couldn't deliver the error message for %s through client socket %d: %E",
893 http->url, csp->cfd);
897 /* Clean up and return */
898 if (cgi_error_memory() != rsp)
900 free_http_response(rsp);
906 /*********************************************************************
908 * Function : crunch_response_triggered
910 * Description : Checks if the request has to be crunched,
911 * and delivers the crunch response if necessary.
914 * 1 : csp = Current client state (buffers, headers, etc...)
915 * 2 : crunchers = list of cruncher functions to run
917 * Returns : TRUE if the request was answered with a crunch response
920 *********************************************************************/
921 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
923 struct http_response *rsp = NULL;
924 const struct cruncher *c;
927 * If CGI request crunching is disabled,
928 * check the CGI dispatcher out of order to
929 * prevent unintentional blocks or redirects.
931 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
932 && (NULL != (rsp = dispatch_cgi(csp))))
934 /* Deliver, log and free the interception response. */
935 send_crunch_response(csp, rsp);
936 csp->flags |= CSP_FLAG_CRUNCHED;
940 for (c = crunchers; c->cruncher != NULL; c++)
943 * Check the cruncher if either Privoxy is toggled
944 * on and the request isn't forced, or if the cruncher
945 * applies to forced requests as well.
947 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
948 !(csp->flags & CSP_FLAG_FORCED)) ||
949 (c->flags & CF_IGNORE_FORCE))
951 rsp = c->cruncher(csp);
954 /* Deliver, log and free the interception response. */
955 send_crunch_response(csp, rsp);
956 csp->flags |= CSP_FLAG_CRUNCHED;
957 #ifdef FEATURE_STATISTICS
958 if (c->flags & CF_COUNT_AS_REJECT)
960 csp->flags |= CSP_FLAG_REJECTED;
962 #endif /* def FEATURE_STATISTICS */
973 /*********************************************************************
975 * Function : build_request_line
977 * Description : Builds the HTTP request line.
979 * If a HTTP forwarder is used it expects the whole URL,
980 * web servers only get the path.
983 * 1 : csp = Current client state (buffers, headers, etc...)
984 * 2 : fwd = The forwarding spec used for the request
985 * XXX: Should use http->fwd instead.
986 * 3 : request_line = The old request line which will be replaced.
988 * Returns : Nothing. Terminates in case of memory problems.
990 *********************************************************************/
991 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
993 struct http_request *http = csp->http;
996 * Downgrade http version from 1.1 to 1.0
997 * if +downgrade action applies.
999 if ((csp->action->flags & ACTION_DOWNGRADE)
1000 && (!strcmpic(http->version, "HTTP/1.1")))
1002 freez(http->version);
1003 http->version = strdup_or_die("HTTP/1.0");
1007 * Rebuild the request line.
1009 freez(*request_line);
1010 *request_line = strdup(http->gpc);
1011 string_append(request_line, " ");
1013 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1015 string_append(request_line, http->url);
1019 string_append(request_line, http->path);
1021 string_append(request_line, " ");
1022 string_append(request_line, http->version);
1024 if (*request_line == NULL)
1026 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1028 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1032 /*********************************************************************
1034 * Function : change_request_destination
1036 * Description : Parse a (rewritten) request line and regenerate
1037 * the http request data.
1040 * 1 : csp = Current client state (buffers, headers, etc...)
1042 * Returns : Forwards the parse_http_request() return code.
1043 * Terminates in case of memory problems.
1045 *********************************************************************/
1046 static jb_err change_request_destination(struct client_state *csp)
1048 struct http_request *http = csp->http;
1051 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1052 csp->headers->first->str);
1053 free_http_request(http);
1054 err = parse_http_request(csp->headers->first->str, http);
1055 if (JB_ERR_OK != err)
1057 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1058 jb_err_to_string(err));
1065 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1066 /*********************************************************************
1068 * Function : server_response_is_complete
1070 * Description : Determines whether we should stop reading
1071 * from the server socket.
1074 * 1 : csp = Current client state (buffers, headers, etc...)
1075 * 2 : content_length = Length of content received so far.
1077 * Returns : TRUE if the response is complete,
1080 *********************************************************************/
1081 static int server_response_is_complete(struct client_state *csp,
1082 unsigned long long content_length)
1084 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1086 if (!strcmpic(csp->http->gpc, "HEAD"))
1089 * "HEAD" implies no body, we are thus expecting
1090 * no content. XXX: incomplete "list" of methods?
1092 csp->expected_content_length = 0;
1093 content_length_known = TRUE;
1094 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1097 if (csp->http->status == 204 || csp->http->status == 304)
1100 * Expect no body. XXX: incomplete "list" of status codes?
1102 csp->expected_content_length = 0;
1103 content_length_known = TRUE;
1104 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1107 return (content_length_known && ((0 == csp->expected_content_length)
1108 || (csp->expected_content_length <= content_length)));
1112 #ifdef FEATURE_CONNECTION_SHARING
1113 /*********************************************************************
1115 * Function : wait_for_alive_connections
1117 * Description : Waits for alive connections to timeout.
1123 *********************************************************************/
1124 static void wait_for_alive_connections(void)
1126 int connections_alive = close_unusable_connections();
1128 while (0 < connections_alive)
1130 log_error(LOG_LEVEL_CONNECT,
1131 "Waiting for %d connections to timeout.",
1134 connections_alive = close_unusable_connections();
1137 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1140 #endif /* def FEATURE_CONNECTION_SHARING */
1143 /*********************************************************************
1145 * Function : save_connection_destination
1147 * Description : Remembers a connection for reuse later on.
1150 * 1 : sfd = Open socket to remember.
1151 * 2 : http = The destination for the connection.
1152 * 3 : fwd = The forwarder settings used.
1153 * 4 : server_connection = storage.
1157 *********************************************************************/
1158 void save_connection_destination(jb_socket sfd,
1159 const struct http_request *http,
1160 const struct forward_spec *fwd,
1161 struct reusable_connection *server_connection)
1163 assert(sfd != JB_INVALID_SOCKET);
1164 assert(NULL != http->host);
1166 server_connection->sfd = sfd;
1167 server_connection->host = strdup_or_die(http->host);
1168 server_connection->port = http->port;
1170 assert(NULL != fwd);
1171 assert(server_connection->gateway_host == NULL);
1172 assert(server_connection->gateway_port == 0);
1173 assert(server_connection->forwarder_type == 0);
1174 assert(server_connection->forward_host == NULL);
1175 assert(server_connection->forward_port == 0);
1177 server_connection->forwarder_type = fwd->type;
1178 if (NULL != fwd->gateway_host)
1180 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1184 server_connection->gateway_host = NULL;
1186 server_connection->gateway_port = fwd->gateway_port;
1188 if (NULL != fwd->forward_host)
1190 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1194 server_connection->forward_host = NULL;
1196 server_connection->forward_port = fwd->forward_port;
1200 /*********************************************************************
1202 * Function : verify_request_length
1204 * Description : Checks if we already got the whole client requests
1205 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1208 * Data that doesn't belong to the current request is
1209 * either thrown away to let the client retry on a clean
1210 * socket, or stashed to be dealt with after the current
1211 * request is served.
1214 * 1 : csp = Current client state (buffers, headers, etc...)
1218 *********************************************************************/
1219 static void verify_request_length(struct client_state *csp)
1221 unsigned long long buffered_request_bytes =
1222 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1224 if ((csp->expected_client_content_length != 0)
1225 && (buffered_request_bytes != 0))
1227 if (csp->expected_client_content_length >= buffered_request_bytes)
1229 csp->expected_client_content_length -= buffered_request_bytes;
1230 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1231 "to account for the %llu ones we already got.",
1232 csp->expected_client_content_length, buffered_request_bytes);
1236 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1237 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1238 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1239 "Marking the server socket tainted after throwing %llu bytes away.",
1240 buffered_request_bytes - csp->expected_client_content_length);
1241 csp->expected_client_content_length = 0;
1242 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1245 if (csp->expected_client_content_length == 0)
1247 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1251 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1252 && ((csp->client_iob->cur < csp->client_iob->eod)
1253 || (csp->expected_client_content_length != 0)))
1255 if (strcmpic(csp->http->gpc, "GET")
1256 && strcmpic(csp->http->gpc, "HEAD")
1257 && strcmpic(csp->http->gpc, "TRACE")
1258 && strcmpic(csp->http->gpc, "OPTIONS")
1259 && strcmpic(csp->http->gpc, "DELETE"))
1261 /* XXX: this is an incomplete hack */
1262 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1263 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1267 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1269 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1271 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1272 log_error(LOG_LEVEL_CONNECT,
1273 "Possible pipeline attempt detected. The connection will not "
1274 "be kept alive and we will only serve the first request.");
1275 /* Nuke the pipelined requests from orbit, just to be sure. */
1276 clear_iob(csp->client_iob);
1281 * Keep the pipelined data around for now, we'll deal with
1282 * it once we're done serving the current request.
1284 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1285 assert(csp->client_iob->eod >= csp->client_iob->cur);
1286 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1287 "%d bytes of pipelined data received.",
1288 (int)(csp->client_iob->eod - csp->client_iob->cur));
1294 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1295 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1298 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1301 /*********************************************************************
1303 * Function : mark_server_socket_tainted
1305 * Description : Makes sure we don't reuse a server socket
1306 * (if we didn't read everything the server sent
1307 * us reusing the socket would lead to garbage).
1310 * 1 : csp = Current client state (buffers, headers, etc...)
1314 *********************************************************************/
1315 static void mark_server_socket_tainted(struct client_state *csp)
1318 * For consistency we always mark the server socket
1319 * tainted, however, to reduce the log noise we only
1320 * emit a log message if the server socket could have
1321 * actually been reused.
1323 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1324 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1326 log_error(LOG_LEVEL_CONNECT,
1327 "Marking the server socket %d tainted.",
1328 csp->server_connection.sfd);
1330 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1333 /*********************************************************************
1335 * Function : get_request_line
1337 * Description : Read the client request line.
1340 * 1 : csp = Current client state (buffers, headers, etc...)
1342 * Returns : Pointer to request line or NULL in case of errors.
1344 *********************************************************************/
1345 static char *get_request_line(struct client_state *csp)
1347 char buf[BUFFER_SIZE];
1348 char *request_line = NULL;
1351 memset(buf, 0, sizeof(buf));
1353 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1356 * If there are multiple pipelined requests waiting,
1357 * the flag will be set again once the next request
1360 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1362 request_line = get_header(csp->client_iob);
1363 if ((NULL != request_line) && ('\0' != *request_line))
1365 return request_line;
1369 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1370 "received yet. Continuing reading from %d.", csp->cfd);
1378 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1380 !data_is_available(csp->cfd, csp->config->socket_timeout)
1383 if (socket_is_still_alive(csp->cfd))
1385 log_error(LOG_LEVEL_CONNECT,
1386 "No request line on socket %d received in time. Timeout: %d.",
1387 csp->cfd, csp->config->socket_timeout);
1388 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1389 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1390 get_write_delay(csp));
1394 log_error(LOG_LEVEL_CONNECT,
1395 "The client side of the connection on socket %d got "
1396 "closed without sending a complete request line.", csp->cfd);
1401 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1403 if (len <= 0) return NULL;
1406 * If there is no memory left for buffering the
1407 * request, there is nothing we can do but hang up
1409 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1414 request_line = get_header(csp->client_iob);
1416 } while ((NULL != request_line) && ('\0' == *request_line));
1418 return request_line;
1424 CHUNK_STATUS_MISSING_DATA,
1425 CHUNK_STATUS_BODY_COMPLETE,
1426 CHUNK_STATUS_PARSE_ERROR
1430 /*********************************************************************
1432 * Function : chunked_body_is_complete
1434 * Description : Figures out whether or not a chunked body is complete.
1436 * Currently it always starts at the beginning of the
1437 * buffer which is somewhat wasteful and prevents Privoxy
1438 * from starting to forward the correctly parsed chunks
1439 * as soon as theoretically possible.
1441 * Should be modified to work with a common buffer,
1442 * and allow the caller to skip already parsed chunks.
1444 * This would allow the function to be used for unbuffered
1445 * response bodies as well.
1448 * 1 : iob = Buffer with the body to check.
1449 * 2 : length = Length of complete body
1451 * Returns : Enum with the result of the check.
1453 *********************************************************************/
1454 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1456 unsigned int chunksize;
1462 * We need at least a single digit, followed by "\r\n",
1463 * followed by an unknown amount of data, followed by "\r\n".
1465 if (p + 5 > iob->eod)
1467 return CHUNK_STATUS_MISSING_DATA;
1469 if (sscanf(p, "%x", &chunksize) != 1)
1471 return CHUNK_STATUS_PARSE_ERROR;
1475 * We want at least a single digit, followed by "\r\n",
1476 * followed by the specified amount of data, followed by "\r\n".
1478 if (p + chunksize + 5 > iob->eod)
1480 return CHUNK_STATUS_MISSING_DATA;
1483 /* Skip chunk-size. */
1484 p = strstr(p, "\r\n");
1487 return CHUNK_STATUS_PARSE_ERROR;
1489 /* Move beyond the chunkdata. */
1492 /* There should be another "\r\n" to skip */
1493 if (memcmp(p, "\r\n", 2))
1495 return CHUNK_STATUS_PARSE_ERROR;
1498 } while (chunksize > 0U);
1500 *length = (size_t)(p - iob->cur);
1501 assert(*length <= (size_t)(iob->eod - iob->cur));
1502 assert(p <= iob->eod);
1504 return CHUNK_STATUS_BODY_COMPLETE;
1509 /*********************************************************************
1511 * Function : receive_chunked_client_request_body
1513 * Description : Read the chunk-encoded client request body.
1514 * Failures are dealt with.
1517 * 1 : csp = Current client state (buffers, headers, etc...)
1519 * Returns : JB_ERR_OK or JB_ERR_PARSE
1521 *********************************************************************/
1522 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1525 enum chunk_status status;
1527 while (CHUNK_STATUS_MISSING_DATA ==
1528 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1530 char buf[BUFFER_SIZE];
1533 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1535 log_error(LOG_LEVEL_ERROR,
1536 "Timeout while waiting for the client body.");
1539 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1542 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1545 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1550 if (status != CHUNK_STATUS_BODY_COMPLETE)
1552 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1553 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1554 log_error(LOG_LEVEL_CLF,
1555 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1556 return JB_ERR_PARSE;
1558 log_error(LOG_LEVEL_CONNECT,
1559 "Chunked client body completely read. Length: %d", body_length);
1560 csp->expected_client_content_length = body_length;
1568 /*********************************************************************
1570 * Function : fuzz_chunked_transfer_encoding
1572 * Description : Treat the fuzzed input as chunked transfer encoding
1573 * to check and dechunk.
1576 * 1 : csp = Used to store the data.
1577 * 2 : fuzz_input_file = File to read the input from.
1579 * Returns : Result of dechunking
1581 *********************************************************************/
1582 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1585 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1586 enum chunk_status status;
1588 status = chunked_body_is_complete(csp->iob, &length);
1589 if (CHUNK_STATUS_BODY_COMPLETE != status)
1591 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1594 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1599 /*********************************************************************
1601 * Function : fuzz_client_request
1603 * Description : Try to get a client request from the fuzzed input.
1606 * 1 : csp = Current client state (buffers, headers, etc...)
1607 * 2 : fuzz_input_file = File to read the input from.
1609 * Returns : Result of fuzzing.
1611 *********************************************************************/
1612 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1617 csp->ip_addr_str = "fuzzer";
1619 if (strcmp(fuzz_input_file, "-") != 0)
1621 log_error(LOG_LEVEL_FATAL,
1622 "Fuzzed client requests can currenty only be read from stdin (-).");
1624 err = receive_client_request(csp);
1625 if (err != JB_ERR_OK)
1629 err = parse_client_request(csp);
1630 if (err != JB_ERR_OK)
1638 #endif /* def FUZZ */
1641 #ifdef FEATURE_FORCE_LOAD
1642 /*********************************************************************
1644 * Function : force_required
1646 * Description : Checks a request line to see if it contains
1647 * the FORCE_PREFIX. If it does, it is removed
1648 * unless enforcing requests has beend disabled.
1651 * 1 : request_line = HTTP request line
1653 * Returns : TRUE if force is required, FALSE otherwise.
1655 *********************************************************************/
1656 static int force_required(const struct client_state *csp, char *request_line)
1660 p = strstr(request_line, "http://");
1664 p += strlen("http://");
1668 /* Intercepted request usually don't specify the protocol. */
1672 /* Go to the beginning of the path */
1677 * If the path is missing the request line is invalid and we
1678 * are done here. The client-visible rejection happens later on.
1683 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1685 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1687 /* XXX: Should clean more carefully */
1688 strclean(request_line, FORCE_PREFIX);
1689 log_error(LOG_LEVEL_FORCE,
1690 "Enforcing request: \"%s\".", request_line);
1694 log_error(LOG_LEVEL_FORCE,
1695 "Ignored force prefix in request: \"%s\".", request_line);
1701 #endif /* def FEATURE_FORCE_LOAD */
1704 /*********************************************************************
1706 * Function : receive_client_request
1708 * Description : Read the client's request (more precisely the
1709 * client headers) and answer it if necessary.
1712 * 1 : csp = Current client state (buffers, headers, etc...)
1714 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1716 *********************************************************************/
1717 static jb_err receive_client_request(struct client_state *csp)
1719 char buf[BUFFER_SIZE];
1722 struct http_request *http;
1726 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1727 struct list header_list;
1728 struct list *headers = &header_list;
1730 /* We don't care if the arriving data is a valid HTTP request or not. */
1731 csp->requests_received_total++;
1735 memset(buf, 0, sizeof(buf));
1737 req = get_request_line(csp);
1740 mark_server_socket_tainted(csp);
1741 return JB_ERR_PARSE;
1743 assert(*req != '\0');
1745 if (client_protocol_is_unsupported(csp, req))
1747 return JB_ERR_PARSE;
1750 #ifdef FEATURE_FORCE_LOAD
1751 if (force_required(csp, req))
1753 csp->flags |= CSP_FLAG_FORCED;
1755 #endif /* def FEATURE_FORCE_LOAD */
1757 err = parse_http_request(req, http);
1759 if (JB_ERR_OK != err)
1761 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1762 get_write_delay(csp));
1763 /* XXX: Use correct size */
1764 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1765 log_error(LOG_LEVEL_ERROR,
1766 "Couldn't parse request line received from %s: %s",
1767 csp->ip_addr_str, jb_err_to_string(err));
1769 free_http_request(http);
1770 return JB_ERR_PARSE;
1773 /* grab the rest of the client's headers */
1777 p = get_header(csp->client_iob);
1781 /* There are no additional headers to read. */
1788 * We didn't receive a complete header
1789 * line yet, get the rest of it.
1791 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1793 log_error(LOG_LEVEL_ERROR,
1794 "Stopped grabbing the client headers.");
1795 destroy_list(headers);
1796 return JB_ERR_PARSE;
1799 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1802 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1803 destroy_list(headers);
1804 return JB_ERR_PARSE;
1807 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1810 * If there is no memory left for buffering the
1811 * request, there is nothing we can do but hang up
1813 destroy_list(headers);
1814 return JB_ERR_MEMORY;
1819 if (!strncmpic(p, "Transfer-Encoding:", 18))
1822 * XXX: should be called through sed()
1823 * but currently can't.
1825 client_transfer_encoding(csp, &p);
1828 * We were able to read a complete
1829 * header and can finally enlist it.
1836 if (http->host == NULL)
1839 * If we still don't know the request destination,
1840 * the request is invalid or the client uses
1841 * Privoxy without its knowledge.
1843 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1846 * Our attempts to get the request destination
1847 * elsewhere failed or Privoxy is configured
1848 * to only accept proxy requests.
1850 * An error response has already been send
1851 * and we're done here.
1853 return JB_ERR_PARSE;
1857 #ifdef FEATURE_CLIENT_TAGS
1858 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1859 set_client_address(csp, headers);
1860 get_tag_list_for_client(csp->client_tags, csp->client_address);
1864 * Determine the actions for this URL
1866 #ifdef FEATURE_TOGGLE
1867 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1869 /* Most compatible set of actions (i.e. none) */
1870 init_current_action(csp->action);
1873 #endif /* ndef FEATURE_TOGGLE */
1875 get_url_actions(csp, http);
1878 enlist(csp->headers, http->cmd);
1880 /* Append the previously read headers */
1881 err = list_append_list_unique(csp->headers, headers);
1882 destroy_list(headers);
1889 /*********************************************************************
1891 * Function : parse_client_request
1893 * Description : Parses the client's request and decides what to do
1896 * Note that since we're not using select() we could get
1897 * blocked here if a client connected, then didn't say
1901 * 1 : csp = Current client state (buffers, headers, etc...)
1903 * Returns : JB_ERR_OK or JB_ERR_PARSE
1905 *********************************************************************/
1906 static jb_err parse_client_request(struct client_state *csp)
1908 struct http_request *http = csp->http;
1911 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1912 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1913 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1914 && (csp->http->ssl == 0))
1916 /* Assume persistence until further notice */
1917 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1920 if (csp->http->ssl == 0)
1923 * This whole block belongs to chat() but currently
1924 * has to be executed before sed().
1926 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1928 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1930 return JB_ERR_PARSE;
1935 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1937 verify_request_length(csp);
1941 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1943 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1945 err = sed(csp, FILTER_CLIENT_HEADERS);
1946 if (JB_ERR_OK != err)
1948 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1950 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1951 csp->ip_addr_str, csp->http->cmd);
1952 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1953 return JB_ERR_PARSE;
1955 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1957 /* Check request line for rewrites. */
1958 if ((NULL == csp->headers->first->str)
1959 || (strcmp(http->cmd, csp->headers->first->str) &&
1960 (JB_ERR_OK != change_request_destination(csp))))
1963 * A header filter broke the request line - bail out.
1965 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1966 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1967 /* XXX: Use correct size */
1968 log_error(LOG_LEVEL_CLF,
1969 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1970 log_error(LOG_LEVEL_ERROR,
1971 "Invalid request line after applying header filters.");
1972 free_http_request(http);
1974 return JB_ERR_PARSE;
1977 if (client_has_unsupported_expectations(csp))
1979 return JB_ERR_PARSE;
1987 /*********************************************************************
1989 * Function : send_http_request
1991 * Description : Sends the HTTP headers from the client request
1992 * and all the body data that has already been received.
1995 * 1 : csp = Current client state (buffers, headers, etc...)
1997 * Returns : 0 on success, anything else is an error.
1999 *********************************************************************/
2000 static int send_http_request(struct client_state *csp)
2005 hdr = list_to_text(csp->headers);
2008 /* FIXME Should handle error properly */
2009 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2011 list_remove_all(csp->headers);
2014 * Write the client's (modified) header to the server
2015 * (along with anything else that may be in the buffer)
2017 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2022 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2023 csp->http->hostport);
2025 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2026 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2029 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2030 csp->http->hostport);
2033 return write_failure;
2038 #ifdef FEATURE_HTTPS_INSPECTION
2039 /*********************************************************************
2041 * Function : receive_and_send_encrypted_post_data
2043 * Description : Reads remaining POST data from the client and sends
2047 * 1 : csp = Current client state (buffers, headers, etc...)
2049 * Returns : 0 on success, anything else is an error.
2051 *********************************************************************/
2052 static jb_err receive_and_send_encrypted_post_data(struct client_state *csp)
2054 int content_length_known = csp->expected_client_content_length != 0;
2056 while (is_ssl_pending(&(csp->mbedtls_client_attr.ssl)))
2058 unsigned char buf[BUFFER_SIZE];
2060 int max_bytes_to_read = sizeof(buf);
2062 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2064 max_bytes_to_read = (int)csp->expected_client_content_length;
2066 log_error(LOG_LEVEL_CONNECT,
2067 "Waiting for up to %d bytes of POST data from the client.",
2069 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl), buf,
2070 (unsigned)max_bytes_to_read);
2077 /* XXX: Does this actually happen? */
2080 log_error(LOG_LEVEL_HEADER, "Forwarding %d bytes of encrypted POST data",
2082 len = ssl_send_data(&(csp->mbedtls_server_attr.ssl), buf, (size_t)len);
2087 if (csp->expected_client_content_length != 0)
2089 if (csp->expected_client_content_length >= len)
2091 csp->expected_client_content_length -= (unsigned)len;
2093 if (csp->expected_client_content_length == 0)
2095 log_error(LOG_LEVEL_HEADER, "Forwarded the last %d bytes", len);
2101 log_error(LOG_LEVEL_HEADER, "Done forwarding encrypted POST data");
2108 /*********************************************************************
2110 * Function : send_https_request
2112 * Description : Sends the HTTP headers from the client request
2113 * and all the body data that has already been received.
2116 * 1 : csp = Current client state (buffers, headers, etc...)
2118 * Returns : 0 on success, anything else is an error.
2120 *********************************************************************/
2121 static int send_https_request(struct client_state *csp)
2127 hdr = list_to_text(csp->https_headers);
2130 /* FIXME Should handle error properly */
2131 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2133 list_remove_all(csp->https_headers);
2136 * Write the client's (modified) header to the server
2137 * (along with anything else that may be in the buffer)
2139 ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2140 (const unsigned char *)hdr, strlen(hdr));
2145 log_error(LOG_LEVEL_CONNECT,
2146 "Failed sending encrypted request headers to: %s: %E",
2147 csp->http->hostport);
2148 mark_server_socket_tainted(csp);
2152 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2153 && ((flushed = ssl_flush_socket(&(csp->mbedtls_server_attr.ssl),
2154 csp->client_iob)) < 0))
2156 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2157 csp->http->hostport);
2162 if (csp->expected_client_content_length != 0)
2164 if (csp->expected_client_content_length < flushed)
2166 log_error(LOG_LEVEL_ERROR,
2167 "Flushed %d bytes of request body while only expecting %llu",
2168 flushed, csp->expected_client_content_length);
2169 csp->expected_client_content_length = 0;
2173 log_error(LOG_LEVEL_CONNECT,
2174 "Flushed %d bytes of request body while expecting %llu",
2175 flushed, csp->expected_client_content_length);
2176 csp->expected_client_content_length -= (unsigned)flushed;
2177 if (receive_and_send_encrypted_post_data(csp))
2185 log_error(LOG_LEVEL_CONNECT,
2186 "Flushed %d bytes of request body", flushed);
2190 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2197 /*********************************************************************
2199 * Function : receive_encrypted_request
2201 * Description : Receives an encrypted request.
2204 * 1 : csp = Current client state (buffers, headers, etc...)
2206 * Returns : JB_ERR_OK on success,
2207 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2209 *********************************************************************/
2210 static jb_err receive_encrypted_request(struct client_state *csp)
2212 char buf[BUFFER_SIZE];
2218 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2219 if (!data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout))
2221 log_error(LOG_LEVEL_CONNECT,
2222 "Socket %d timed out while waiting for client headers", csp->cfd);
2223 return JB_ERR_PARSE;
2225 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2226 (unsigned char *)buf, sizeof(buf));
2229 return JB_ERR_PARSE;
2231 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2233 return JB_ERR_MEMORY;
2235 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2236 } while (p == NULL);
2238 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2244 /*********************************************************************
2246 * Function : process_encrypted_request
2248 * Description : Receives and parses an encrypted request.
2251 * 1 : csp = Current client state (buffers, headers, etc...)
2253 * Returns : JB_ERR_OK on success,
2254 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2256 *********************************************************************/
2257 static jb_err process_encrypted_request(struct client_state *csp)
2262 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2263 struct list header_list;
2264 struct list *headers = &header_list;
2266 err = receive_encrypted_request(csp);
2267 if (err != JB_ERR_OK)
2269 /* XXX: Also used for JB_ERR_MEMORY */
2270 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2271 jb_err_to_string(err));
2272 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2273 (const unsigned char *)CHEADER, strlen(CHEADER));
2277 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2278 request_line = get_header(csp->client_iob);
2279 if (request_line == NULL)
2281 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2282 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2283 (const unsigned char *)CHEADER, strlen(CHEADER));
2284 return JB_ERR_PARSE;
2286 assert(*request_line != '\0');
2288 if (client_protocol_is_unsupported(csp, request_line))
2291 * If the protocol is unsupported we're done here.
2292 * client_protocol_is_unsupported() took care of sending
2293 * the error response and logging the error message.
2295 return JB_ERR_PARSE;
2298 #ifdef FEATURE_FORCE_LOAD
2299 if (force_required(csp, request_line))
2301 csp->flags |= CSP_FLAG_FORCED;
2303 #endif /* def FEATURE_FORCE_LOAD */
2305 free_http_request(csp->http);
2307 err = parse_http_request(request_line, csp->http);
2308 /* XXX: Restore ssl setting. This is ugly */
2309 csp->http->client_ssl = 1;
2310 csp->http->server_ssl = 1;
2312 freez(request_line);
2313 if (JB_ERR_OK != err)
2315 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2316 (const unsigned char *)CHEADER, strlen(CHEADER));
2317 /* XXX: Use correct size */
2318 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2319 log_error(LOG_LEVEL_ERROR,
2320 "Couldn't parse request line received from %s: %s",
2321 csp->ip_addr_str, jb_err_to_string(err));
2323 free_http_request(csp->http);
2324 return JB_ERR_PARSE;
2327 /* Parse the rest of the client's headers. */
2331 p = get_header(csp->client_iob);
2335 /* There are no additional headers to read. */
2342 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2345 * Our attempts to get the request destination
2348 log_error(LOG_LEVEL_ERROR,
2349 "Failed to get the encrypted request destination");
2350 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2351 (const unsigned char *)CHEADER, strlen(CHEADER));
2352 return JB_ERR_PARSE;
2355 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
2356 /* Split the domain we just got for pattern matching */
2357 init_domain_components(csp->http);
2360 #ifdef FEATURE_TOGGLE
2361 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2364 /* Determine the actions for this URL */
2365 get_url_actions(csp, csp->http);
2368 enlist(csp->https_headers, csp->http->cmd);
2370 /* Append the previously read headers */
2371 err = list_append_list_unique(csp->https_headers, headers);
2372 destroy_list(headers);
2373 if (JB_ERR_OK != err)
2375 /* XXX: Send error message */
2379 /* XXX: Work around crash */
2380 csp->error_message = NULL;
2382 /* XXX: Why do this here? */
2385 err = sed_https(csp);
2386 if (JB_ERR_OK != err)
2388 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2389 (const unsigned char *)CHEADER, strlen(CHEADER));
2390 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2392 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2393 csp->ip_addr_str, csp->http->cmd);
2394 return JB_ERR_PARSE;
2397 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2398 log_applied_actions(csp->action);
2399 log_error(LOG_LEVEL_GPC, "https://%s%s", csp->http->hostport,
2408 /*********************************************************************
2410 * Function : handle_established_connection
2412 * Description : Shuffle data between client and server once the
2413 * connection has been established.
2416 * 1 : csp = Current client state (buffers, headers, etc...)
2418 * Returns : Nothing.
2420 *********************************************************************/
2421 static void handle_established_connection(struct client_state *csp)
2427 struct pollfd poll_fds[2];
2431 struct timeval timeout;
2434 int ms_iis5_hack = 0;
2435 unsigned long long byte_count = 0;
2436 struct http_request *http;
2437 long len = 0; /* for buffer sizes (and negative error codes) */
2438 int buffer_and_filter_content = 0;
2439 unsigned int write_delay;
2440 #ifdef FEATURE_HTTPS_INSPECTION
2442 int use_ssl_tunnel = 0;
2443 csp->dont_verify_certificate = 0;
2445 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2447 /* Pass encrypted content without filtering. */
2452 /* Skeleton for HTTP response, if we should intercept the request */
2453 struct http_response *rsp;
2454 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2455 int watch_client_socket;
2458 csp->receive_buffer_size = csp->config->receive_buffer_size;
2459 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2460 if (csp->receive_buffer == NULL)
2462 log_error(LOG_LEVEL_ERROR,
2463 "Out of memory. Failed to allocate the receive buffer.");
2464 rsp = cgi_error_memory();
2465 send_crunch_response(csp, rsp);
2472 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2473 csp->cfd : csp->server_connection.sfd;
2476 /* pass data between the client and server
2477 * until one or the other shuts down the connection.
2482 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2483 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2485 write_delay = get_write_delay(csp);
2492 * FD_ZERO here seems to point to an errant macro which crashes.
2493 * So do this by hand for now...
2495 memset(&rfds,0x00,sizeof(fd_set));
2499 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2500 if (!watch_client_socket)
2502 maxfd = csp->server_connection.sfd;
2505 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2507 FD_SET(csp->cfd, &rfds);
2510 FD_SET(csp->server_connection.sfd, &rfds);
2511 #endif /* ndef HAVE_POLL */
2513 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2514 if ((csp->flags & CSP_FLAG_CHUNKED)
2515 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2516 && ((csp->iob->eod - csp->iob->cur) >= 5)
2517 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2520 * XXX: This check should be obsolete now,
2521 * but let's wait a while to be sure.
2523 log_error(LOG_LEVEL_CONNECT,
2524 "Looks like we got the last chunk together with "
2525 "the server headers but didn't detect it earlier. "
2526 "We better stop reading.");
2527 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2528 csp->expected_content_length = byte_count;
2529 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2531 if (server_body && server_response_is_complete(csp, byte_count))
2533 if (csp->expected_content_length == byte_count)
2535 log_error(LOG_LEVEL_CONNECT,
2536 "Done reading from server. Content length: %llu as expected. "
2537 "Bytes most recently read: %d.",
2542 log_error(LOG_LEVEL_CONNECT,
2543 "Done reading from server. Expected content length: %llu. "
2544 "Actual content length: %llu. Bytes most recently read: %d.",
2545 csp->expected_content_length, byte_count, len);
2549 * XXX: Should not jump around, handle_established_connection()
2550 * is complicated enough already.
2554 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2557 poll_fds[0].fd = csp->cfd;
2558 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2559 if (!watch_client_socket)
2562 * Ignore incoming data, but still watch out
2563 * for disconnects etc. These flags are always
2564 * implied anyway but explicitly setting them
2567 poll_fds[0].events = POLLERR|POLLHUP;
2572 poll_fds[0].events = POLLIN;
2574 poll_fds[1].fd = csp->server_connection.sfd;
2575 poll_fds[1].events = POLLIN;
2576 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2578 timeout.tv_sec = csp->config->socket_timeout;
2579 timeout.tv_usec = 0;
2580 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
2581 #endif /* def HAVE_POLL */
2583 /*server or client not responding in timeout */
2586 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2587 csp->config->socket_timeout, http->url);
2588 if ((byte_count == 0) && (http->ssl == 0))
2590 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2592 mark_server_socket_tainted(csp);
2593 #ifdef FEATURE_HTTPS_INSPECTION
2594 close_client_and_server_ssl_connections(csp);
2601 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2603 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2605 mark_server_socket_tainted(csp);
2606 #ifdef FEATURE_HTTPS_INSPECTION
2607 close_client_and_server_ssl_connections(csp);
2613 * This is the body of the browser's request,
2614 * just read and write it.
2616 * Receives data from browser and sends it to server
2618 * XXX: Make sure the client doesn't use pipelining
2619 * behind Privoxy's back.
2622 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2624 log_error(LOG_LEVEL_CONNECT,
2625 "The client socket %d has become unusable while "
2626 "the server socket %d is still open.",
2627 csp->cfd, csp->server_connection.sfd);
2628 mark_server_socket_tainted(csp);
2632 if (poll_fds[0].revents != 0)
2634 if (FD_ISSET(csp->cfd, &rfds))
2635 #endif /* def HAVE_POLL*/
2637 int max_bytes_to_read = (int)csp->receive_buffer_size;
2639 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2640 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2642 if (data_is_available(csp->cfd, 0))
2645 * If the next request is already waiting, we have
2646 * to stop select()ing the client socket. Otherwise
2647 * we would always return right away and get nothing
2650 watch_client_socket = 0;
2651 log_error(LOG_LEVEL_CONNECT,
2652 "Stop watching client socket %d. "
2653 "There's already another request waiting.",
2658 * If the client socket is set, but there's no data
2659 * available on the socket, the client went fishing
2660 * and continuing talking to the server makes no sense.
2662 log_error(LOG_LEVEL_CONNECT,
2663 "The client closed socket %d while "
2664 "the server socket %d is still open.",
2665 csp->cfd, csp->server_connection.sfd);
2666 mark_server_socket_tainted(csp);
2669 if (csp->expected_client_content_length != 0)
2671 if (csp->expected_client_content_length < csp->receive_buffer_size)
2673 max_bytes_to_read = (int)csp->expected_client_content_length;
2675 log_error(LOG_LEVEL_CONNECT,
2676 "Waiting for up to %d bytes from the client.",
2679 assert(max_bytes_to_read <= csp->receive_buffer_size);
2680 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2682 #ifdef FEATURE_HTTPS_INSPECTION
2683 if (client_use_ssl(csp))
2685 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
2689 #endif /* def FEATURE_HTTPS_INSPECTION */
2691 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2695 /* XXX: not sure if this is necessary. */
2696 mark_server_socket_tainted(csp);
2697 break; /* "game over, man" */
2700 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2701 if (csp->expected_client_content_length != 0)
2703 assert(len <= max_bytes_to_read);
2704 csp->expected_client_content_length -= (unsigned)len;
2705 log_error(LOG_LEVEL_CONNECT,
2706 "Expected client content length set to %llu "
2707 "after reading %d bytes.",
2708 csp->expected_client_content_length, len);
2709 if (csp->expected_client_content_length == 0)
2711 log_error(LOG_LEVEL_CONNECT,
2712 "Done reading from the client.");
2713 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2716 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2718 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2720 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2721 mark_server_socket_tainted(csp);
2729 * The server wants to talk. It could be the header or the body.
2730 * If `hdr' is null, then it's the header otherwise it's the body.
2731 * FIXME: Does `hdr' really mean `host'? No.
2734 if (poll_fds[1].revents != 0)
2736 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2737 #endif /* HAVE_POLL */
2739 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2741 * If we are buffering content, we don't want to eat up to
2742 * buffer-limit bytes if the client no longer cares about them.
2743 * If we aren't buffering, however, a dead client socket will be
2744 * noticed pretty much right away anyway, so we can reduce the
2745 * overhead by skipping the check.
2747 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2750 log_error(LOG_LEVEL_CONNECT,
2751 "The server still wants to talk, but the client may already have hung up on us.");
2753 log_error(LOG_LEVEL_CONNECT,
2754 "The server still wants to talk, but the client hung up on us.");
2755 mark_server_socket_tainted(csp);
2756 #ifdef FEATURE_HTTPS_INSPECTION
2757 close_client_and_server_ssl_connections(csp);
2760 #endif /* def _WIN32 */
2762 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2764 #ifdef FEATURE_HTTPS_INSPECTION
2766 * Reading data from standard or secured connection (HTTP/HTTPS)
2768 if (server_use_ssl(csp))
2770 len = ssl_recv_data(&(csp->mbedtls_server_attr.ssl),
2771 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2776 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2777 (int)csp->receive_buffer_size);
2782 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2784 if ((http->ssl && (csp->fwd == NULL))
2785 #ifdef FEATURE_HTTPS_INSPECTION
2791 * Just hang up. We already confirmed the client's CONNECT
2792 * request with status code 200 and unencrypted content is
2793 * no longer welcome.
2795 log_error(LOG_LEVEL_ERROR,
2796 "CONNECT already confirmed. Unable to tell the client about the problem.");
2799 else if (byte_count)
2802 * Just hang up. We already transmitted the original headers
2803 * and parts of the original content and therefore missed the
2804 * chance to send an error message (without risking data corruption).
2806 * XXX: we could retry with a fancy range request here.
2808 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2809 "Unable to tell the client about the problem.");
2810 mark_server_socket_tainted(csp);
2811 #ifdef FEATURE_HTTPS_INSPECTION
2812 close_client_and_server_ssl_connections(csp);
2817 * XXX: Consider handling the cases above the same.
2819 mark_server_socket_tainted(csp);
2823 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2824 if (csp->flags & CSP_FLAG_CHUNKED)
2826 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2828 /* XXX: this is a temporary hack */
2829 log_error(LOG_LEVEL_CONNECT,
2830 "Looks like we reached the end of the last chunk. "
2831 "We better stop reading.");
2832 csp->expected_content_length = byte_count + (unsigned long long)len;
2833 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2837 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2840 * This is guaranteed by allocating with zalloc_or_die()
2841 * and never (intentionally) writing to the last byte.
2843 * csp->receive_buffer_size is the size of the part of the
2844 * buffer we intentionally write to, but we actually
2845 * allocated csp->receive_buffer_size+1 bytes so the assertion
2846 * stays within the allocated range.
2848 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2851 * Add a trailing zero to let be able to use string operations.
2852 * XXX: do we still need this with filter_popups gone?
2854 assert(len <= csp->receive_buffer_size);
2855 csp->receive_buffer[len] = '\0';
2858 * Normally, this would indicate that we've read
2859 * as much as the server has sent us and we can
2860 * close the client connection. However, Microsoft
2861 * in its wisdom has released IIS/5 with a bug that
2862 * prevents it from sending the trailing \r\n in
2863 * a 302 redirect header (and possibly other headers).
2864 * To work around this if we've haven't parsed
2865 * a full header we'll append a trailing \r\n
2866 * and see if this now generates a valid one.
2868 * This hack shouldn't have any impacts. If we've
2869 * already transmitted the header or if this is a
2870 * SSL connection, then we won't bother with this
2871 * hack. So we only work on partially received
2872 * headers. If we append a \r\n and this still
2873 * doesn't generate a valid header, then we won't
2874 * transmit anything to the client.
2879 if (server_body || (http->ssl
2880 #ifdef FEATURE_HTTPS_INSPECTION
2886 * If we have been buffering up the document,
2887 * now is the time to apply content modification
2888 * and send the result to the client.
2890 if (buffer_and_filter_content)
2892 p = execute_content_filters(csp);
2894 * If content filtering fails, use the original
2895 * buffer and length.
2896 * (see p != NULL ? p : csp->iob->cur below)
2900 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2902 #ifdef FEATURE_COMPRESSION
2903 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2904 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2906 char *compressed_content = compress_buffer(p,
2907 (size_t *)&csp->content_length, csp->config->compression_level);
2908 if (compressed_content != NULL)
2911 p = compressed_content;
2912 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2917 if (JB_ERR_OK != update_server_headers(csp))
2919 log_error(LOG_LEVEL_FATAL,
2920 "Failed to update server headers. after filtering.");
2923 hdr = list_to_text(csp->headers);
2926 /* FIXME Should handle error properly */
2927 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2930 #ifdef FEATURE_HTTPS_INSPECTION
2932 * Sending data with standard or secured connection (HTTP/HTTPS)
2934 if (client_use_ssl(csp))
2936 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2937 (const unsigned char *)hdr, strlen(hdr)) < 0)
2938 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2939 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
2940 csp->content_length) < 0))
2942 log_error(LOG_LEVEL_ERROR, "write modified content to "
2943 "client over TLS/SSL failed");
2946 mark_server_socket_tainted(csp);
2947 close_client_and_server_ssl_connections(csp);
2952 #endif /* def FEATURE_HTTPS_INSPECTION */
2954 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2955 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
2956 (size_t)csp->content_length, write_delay))
2958 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2961 mark_server_socket_tainted(csp);
2970 break; /* "game over, man" */
2974 * This is NOT the body, so
2975 * Let's pretend the server just sent us a blank line.
2977 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
2978 len = (int)strlen(csp->receive_buffer);
2981 * Now, let the normal header parsing algorithm below do its
2982 * job. If it fails, we'll exit instead of continuing.
2989 * If we're in the body of the server document, just write it to
2990 * the client, unless we need to buffer the body for later
2991 * content-filtering.
2993 if (server_body || (http->ssl
2994 #ifdef FEATURE_HTTPS_INSPECTION
2999 if (buffer_and_filter_content)
3002 * If there is no memory left for buffering the content, or the buffer limit
3003 * has been reached, switch to non-filtering mode, i.e. make & write the
3004 * header, flush the iob and buf, and get out of the way.
3006 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3011 log_error(LOG_LEVEL_INFO,
3012 "Flushing header and buffers. Stepping back from filtering.");
3014 hdr = list_to_text(csp->headers);
3018 * Memory is too tight to even generate the header.
3019 * Send our static "Out-of-memory" page.
3021 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3022 rsp = cgi_error_memory();
3023 send_crunch_response(csp, rsp);
3024 mark_server_socket_tainted(csp);
3025 #ifdef FEATURE_HTTPS_INSPECTION
3026 close_client_and_server_ssl_connections(csp);
3030 hdrlen = strlen(hdr);
3032 #ifdef FEATURE_HTTPS_INSPECTION
3034 * Sending data with standard or secured connection (HTTP/HTTPS)
3036 if (client_use_ssl(csp))
3038 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3039 (const unsigned char *)hdr, hdrlen) < 0)
3040 || ((flushed = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3042 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3043 (const unsigned char *)csp->receive_buffer, (size_t)len) < 0))
3045 log_error(LOG_LEVEL_CONNECT,
3046 "Flush header and buffers to client failed");
3048 mark_server_socket_tainted(csp);
3049 close_client_and_server_ssl_connections(csp);
3054 #endif /* def FEATURE_HTTPS_INSPECTION */
3056 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3057 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3058 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3061 log_error(LOG_LEVEL_CONNECT,
3062 "Flush header and buffers to client failed: %E");
3064 mark_server_socket_tainted(csp);
3070 * Reset the byte_count to the amount of bytes
3071 * we just flushed. len will be added a few lines below,
3072 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3074 byte_count = (unsigned long long)flushed;
3076 buffer_and_filter_content = 0;
3082 #ifdef FEATURE_HTTPS_INSPECTION
3084 * Sending data with standard or secured connection (HTTP/HTTPS)
3086 if (client_use_ssl(csp))
3088 ret = ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3089 (const unsigned char *)csp->receive_buffer, (size_t)len);
3092 log_error(LOG_LEVEL_ERROR,
3093 "Sending data to client failed");
3094 mark_server_socket_tainted(csp);
3095 close_client_and_server_ssl_connections(csp);
3100 #endif /* def FEATURE_HTTPS_INSPECTION */
3102 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3103 (size_t)len, write_delay))
3105 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3106 mark_server_socket_tainted(csp);
3111 byte_count += (unsigned long long)len;
3117 * We're still looking for the end of the server's header.
3118 * Buffer up the data we just read. If that fails, there's
3119 * little we can do but send our static out-of-memory page.
3121 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3123 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3124 rsp = cgi_error_memory();
3125 send_crunch_response(csp, rsp);
3126 mark_server_socket_tainted(csp);
3127 #ifdef FEATURE_HTTPS_INSPECTION
3128 close_client_and_server_ssl_connections(csp);
3133 /* Convert iob into something sed() can digest */
3134 if (JB_ERR_PARSE == get_server_headers(csp))
3139 * Well, we tried our MS IIS/5 hack and it didn't work.
3140 * The header is incomplete and there isn't anything
3141 * we can do about it.
3143 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3144 "Applying the MS IIS5 hack didn't help.");
3145 log_error(LOG_LEVEL_CLF,
3146 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3147 #ifdef FEATURE_HTTPS_INSPECTION
3149 * Sending data with standard or secured connection (HTTP/HTTPS)
3151 if (client_use_ssl(csp))
3153 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3154 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3155 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3158 #endif /* def FEATURE_HTTPS_INSPECTION */
3160 write_socket_delayed(csp->cfd,
3161 INVALID_SERVER_HEADERS_RESPONSE,
3162 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3164 mark_server_socket_tainted(csp);
3165 #ifdef FEATURE_HTTPS_INSPECTION
3166 close_client_and_server_ssl_connections(csp);
3173 * Since we have to wait for more from the server before
3174 * we can parse the headers we just continue here.
3176 log_error(LOG_LEVEL_CONNECT,
3177 "Continuing buffering server headers from socket %d. "
3178 "Bytes most recently read: %d.", csp->cfd, len);
3185 * Account for the content bytes we
3186 * might have gotten with the headers.
3188 assert(csp->iob->eod >= csp->iob->cur);
3189 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3192 /* Did we actually get anything? */
3193 if (NULL == csp->headers->first)
3195 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3197 log_error(LOG_LEVEL_ERROR,
3198 "No server or forwarder response received on socket %d. "
3199 "Closing client socket %d without sending data.",
3200 csp->server_connection.sfd, csp->cfd);
3201 log_error(LOG_LEVEL_CLF,
3202 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3206 log_error(LOG_LEVEL_ERROR,
3207 "No server or forwarder response received on socket %d.",
3208 csp->server_connection.sfd);
3209 send_crunch_response(csp, error_response(csp, "no-server-data"));
3211 free_http_request(http);
3212 mark_server_socket_tainted(csp);
3213 #ifdef FEATURE_HTTPS_INSPECTION
3214 close_client_and_server_ssl_connections(csp);
3219 if (!csp->headers->first->str)
3221 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3223 assert(csp->headers->first->str);
3225 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3226 strncmpic(csp->headers->first->str, "ICY", 3))
3229 * It doesn't look like a HTTP (or Shoutcast) response:
3230 * tell the client and log the problem.
3232 if (strlen(csp->headers->first->str) > 30)
3234 csp->headers->first->str[30] = '\0';
3236 log_error(LOG_LEVEL_ERROR,
3237 "Invalid server or forwarder response. Starts with: %s",
3238 csp->headers->first->str);
3239 log_error(LOG_LEVEL_CLF,
3240 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3241 #ifdef FEATURE_HTTPS_INSPECTION
3243 * Sending data with standard or secured connection (HTTP/HTTPS)
3245 if (client_use_ssl(csp))
3247 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3248 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3249 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3252 #endif /* def FEATURE_HTTPS_INSPECTION */
3254 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3255 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3257 free_http_request(http);
3258 mark_server_socket_tainted(csp);
3259 #ifdef FEATURE_HTTPS_INSPECTION
3260 close_client_and_server_ssl_connections(csp);
3266 * We have now received the entire server header,
3267 * filter it and send the result to the client
3269 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3271 log_error(LOG_LEVEL_CLF,
3272 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3273 #ifdef FEATURE_HTTPS_INSPECTION
3275 * Sending data with standard or secured connection (HTTP/HTTPS)
3277 if (client_use_ssl(csp))
3279 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3280 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3281 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3286 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3287 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3289 free_http_request(http);
3290 mark_server_socket_tainted(csp);
3291 #ifdef FEATURE_HTTPS_INSPECTION
3292 close_client_and_server_ssl_connections(csp);
3296 hdr = list_to_text(csp->headers);
3299 /* FIXME Should handle error properly */
3300 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3303 if ((csp->flags & CSP_FLAG_CHUNKED)
3304 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3305 && ((csp->iob->eod - csp->iob->cur) >= 5)
3306 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3308 log_error(LOG_LEVEL_CONNECT,
3309 "Looks like we got the last chunk together with "
3310 "the server headers. We better stop reading.");
3311 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3312 csp->expected_content_length = byte_count;
3313 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3316 csp->server_connection.response_received = time(NULL);
3318 if (crunch_response_triggered(csp, crunchers_light))
3321 * One of the tags created by a server-header
3322 * tagger triggered a crunch. We already
3323 * delivered the crunch response to the client
3324 * and are done here after cleaning up.
3327 mark_server_socket_tainted(csp);
3328 #ifdef FEATURE_HTTPS_INSPECTION
3329 close_client_and_server_ssl_connections(csp);
3334 /* Buffer and pcrs filter this if appropriate. */
3335 buffer_and_filter_content = content_requires_filtering(csp);
3337 if (!buffer_and_filter_content)
3340 * Write the server's (modified) header to
3341 * the client (along with anything else that
3342 * may be in the buffer). Use standard or secured
3345 #ifdef FEATURE_HTTPS_INSPECTION
3346 if (client_use_ssl(csp))
3348 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3349 (const unsigned char *)hdr, strlen(hdr)) < 0)
3350 || (len = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3353 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3356 * The write failed, so don't bother mentioning it
3357 * to the client... it probably can't hear us anyway.
3360 mark_server_socket_tainted(csp);
3361 #ifdef FEATURE_HTTPS_INSPECTION
3362 close_client_and_server_ssl_connections(csp);
3368 #endif /* def FEATURE_HTTPS_INSPECTION */
3370 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3371 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3373 log_error(LOG_LEVEL_ERROR,
3374 "write header to client failed");
3376 * The write failed, so don't bother mentioning it
3377 * to the client... it probably can't hear us anyway.
3380 mark_server_socket_tainted(csp);
3386 /* we're finished with the server's header */
3392 * If this was a MS IIS/5 hack then it means the server
3393 * has already closed the connection. Nothing more to read.
3398 log_error(LOG_LEVEL_ERROR,
3399 "Closed server connection detected. "
3400 "Applying the MS IIS5 hack didn't help.");
3401 log_error(LOG_LEVEL_CLF,
3402 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3403 #ifdef FEATURE_HTTPS_INSPECTION
3405 * Sending data with standard or secured connection (HTTP/HTTPS)
3407 if (client_use_ssl(csp))
3409 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3410 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3411 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3414 #endif /* def FEATURE_HTTPS_INSPECTION */
3416 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3417 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3419 mark_server_socket_tainted(csp);
3420 #ifdef FEATURE_HTTPS_INSPECTION
3421 close_client_and_server_ssl_connections(csp);
3428 mark_server_socket_tainted(csp);
3429 #ifdef FEATURE_HTTPS_INSPECTION
3430 close_client_and_server_ssl_connections(csp);
3432 return; /* huh? we should never get here */
3434 #ifdef FEATURE_HTTPS_INSPECTION
3435 close_client_and_server_ssl_connections(csp);
3437 if (csp->content_length == 0)
3440 * If Privoxy didn't recalculate the Content-Length,
3441 * byte_count is still correct.
3443 csp->content_length = byte_count;
3446 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3447 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3448 && (csp->expected_content_length != byte_count))
3450 log_error(LOG_LEVEL_CONNECT,
3451 "Received %llu bytes while expecting %llu.",
3452 byte_count, csp->expected_content_length);
3453 mark_server_socket_tainted(csp);
3457 #ifdef FEATURE_HTTPS_INSPECTION
3458 if (client_use_ssl(csp))
3460 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
3461 csp->ip_addr_str, http->gpc, http->hostport, http->path,
3462 http->version, csp->content_length);
3467 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3468 csp->ip_addr_str, http->ocmd, csp->content_length);
3470 csp->server_connection.timestamp = time(NULL);
3474 /*********************************************************************
3478 * Description : Once a connection from the client has been accepted,
3479 * this function is called (via serve()) to handle the
3480 * main business of the communication. This function
3481 * returns after dealing with a single request. It can
3482 * be called multiple times with the same client socket
3483 * if the client is keeping the connection alive.
3485 * The decision whether or not a client connection will
3486 * be kept alive is up to the caller which also must
3487 * close the client socket when done.
3489 * FIXME: chat is nearly thousand lines long.
3493 * 1 : csp = Current client state (buffers, headers, etc...)
3495 * Returns : Nothing.
3497 *********************************************************************/
3498 static void chat(struct client_state *csp)
3500 const struct forward_spec *fwd;
3501 struct http_request *http;
3502 /* Skeleton for HTTP response, if we should intercept the request */
3503 struct http_response *rsp;
3504 #ifdef FEATURE_HTTPS_INSPECTION
3505 int use_ssl_tunnel = 0;
3510 if (receive_client_request(csp) != JB_ERR_OK)
3514 if (parse_client_request(csp) != JB_ERR_OK)
3519 /* decide how to route the HTTP request */
3520 fwd = forward_url(csp, http);
3523 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
3524 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3528 #ifdef FEATURE_HTTPS_INSPECTION
3530 * Setting flags to use old solution with SSL tunnel and to disable
3531 * certificates verification.
3533 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3538 if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3540 csp->dont_verify_certificate = 1;
3545 * build the http request to send to the server
3546 * we have to do one of the following:
3548 * create = use the original HTTP request to create a new
3549 * HTTP request that has either the path component
3550 * without the http://domainspec (w/path) or the
3551 * full orininal URL (w/url)
3552 * Note that the path and/or the HTTP version may
3553 * have been altered by now.
3555 * SSL proxy = Open a socket to the host:port of the server
3556 * and create TLS/SSL connection with server and
3557 * with client. Then behave like mediator between
3558 * client and server over TLS/SSL.
3560 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3561 * with request to a parent proxy. Note that we'll be sending
3562 * forwarding the CFAIL message ourselves if connecting to the parent
3563 * fails, but we won't send a CSUCCEED message if it works,
3564 * since that would result in a double message (ours and the
3565 * parent's). After sending the request to the parent, we
3566 * must parse answer and send it to client. If connection
3567 * with server is established, we do TLS/SSL proxy. Otherwise
3568 * we send parent response to client and close connections.
3570 * here's the matrix:
3573 * +--------+--------+
3575 * 0 | create | SSL |
3576 * | w/path | proxy |
3577 * Forwarding +--------+--------+
3579 * 1 | create | proxy |
3580 * | w/url |+forward|
3581 * +--------+--------+
3585 #ifdef FEATURE_HTTPS_INSPECTION
3587 * Presetting SSL client and server flags
3589 if (http->ssl && !use_ssl_tunnel)
3591 http->client_ssl = 1;
3592 http->server_ssl = 1;
3596 http->client_ssl = 0;
3597 http->server_ssl = 0;
3601 if (http->ssl && connect_port_is_forbidden(csp))
3603 const char *acceptable_connect_ports =
3604 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3605 assert(NULL != acceptable_connect_ports);
3606 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3607 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3608 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3609 csp->action->flags |= ACTION_BLOCK;
3611 #ifdef FEATURE_HTTPS_INSPECTION
3612 http->client_ssl = 0;
3613 http->server_ssl = 0;
3618 freez(csp->headers->first->str);
3619 build_request_line(csp, fwd, &csp->headers->first->str);
3622 * We have a request. Check if one of the crunchers wants it
3623 * unless the client wants to use TLS/SSL in which case we
3624 * haven't setup the TLS context yet and will send the crunch
3628 #ifdef FEATURE_HTTPS_INSPECTION
3629 !client_use_ssl(csp) &&
3631 crunch_response_triggered(csp, crunchers_all))
3634 * Yes. The client got the crunch response and we're done here.
3639 log_applied_actions(csp->action);
3640 #ifdef FEATURE_HTTPS_INSPECTION
3642 * Log the request unless we're https inspecting
3643 * in which case we don't have the path yet and
3644 * will log the request later.
3646 if (!client_use_ssl(csp))
3649 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
3651 if (fwd->forward_host)
3653 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3654 fwd->forward_host, fwd->forward_port, http->hostport);
3658 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3661 /* here we connect to the server, gateway, or the forwarder */
3663 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3664 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3665 && socket_is_still_alive(csp->server_connection.sfd)
3666 && connection_destination_matches(&csp->server_connection, http, fwd))
3668 log_error(LOG_LEVEL_CONNECT,
3669 "Reusing server socket %d connected to %s. Total requests: %u.",
3670 csp->server_connection.sfd, csp->server_connection.host,
3671 csp->server_connection.requests_sent_total);
3675 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3677 #ifdef FEATURE_CONNECTION_SHARING
3678 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3680 remember_connection(&csp->server_connection);
3683 #endif /* def FEATURE_CONNECTION_SHARING */
3685 log_error(LOG_LEVEL_CONNECT,
3686 "Closing server socket %d connected to %s. Total requests: %u.",
3687 csp->server_connection.sfd, csp->server_connection.host,
3688 csp->server_connection.requests_sent_total);
3689 close_socket(csp->server_connection.sfd);
3691 mark_connection_closed(&csp->server_connection);
3693 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3694 #ifdef FEATURE_HTTPS_INSPECTION
3695 if (http->ssl && !use_ssl_tunnel)
3699 * Creating an SSL proxy. If forwarding is disabled, we must send
3700 * CSUCCEED mesage to client. Then TLS/SSL connection with client
3704 if (fwd->forward_host == NULL)
3707 * We're lying to the client as the connection hasn't actually
3708 * been established yet. We don't establish the connection until
3709 * we have seen and parsed the encrypted client headers.
3711 if (write_socket_delayed(csp->cfd, CSUCCEED,
3712 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3714 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3719 ret = create_client_ssl_connection(csp);
3722 log_error(LOG_LEVEL_ERROR,
3723 "Can't open secure connection with client");
3724 close_client_ssl_connection(csp); /* XXX: Is this needed? */
3727 if (JB_ERR_OK != process_encrypted_request(csp))
3729 log_error(LOG_LEVEL_ERROR, "Failed to parse encrypted request.");
3730 close_client_ssl_connection(csp);
3734 * We have an encrypted request. Check if one of the crunchers now
3735 * wants it (for example because the previously invisible path was
3736 * required to match).
3738 if (crunch_response_triggered(csp, crunchers_all))
3741 * Yes. The client got the crunch response and we're done here.
3743 close_client_ssl_connection(csp);
3749 * Connecting to destination server
3751 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3753 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3755 if (fwd->type != SOCKS_NONE)
3758 rsp = error_response(csp, "forwarding-failed");
3760 else if (errno == EINVAL)
3762 rsp = error_response(csp, "no-such-domain");
3766 rsp = error_response(csp, "connect-failed");
3769 /* Write the answer to the client */
3772 send_crunch_response(csp, rsp);
3776 * Temporary workaround to prevent already-read client
3777 * bodies from being parsed as new requests. For now we
3778 * err on the safe side and throw all the following
3779 * requests under the bus, even if no client body has been
3780 * buffered. A compliant client will repeat the dropped
3781 * requests on an untainted connection.
3783 * The proper fix is to discard the no longer needed
3784 * client body in the buffer (if there is one) and to
3785 * continue parsing the bytes that follow.
3787 #ifdef FEATURE_HTTPS_INSPECTION
3788 close_client_ssl_connection(csp);
3790 drain_and_close_socket(csp->cfd);
3791 csp->cfd = JB_INVALID_SOCKET;
3796 #ifdef FEATURE_HTTPS_INSPECTION
3798 * Creating TLS/SSL connections with destination server or parent
3799 * proxy. If forwarding is enabled, we must send client request to
3800 * parent proxy and receive, parse and resend parent proxy answer.
3802 if (http->ssl && !use_ssl_tunnel)
3804 if (fwd->forward_host != NULL)
3806 char server_response[BUFFER_SIZE];
3809 char *hdr = list_to_text(csp->headers);
3810 memset(server_response, 0, sizeof(server_response));
3814 log_error(LOG_LEVEL_FATAL,
3815 "Out of memory parsing client header");
3817 list_remove_all(csp->headers);
3820 * Sending client's CONNECT request to the parent proxy
3822 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
3828 log_error(LOG_LEVEL_CONNECT,
3829 "Sending request headers to: %s failed", http->hostport);
3830 mark_server_socket_tainted(csp);
3831 close_client_ssl_connection(csp);
3835 /* Waiting for parent proxy server response */
3836 len = read_socket(csp->server_connection.sfd, server_response,
3837 sizeof(server_response)-1);
3841 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
3842 "server on socket %d.", csp->server_connection.sfd);
3844 rsp = error_response(csp, "no-server-data");
3847 send_crunch_response(csp, rsp);
3849 mark_server_socket_tainted(csp);
3850 close_client_ssl_connection(csp);
3855 * Test if connection with destination server was established
3856 * successfully by parent proxy. Then we can send response to
3857 * the client and continue or stop.
3859 if (!tunnel_established_successfully(server_response, (unsigned int)len))
3861 log_error(LOG_LEVEL_ERROR, "Forwarder hasn't established "
3862 "connection with destination server.");
3864 write_socket(csp->cfd, server_response, (size_t)len);
3865 mark_server_socket_tainted(csp);
3866 close_client_ssl_connection(csp);
3871 * Parent proxy has established connection with destination server.
3872 * Now we must create TLS/SSL connection with parent proxy.
3874 ret = create_server_ssl_connection(csp);
3877 * If TLS/SSL connection wasn't created and invalid certificate
3878 * wasn't detected, we can interrupt this function. Otherwise, we
3879 * must inform the client about invalid server certificate.
3882 && (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3883 || csp->server_cert_verification_result == SSL_CERT_VALID))
3885 rsp = error_response(csp, "connect-failed");
3888 send_crunch_response(csp, rsp);
3894 * TLS/SSL connection with parent proxy is established, we can
3895 * inform client about success.
3897 ret = write_socket(csp->cfd, server_response, (size_t)len);
3900 log_error(LOG_LEVEL_ERROR,
3901 "Sending parent proxy response to client failed");
3902 mark_server_socket_tainted(csp);
3903 close_client_ssl_connection(csp);
3906 }/* -END- if (fwd->forward_host != NULL) */
3910 * Parent proxy is not used, we can just create TLS/SSL connection
3911 * with destination server
3913 int ret = create_server_ssl_connection(csp);
3916 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
3917 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
3920 * If the server certificate is invalid, we must inform
3921 * the client and then close connection to the client.
3923 ssl_send_certificate_error(csp);
3924 close_client_and_server_ssl_connections(csp);
3927 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3928 || csp->server_cert_verification_result == SSL_CERT_VALID)
3931 * The TLS/SSL connection wasn't created but an invalid
3932 * certificate wasn't detected. Report it as connection
3935 rsp = error_response(csp, "connect-failed");
3938 send_crunch_response(csp, rsp);
3940 close_client_and_server_ssl_connections(csp);
3945 }/* -END- if (http->ssl) */
3946 #endif /* def FEATURE_HTTPS_INSPECTION */
3948 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3949 save_connection_destination(csp->server_connection.sfd,
3950 http, fwd, &csp->server_connection);
3951 csp->server_connection.keep_alive_timeout =
3952 (unsigned)csp->config->keep_alive_timeout;
3954 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3956 csp->server_connection.requests_sent_total++;
3958 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
3960 /* Client headers have been sent optimistically */
3961 assert(csp->headers->last == NULL);
3963 else if (http->ssl == 0 || (fwd->forward_host
3964 #ifdef FEATURE_HTTPS_INSPECTION
3969 if (send_http_request(csp))
3971 rsp = error_response(csp, "connect-failed");
3974 send_crunch_response(csp, rsp);
3982 * Using old solution with SSL tunnel or new solution with SSL proxy
3984 list_remove_all(csp->headers);
3985 #ifdef FEATURE_HTTPS_INSPECTION
3990 * We're running an SSL tunnel and we're not forwarding,
3991 * so just ditch the client headers, send the "connect succeeded"
3992 * message to the client, flush the rest, and get out of the way.
3994 if (write_socket_delayed(csp->cfd, CSUCCEED,
3995 strlen(CSUCCEED), get_write_delay(csp)))
4000 #ifdef FEATURE_HTTPS_INSPECTION
4004 * If server certificate is invalid, we must inform client and then
4005 * close connection with client.
4007 if (csp->server_cert_verification_result != SSL_CERT_VALID)
4009 ssl_send_certificate_error(csp);
4010 close_client_and_server_ssl_connections(csp);
4013 if (send_https_request(csp))
4015 rsp = error_response(csp, "connect-failed");
4018 send_crunch_response(csp, rsp);
4020 close_client_and_server_ssl_connections(csp);
4024 #endif /* def FEATURE_HTTPS_INSPECTION */
4025 clear_iob(csp->client_iob);
4026 }/* -END- else ... if (http->ssl == 1) */
4028 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4030 /* XXX: should the time start earlier for optimistically sent data? */
4031 csp->server_connection.request_sent = time(NULL);
4033 handle_established_connection(csp);
4034 freez(csp->receive_buffer);
4039 /*********************************************************************
4041 * Function : fuzz_server_response
4043 * Description : Treat the input as a whole server response.
4046 * 1 : csp = Current client state (buffers, headers, etc...)
4047 * 2 : fuzz_input_file = File to read the input from.
4051 *********************************************************************/
4052 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4054 static struct forward_spec fwd; /* Zero'd due to being static */
4057 if (strcmp(fuzz_input_file, "-") == 0)
4059 /* XXX: Doesn'T work yet. */
4060 csp->server_connection.sfd = 0;
4064 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4065 if (csp->server_connection.sfd == -1)
4067 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4072 csp->content_type |= CT_GIF;
4073 csp->action->flags |= ACTION_DEANIMATE;
4074 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4076 csp->http->path = strdup_or_die("/");
4077 csp->http->host = strdup_or_die("fuzz.example.org");
4078 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4079 /* Prevent client socket monitoring */
4080 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4081 csp->flags |= CSP_FLAG_CHUNKED;
4083 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4084 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4086 csp->content_type |= CT_DECLARED|CT_GIF;
4088 csp->config->socket_timeout = 0;
4090 cgi_init_error_messages();
4092 handle_established_connection(csp);
4093 freez(csp->receive_buffer);
4100 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4101 /*********************************************************************
4103 * Function : prepare_csp_for_next_request
4105 * Description : Put the csp in a mostly vergin state.
4108 * 1 : csp = Current client state (buffers, headers, etc...)
4112 *********************************************************************/
4113 static void prepare_csp_for_next_request(struct client_state *csp)
4115 csp->content_type = 0;
4116 csp->content_length = 0;
4117 csp->expected_content_length = 0;
4118 csp->expected_client_content_length = 0;
4119 list_remove_all(csp->headers);
4120 clear_iob(csp->iob);
4121 freez(csp->error_message);
4122 free_http_request(csp->http);
4123 destroy_list(csp->headers);
4124 destroy_list(csp->tags);
4125 #ifdef FEATURE_CLIENT_TAGS
4126 destroy_list(csp->client_tags);
4127 freez(csp->client_address);
4129 free_current_action(csp->action);
4130 if (NULL != csp->fwd)
4132 unload_forward_spec(csp->fwd);
4135 /* XXX: Store per-connection flags someplace else. */
4136 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4137 #ifdef FEATURE_TOGGLE
4138 if (global_toggle_state)
4139 #endif /* def FEATURE_TOGGLE */
4141 csp->flags |= CSP_FLAG_TOGGLED_ON;
4144 if (csp->client_iob->eod > csp->client_iob->cur)
4146 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4147 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4149 assert(bytes_to_shift > 0);
4150 assert(data_length > 0);
4152 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
4153 data_length, bytes_to_shift);
4154 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4155 csp->client_iob->cur = csp->client_iob->buf;
4156 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4157 csp->client_iob->eod = csp->client_iob->buf + data_length;
4158 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4160 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4165 * We mainly care about resetting client_iob->cur so we don't
4166 * waste buffer space at the beginning and don't mess up the
4167 * request restoration done by cgi_show_request().
4169 * Freeing the buffer itself isn't technically necessary,
4170 * but makes debugging more convenient.
4172 clear_iob(csp->client_iob);
4175 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4178 /*********************************************************************
4182 * Description : This is little more than chat. We only "serve" to
4183 * to close (or remember) any socket that chat may have
4187 * 1 : csp = Current client state (buffers, headers, etc...)
4191 *********************************************************************/
4192 static void serve(struct client_state *csp)
4194 int config_file_change_detected = 0; /* Only used for debugging */
4195 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4196 #ifdef FEATURE_CONNECTION_SHARING
4197 static int monitor_thread_running = 0;
4198 #endif /* def FEATURE_CONNECTION_SHARING */
4199 int continue_chatting = 0;
4201 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4202 csp->ip_addr_str, csp->cfd);
4206 unsigned int latency;
4211 * If the request has been crunched,
4212 * the calculated latency is zero.
4214 latency = (unsigned)(csp->server_connection.response_received -
4215 csp->server_connection.request_sent) / 2;
4217 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4218 && (csp->flags & CSP_FLAG_CRUNCHED)
4219 && (csp->expected_client_content_length != 0))
4221 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4222 log_error(LOG_LEVEL_CONNECT,
4223 "Tainting client socket %d due to unread data.", csp->cfd);
4226 continue_chatting = (csp->config->feature_flags
4227 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4228 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4229 && (csp->cfd != JB_INVALID_SOCKET)
4230 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4231 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4232 || (csp->flags & CSP_FLAG_CHUNKED));
4234 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4235 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4237 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4239 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4241 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4242 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4243 || !socket_is_still_alive(csp->server_connection.sfd)
4244 || !(latency < csp->server_connection.keep_alive_timeout))
4246 log_error(LOG_LEVEL_CONNECT,
4247 "Closing server socket %d connected to %s. "
4248 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
4249 csp->server_connection.sfd, csp->server_connection.host,
4250 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4251 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4252 socket_is_still_alive(csp->server_connection.sfd),
4253 csp->server_connection.keep_alive_timeout);
4254 #ifdef FEATURE_CONNECTION_SHARING
4255 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4257 forget_connection(csp->server_connection.sfd);
4259 #endif /* def FEATURE_CONNECTION_SHARING */
4260 close_socket(csp->server_connection.sfd);
4261 mark_connection_closed(&csp->server_connection);
4265 if (continue_chatting && any_loaded_file_changed(csp))
4267 continue_chatting = 0;
4268 config_file_change_detected = 1;
4271 if (continue_chatting)
4273 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4274 && socket_is_still_alive(csp->cfd))
4276 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4277 "pipelined on socket %d and the socket is still alive.",
4278 csp->requests_received_total+1, csp->cfd);
4279 prepare_csp_for_next_request(csp);
4283 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4285 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4287 log_error(LOG_LEVEL_CONNECT,
4288 "Waiting for the next client request on socket %d. "
4289 "Keeping the server socket %d to %s open.",
4290 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4294 log_error(LOG_LEVEL_CONNECT,
4295 "Waiting for the next client request on socket %d. "
4296 "No server socket to keep open.", csp->cfd);
4300 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4301 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4302 && socket_is_still_alive(csp->cfd))
4304 log_error(LOG_LEVEL_CONNECT,
4305 "Client request %u arrived in time on socket %d.",
4306 csp->requests_received_total+1, csp->cfd);
4307 prepare_csp_for_next_request(csp);
4311 #ifdef FEATURE_CONNECTION_SHARING
4312 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4313 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4314 && (socket_is_still_alive(csp->server_connection.sfd)))
4316 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4318 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4323 remember_connection(&csp->server_connection);
4324 csp->server_connection.sfd = JB_INVALID_SOCKET;
4325 drain_and_close_socket(csp->cfd);
4326 csp->cfd = JB_INVALID_SOCKET;
4327 privoxy_mutex_lock(&connection_reuse_mutex);
4328 if (!monitor_thread_running)
4330 monitor_thread_running = 1;
4331 privoxy_mutex_unlock(&connection_reuse_mutex);
4332 wait_for_alive_connections();
4333 privoxy_mutex_lock(&connection_reuse_mutex);
4334 monitor_thread_running = 0;
4336 privoxy_mutex_unlock(&connection_reuse_mutex);
4338 #endif /* def FEATURE_CONNECTION_SHARING */
4342 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4344 log_error(LOG_LEVEL_CONNECT,
4345 "Closing server socket %d connected to %s. Keep-alive: %u. "
4346 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4347 "Configuration file change detected: %u",
4348 csp->server_connection.sfd, csp->server_connection.host,
4349 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4350 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4351 socket_is_still_alive(csp->server_connection.sfd),
4352 csp->server_connection.keep_alive_timeout,
4353 config_file_change_detected);
4355 } while (continue_chatting);
4359 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4361 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4363 #ifdef FEATURE_CONNECTION_SHARING
4364 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4366 forget_connection(csp->server_connection.sfd);
4368 #endif /* def FEATURE_CONNECTION_SHARING */
4369 close_socket(csp->server_connection.sfd);
4372 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4373 mark_connection_closed(&csp->server_connection);
4376 if (csp->cfd != JB_INVALID_SOCKET)
4378 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4379 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4380 "Configuration file change detected: %u. Requests received: %u.",
4381 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4382 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4383 config_file_change_detected, csp->requests_received_total);
4384 drain_and_close_socket(csp->cfd);
4387 free_csp_resources(csp);
4389 csp->flags &= ~CSP_FLAG_ACTIVE;
4395 /*********************************************************************
4397 * Function : server_thread
4399 * Description : We only exist to call `serve' in a threaded environment.
4402 * 1 : data = Current client state (buffers, headers, etc...)
4404 * Returns : Always 0.
4406 *********************************************************************/
4407 static int32 server_thread(void *data)
4409 serve((struct client_state *) data);
4416 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4417 /*********************************************************************
4421 * Description : Print usage info & exit.
4423 * Parameters : Pointer to argv[0] for identifying ourselves
4427 *********************************************************************/
4428 static void usage(const char *name)
4430 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4431 "Usage: %s [--config-test] "
4434 #endif /* defined(unix) */
4437 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4438 #endif /* defined(unix) */
4439 "[--version] [configfile]\n",
4443 show_fuzz_usage(name);
4446 printf("Aborting\n");
4451 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4454 #ifdef MUTEX_LOCKS_AVAILABLE
4455 /*********************************************************************
4457 * Function : privoxy_mutex_lock
4459 * Description : Locks a mutex.
4462 * 1 : mutex = The mutex to lock.
4464 * Returns : Void. May exit in case of errors.
4466 *********************************************************************/
4467 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4469 #ifdef FEATURE_PTHREAD
4470 int err = pthread_mutex_lock(mutex);
4473 if (mutex != &log_mutex)
4475 log_error(LOG_LEVEL_FATAL,
4476 "Mutex locking failed: %s.\n", strerror(err));
4481 EnterCriticalSection(mutex);
4482 #endif /* def FEATURE_PTHREAD */
4486 /*********************************************************************
4488 * Function : privoxy_mutex_unlock
4490 * Description : Unlocks a mutex.
4493 * 1 : mutex = The mutex to unlock.
4495 * Returns : Void. May exit in case of errors.
4497 *********************************************************************/
4498 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4500 #ifdef FEATURE_PTHREAD
4501 int err = pthread_mutex_unlock(mutex);
4504 if (mutex != &log_mutex)
4506 log_error(LOG_LEVEL_FATAL,
4507 "Mutex unlocking failed: %s.\n", strerror(err));
4512 LeaveCriticalSection(mutex);
4513 #endif /* def FEATURE_PTHREAD */
4517 /*********************************************************************
4519 * Function : privoxy_mutex_init
4521 * Description : Prepares a mutex.
4524 * 1 : mutex = The mutex to initialize.
4526 * Returns : Void. May exit in case of errors.
4528 *********************************************************************/
4529 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4531 #ifdef FEATURE_PTHREAD
4532 int err = pthread_mutex_init(mutex, 0);
4535 printf("Fatal error. Mutex initialization failed: %s.\n",
4540 InitializeCriticalSection(mutex);
4541 #endif /* def FEATURE_PTHREAD */
4543 #endif /* def MUTEX_LOCKS_AVAILABLE */
4545 /*********************************************************************
4547 * Function : initialize_mutexes
4549 * Description : Prepares mutexes if mutex support is available.
4553 * Returns : Void, exits in case of errors.
4555 *********************************************************************/
4556 static void initialize_mutexes(void)
4558 #ifdef MUTEX_LOCKS_AVAILABLE
4560 * Prepare global mutex semaphores
4563 #ifdef FEATURE_HTTPS_INSPECTION
4564 privoxy_mutex_init(&certificate_mutex);
4565 privoxy_mutex_init(&rng_mutex);
4568 privoxy_mutex_init(&log_mutex);
4569 privoxy_mutex_init(&log_init_mutex);
4570 privoxy_mutex_init(&connection_reuse_mutex);
4571 #ifdef FEATURE_EXTERNAL_FILTERS
4572 privoxy_mutex_init(&external_filter_mutex);
4574 #ifdef FEATURE_CLIENT_TAGS
4575 privoxy_mutex_init(&client_tags_mutex);
4579 * XXX: The assumptions below are a bit naive
4580 * and can cause locks that aren't necessary.
4582 * For example older FreeBSD versions (< 6.x?)
4583 * have no gethostbyname_r, but gethostbyname is
4586 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4587 privoxy_mutex_init(&resolver_mutex);
4588 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4590 * XXX: should we use a single mutex for
4591 * localtime() and gmtime() as well?
4593 #ifndef HAVE_GMTIME_R
4594 privoxy_mutex_init(&gmtime_mutex);
4595 #endif /* ndef HAVE_GMTIME_R */
4597 #ifndef HAVE_LOCALTIME_R
4598 privoxy_mutex_init(&localtime_mutex);
4599 #endif /* ndef HAVE_GMTIME_R */
4601 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4602 privoxy_mutex_init(&rand_mutex);
4603 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4605 #endif /* def MUTEX_LOCKS_AVAILABLE */
4608 /*********************************************************************
4612 * Description : Load the config file and start the listen loop.
4613 * This function is a lot more *sane* with the `load_config'
4614 * and `listen_loop' functions; although it stills does
4615 * a *little* too much for my taste.
4618 * 1 : argc = Number of parameters (including $0).
4619 * 2 : argv = Array of (char *)'s to the parameters.
4621 * Returns : 1 if : can't open config file, unrecognized directive,
4622 * stats requested in multi-thread mode, can't open the
4623 * log file, can't open the jar file, listen port is invalid,
4624 * any load fails, and can't bind port.
4626 * Else main never returns, the process must be signaled
4627 * to terminate execution. Or, on Windows, use the
4628 * "File", "Exit" menu option.
4630 *********************************************************************/
4632 int real_main(int argc, char **argv)
4634 int main(int argc, char **argv)
4638 int do_config_test = 0;
4639 #ifndef HAVE_ARC4RANDOM
4640 unsigned int random_seed;
4643 struct passwd *pw = NULL;
4644 struct group *grp = NULL;
4646 char *pre_chroot_nslookup_to_load_resolver = NULL;
4649 char *fuzz_input_type = NULL;
4650 char *fuzz_input_file = NULL;
4657 #if !defined(_WIN32)
4664 /* Prepare mutexes if supported and necessary. */
4665 initialize_mutexes();
4667 /* Enable logging until further notice. */
4671 * Parse the command line arguments
4673 * XXX: simply printing usage information in case of
4674 * invalid arguments isn't particularly user friendly.
4676 while (++argc_pos < argc)
4679 /* Check to see if the service must be installed or uninstalled */
4680 if (strncmp(argv[argc_pos], "--install", 9) == 0)
4682 const char *pName = argv[argc_pos] + 9;
4685 exit((install_service(pName)) ? 0 : 1);
4687 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4689 const char *pName = argv[argc_pos] + 11;
4692 exit((uninstall_service(pName)) ? 0 : 1);
4694 else if (strcmp(argv[argc_pos], "--service") == 0)
4696 bRunAsService = TRUE;
4697 w32_set_service_cwd();
4698 atexit(w32_service_exit_notify);
4701 #endif /* defined(_WIN32) */
4704 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4706 if (strcmp(argv[argc_pos], "--help") == 0)
4711 else if (strcmp(argv[argc_pos], "--version") == 0)
4713 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4719 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4721 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4725 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4727 if (++argc_pos == argc) usage(argv[0]);
4728 pidfile = strdup_or_die(argv[argc_pos]);
4731 else if (strcmp(argv[argc_pos], "--user") == 0)
4736 if (++argc_pos == argc) usage(argv[argc_pos]);
4738 user_arg = strdup_or_die(argv[argc_pos]);
4739 group_name = strchr(user_arg, '.');
4740 if (NULL != group_name)
4742 /* Nul-terminate the user name */
4745 /* Skip the former delimiter to actually reach the group name */
4748 grp = getgrnam(group_name);
4751 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4754 pw = getpwnam(user_arg);
4757 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4763 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4765 if (++argc_pos == argc) usage(argv[0]);
4766 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4769 else if (strcmp(argv[argc_pos], "--chroot") == 0)
4773 #endif /* defined(unix) */
4775 else if (strcmp(argv[argc_pos], "--config-test") == 0)
4780 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4783 if (argc < argc_pos + 2) usage(argv[0]);
4784 fuzz_input_type = argv[argc_pos];
4786 fuzz_input_file = argv[argc_pos];
4788 else if (strcmp(argv[argc_pos], "--stfu") == 0)
4790 set_debug_level(LOG_LEVEL_STFU);
4793 else if (argc_pos + 1 != argc)
4796 * This is neither the last command line
4797 * option, nor was it recognized before,
4798 * therefore it must be invalid.
4804 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4806 configfile = argv[argc_pos];
4809 } /* -END- while (more arguments) */
4811 show_version(Argv[0]);
4814 if (*configfile != '/')
4816 char cwd[BUFFER_SIZE];
4818 size_t abs_file_size;
4820 /* make config-filename absolute here */
4821 if (NULL == getcwd(cwd, sizeof(cwd)))
4823 perror("failed to get current working directory");
4827 basedir = strdup_or_die(cwd);
4829 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4830 abs_file = malloc_or_die(abs_file_size);
4831 strlcpy(abs_file, basedir, abs_file_size);
4832 strlcat(abs_file, "/", abs_file_size);
4833 strlcat(abs_file, configfile, abs_file_size);
4834 configfile = abs_file;
4836 #endif /* defined unix */
4840 clients->next = NULL;
4842 /* XXX: factor out initialising after the next stable release. */
4847 #ifndef HAVE_ARC4RANDOM
4848 random_seed = (unsigned int)time(NULL);
4850 srandom(random_seed);
4853 #endif /* ifdef HAVE_RANDOM */
4854 #endif /* ifndef HAVE_ARC4RANDOM */
4857 * Unix signal handling
4859 * Catch the abort, interrupt and terminate signals for a graceful exit
4860 * Catch the hangup signal so the errlog can be reopened.
4862 * Ignore the broken pipe signal as connection failures
4863 * are handled when and where they occur without relying
4866 #if !defined(_WIN32) && !defined(__OS2__)
4869 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
4871 for (idx = 0; idx < SZ(catched_signals); idx++)
4873 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
4874 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
4876 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
4877 #endif /* ifdef sun */
4879 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
4883 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4885 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
4889 #else /* ifdef _WIN32 */
4890 # ifdef _WIN_CONSOLE
4892 * We *are* in a windows console app.
4893 * Print a verbose messages about FAQ's and such
4895 printf("%s", win32_blurb);
4896 # endif /* def _WIN_CONSOLE */
4897 #endif /* def _WIN32 */
4900 if (fuzz_input_type != NULL)
4902 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
4904 log_error(LOG_LEVEL_FATAL,
4905 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
4906 "Various data structures are static which is unsafe when using threads.");
4911 exit(NULL == load_config());
4914 /* Initialize the CGI subsystem */
4915 cgi_init_error_messages();
4918 * If running on unix and without the --no-daemon
4919 * option, become a daemon. I.e. fork, detach
4920 * from tty and get process group leadership
4929 if (pid < 0) /* error */
4934 else if (pid != 0) /* parent */
4939 * must check for errors
4940 * child died due to missing files aso
4943 wpid = waitpid(pid, &status, WNOHANG);
4955 * stderr (fd 2) will be closed later on,
4956 * when the config file has been parsed.
4962 * Reserve fd 0 and 1 to prevent abort() and friends
4963 * from sending stuff to the clients or servers.
4965 fd = open("/dev/null", O_RDONLY);
4968 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4972 if (dup2(fd, 0) == -1)
4974 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
4978 fd = open("/dev/null", O_WRONLY);
4981 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4985 if (dup2(fd, 1) == -1)
4987 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
4992 #ifdef FEATURE_EXTERNAL_FILTERS
4993 for (fd = 0; fd < 3; fd++)
4995 mark_socket_for_close_on_execute(fd);
5001 } /* -END- if (daemon_mode) */
5004 * As soon as we have written the PID file, we can switch
5005 * to the user and group ID indicated by the --user option
5007 if (pidfile != NULL)
5009 write_pid_file(pidfile);
5013 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5015 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5019 if (setgroups(1, &grp->gr_gid))
5021 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5024 else if (initgroups(pw->pw_name, pw->pw_gid))
5026 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5032 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5034 /* Read the time zone file from /etc before doing chroot. */
5036 if (NULL != pre_chroot_nslookup_to_load_resolver
5037 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5039 /* Initialize resolver library. */
5040 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5042 if (chroot(pw->pw_dir) < 0)
5044 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5048 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5051 if (setuid(pw->pw_uid))
5053 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5057 char putenv_dummy[64];
5059 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5060 if (putenv(putenv_dummy) != 0)
5062 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5065 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5066 if (putenv(putenv_dummy) != 0)
5068 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5074 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5077 #endif /* defined unix */
5080 /* This will be FALSE unless the command line specified --service
5084 /* Yup, so now we must attempt to establish a connection
5085 * with the service dispatcher. This will only work if this
5086 * process was launched by the service control manager to
5087 * actually run as a service. If this isn't the case, i've
5088 * known it take around 30 seconds or so for the call to return.
5091 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5092 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5094 /* Service has run, and at this point is now being stopped, so just return */
5099 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5101 /* An error occurred. Usually it's because --service was wrongly specified
5102 * and we were unable to connect to the Service Control Dispatcher because
5103 * it wasn't expecting us and is therefore not listening.
5105 * For now, just continue below to call the listen_loop function.
5108 #endif /* def _WIN32 */
5118 /*********************************************************************
5120 * Function : bind_port_helper
5122 * Description : Bind the listen port. Handles logging, and aborts
5126 * 1 : haddr = Host address to bind to. Use NULL to bind to
5128 * 2 : hport = Specifies port to bind to.
5129 * 3 : backlog = Listen backlog.
5131 * Returns : Port that was opened.
5133 *********************************************************************/
5134 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5139 result = bind_port(haddr, hport, backlog, &bfd);
5143 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5147 log_error(LOG_LEVEL_FATAL,
5148 "can't bind to %s:%d: There may be another Privoxy "
5149 "or some other proxy running on port %d",
5150 bind_address, hport, hport);
5153 log_error(LOG_LEVEL_FATAL,
5154 "can't bind to %s:%d: The hostname is not resolvable",
5155 bind_address, hport);
5158 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5159 bind_address, hport);
5162 /* shouldn't get here */
5163 return JB_INVALID_SOCKET;
5168 if (bfd >= FD_SETSIZE)
5170 log_error(LOG_LEVEL_FATAL,
5171 "Bind socket number too high to use select(): %d >= %d",
5179 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5184 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5192 /*********************************************************************
5194 * Function : bind_ports_helper
5196 * Description : Bind the listen ports. Handles logging, and aborts
5200 * 1 : config = Privoxy configuration. Specifies ports
5202 * 2 : sockets = Preallocated array of opened sockets
5203 * corresponding to specification in config.
5204 * All non-opened sockets will be set to
5205 * JB_INVALID_SOCKET.
5207 * Returns : Nothing. Inspect sockets argument.
5209 *********************************************************************/
5210 static void bind_ports_helper(struct configuration_spec * config,
5211 jb_socket sockets[])
5215 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5217 if (config->hport[i])
5219 sockets[i] = bind_port_helper(config->haddr[i],
5220 config->hport[i], config->listen_backlog);
5221 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5222 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5224 struct accept_filter_arg af_options;
5225 bzero(&af_options, sizeof(af_options));
5226 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5227 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5228 sizeof(af_options)))
5230 log_error(LOG_LEVEL_ERROR,
5231 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5238 sockets[i] = JB_INVALID_SOCKET;
5241 config->need_bind = 0;
5245 /*********************************************************************
5247 * Function : close_ports_helper
5249 * Description : Close listenings ports.
5252 * 1 : sockets = Array of opened and non-opened sockets to
5253 * close. All sockets will be set to
5254 * JB_INVALID_SOCKET.
5256 * Returns : Nothing.
5258 *********************************************************************/
5259 static void close_ports_helper(jb_socket sockets[])
5263 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5265 if (JB_INVALID_SOCKET != sockets[i])
5267 close_socket(sockets[i]);
5269 sockets[i] = JB_INVALID_SOCKET;
5275 /* Without this simple workaround we get this compiler warning from _beginthread
5276 * warning C4028: formal parameter 1 different from declaration
5278 void w32_service_listen_loop(void *p)
5282 #endif /* def _WIN32 */
5285 /*********************************************************************
5287 * Function : listen_loop
5289 * Description : bind the listen port and enter a "FOREVER" listening loop.
5295 *********************************************************************/
5296 static void listen_loop(void)
5298 struct client_states *csp_list = NULL;
5299 struct client_state *csp = NULL;
5300 jb_socket bfds[MAX_LISTENING_SOCKETS];
5301 struct configuration_spec *config;
5302 unsigned int active_threads = 0;
5303 #if defined(FEATURE_PTHREAD)
5304 pthread_attr_t attrs;
5306 pthread_attr_init(&attrs);
5307 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5310 config = load_config();
5312 #ifdef FEATURE_CONNECTION_SHARING
5314 * XXX: Should be relocated once it no
5315 * longer needs to emit log messages.
5317 initialize_reusable_connections();
5318 #endif /* def FEATURE_CONNECTION_SHARING */
5320 bind_ports_helper(config, bfds);
5322 #ifdef FEATURE_GRACEFUL_TERMINATION
5323 while (!g_terminate)
5328 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
5329 while (waitpid(-1, NULL, WNOHANG) > 0)
5331 /* zombie children */
5333 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5336 * Free data that was used by died threads
5338 active_threads = sweep();
5342 * Re-open the errlog after HUP signal
5344 if (received_hup_signal)
5346 if (NULL != config->logfile)
5348 init_error_log(Argv[0], config->logfile);
5350 received_hup_signal = 0;
5354 csp_list = zalloc_or_die(sizeof(*csp_list));
5355 csp = &csp_list->csp;
5357 log_error(LOG_LEVEL_CONNECT,
5358 "Waiting for the next client connection. Currently active threads: %d",
5362 * This config may be outdated, but for accept_connection()
5363 * it's fresh enough.
5365 csp->config = config;
5367 if (!accept_connection(csp, bfds))
5369 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5374 csp->flags |= CSP_FLAG_ACTIVE;
5375 csp->server_connection.sfd = JB_INVALID_SOCKET;
5377 csp->config = config = load_config();
5379 if (config->need_bind)
5382 * Since we were listening to the "old port", we will not see
5383 * a "listen" param change until the next request. So, at
5384 * least 1 more request must be made for us to find the new
5385 * setting. I am simply closing the old socket and binding the
5388 * Which-ever is correct, we will serve 1 more page via the
5389 * old settings. This should probably be a "show-status"
5390 * request. This should not be a so common of an operation
5391 * that this will hurt people's feelings.
5394 close_ports_helper(bfds);
5396 bind_ports_helper(config, bfds);
5399 #ifdef FEATURE_TOGGLE
5400 if (global_toggle_state)
5401 #endif /* def FEATURE_TOGGLE */
5403 csp->flags |= CSP_FLAG_TOGGLED_ON;
5406 if (run_loader(csp))
5408 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5409 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5413 if (block_acl(NULL,csp))
5415 log_error(LOG_LEVEL_CONNECT,
5416 "Connection from %s on %s (socket %d) dropped due to ACL",
5417 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5418 close_socket(csp->cfd);
5419 freez(csp->ip_addr_str);
5420 freez(csp->listen_addr_str);
5424 #endif /* def FEATURE_ACL */
5426 if ((0 != config->max_client_connections)
5427 && (active_threads >= config->max_client_connections))
5429 log_error(LOG_LEVEL_CONNECT,
5430 "Rejecting connection from %s. Maximum number of connections reached.",
5432 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5433 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5434 close_socket(csp->cfd);
5435 freez(csp->ip_addr_str);
5436 freez(csp->listen_addr_str);
5441 /* add it to the list of clients */
5442 csp_list->next = clients->next;
5443 clients->next = csp_list;
5445 if (config->multi_threaded)
5449 /* this is a switch () statement in the C preprocessor - ugh */
5450 #undef SELECTED_ONE_OPTION
5452 /* Use Pthreads in preference to native code */
5453 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5454 #define SELECTED_ONE_OPTION
5456 pthread_t the_thread;
5458 errno = pthread_create(&the_thread, &attrs,
5459 (void * (*)(void *))serve, csp);
5460 child_id = errno ? -1 : 0;
5464 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5465 #define SELECTED_ONE_OPTION
5466 child_id = _beginthread(
5467 (void (*)(void *))serve,
5472 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
5473 #define SELECTED_ONE_OPTION
5474 child_id = _beginthread(
5475 (void(* _Optlink)(void*))serve,
5481 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5482 #define SELECTED_ONE_OPTION
5484 thread_id tid = spawn_thread
5485 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5487 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5489 child_id = (int) tid;
5498 #if !defined(SELECTED_ONE_OPTION)
5501 /* This block is only needed when using fork().
5502 * When using threads, the server thread was
5503 * created and run by the call to _beginthread().
5505 if (child_id == 0) /* child */
5508 #ifdef FEATURE_TOGGLE
5509 int inherited_toggle_state = global_toggle_state;
5510 #endif /* def FEATURE_TOGGLE */
5515 * If we've been toggled or we've blocked the request, tell Mom
5518 #ifdef FEATURE_TOGGLE
5519 if (inherited_toggle_state != global_toggle_state)
5521 rc |= RC_FLAG_TOGGLED;
5523 #endif /* def FEATURE_TOGGLE */
5525 #ifdef FEATURE_STATISTICS
5526 if (csp->flags & CSP_FLAG_REJECTED)
5528 rc |= RC_FLAG_BLOCKED;
5530 #endif /* ndef FEATURE_STATISTICS */
5534 else if (child_id > 0) /* parent */
5536 /* in a fork()'d environment, the parent's
5537 * copy of the client socket and the CSP
5541 #if !defined(_WIN32) && !defined(__CYGWIN__)
5543 wait(&child_status);
5546 * Evaluate child's return code: If the child has
5547 * - been toggled, toggle ourselves
5548 * - blocked its request, bump up the stats counter
5551 #ifdef FEATURE_TOGGLE
5552 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5554 global_toggle_state = !global_toggle_state;
5556 #endif /* def FEATURE_TOGGLE */
5558 #ifdef FEATURE_STATISTICS
5560 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5564 #endif /* def FEATURE_STATISTICS */
5566 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5567 close_socket(csp->cfd);
5568 csp->flags &= ~CSP_FLAG_ACTIVE;
5572 #undef SELECTED_ONE_OPTION
5573 /* end of cpp switch () */
5578 * Spawning the child failed, assume it's because
5579 * there are too many children running already.
5580 * XXX: If you assume ...
5582 log_error(LOG_LEVEL_ERROR,
5583 "Unable to take any additional connections: %E. Active threads: %d",
5585 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5586 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5587 close_socket(csp->cfd);
5588 csp->flags &= ~CSP_FLAG_ACTIVE;
5597 #if defined(FEATURE_PTHREAD)
5598 pthread_attr_destroy(&attrs);
5601 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5603 #ifdef FEATURE_HTTPS_INSPECTION
5604 /* Clean up. Aim: free all memory (no leaks) */
5605 if (rng_seeded == 1)
5607 mbedtls_ctr_drbg_free(&ctr_drbg);
5608 mbedtls_entropy_free(&entropy);
5612 #ifdef FEATURE_GRACEFUL_TERMINATION
5614 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
5616 unload_current_config_file();
5617 unload_current_actions_file();
5618 unload_current_re_filterfile();
5619 #ifdef FEATURE_TRUST
5620 unload_current_trust_file();
5623 if (config->multi_threaded)
5630 } while ((clients->next != NULL) && (--i > 0));
5634 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5644 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5645 /* Cleanup - remove taskbar icon etc. */
5650 #endif /* FEATURE_GRACEFUL_TERMINATION */