1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
5 * Purpose : Main file. Contains main() method, main loop, and
6 * the main connection-handling function.
8 * Copyright : Written by and Copyright (C) 2001-2020 the
9 * Privoxy team. https://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
102 #endif /* def __GLIBC__ */
107 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
108 #endif /* HAVE_POLL */
115 #ifdef FEATURE_HTTPS_INSPECTION
121 #include "miscutil.h"
123 #include "jbsockets.h"
128 #include "urlmatch.h"
129 #ifdef FEATURE_CLIENT_TAGS
130 #include "client-tags.h"
134 struct client_states clients[1];
135 struct file_list files[1];
137 #ifdef FEATURE_STATISTICS
138 int urls_read = 0; /* total nr of urls read inc rejected */
139 int urls_rejected = 0; /* total nr of urls rejected */
140 #endif /* def FEATURE_STATISTICS */
142 #ifdef FEATURE_GRACEFUL_TERMINATION
146 #if !defined(_WIN32) && !defined(__OS2__)
147 static void sig_handler(int the_signal);
149 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
150 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
151 static jb_err get_server_headers(struct client_state *csp);
152 static const char *crunch_reason(const struct http_response *rsp);
153 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
154 static char *get_request_line(struct client_state *csp);
155 static jb_err receive_client_request(struct client_state *csp);
156 static jb_err parse_client_request(struct client_state *csp);
157 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
158 static jb_err change_request_destination(struct client_state *csp);
159 static void chat(struct client_state *csp);
160 static void serve(struct client_state *csp);
161 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
162 static void usage(const char *myname);
164 static void initialize_mutexes(void);
165 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
166 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
167 static void close_ports_helper(jb_socket sockets[]);
168 static void listen_loop(void);
169 static void serve(struct client_state *csp);
172 static int32 server_thread(void *data);
173 #endif /* def __BEOS__ */
176 #define sleep(N) Sleep(((N) * 1000))
180 #define sleep(N) DosSleep(((N) * 100))
184 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
185 void show_fuzz_usage(const char *name);
188 #ifdef MUTEX_LOCKS_AVAILABLE
190 * XXX: Does the locking stuff really belong in this file?
192 privoxy_mutex_t log_mutex;
193 privoxy_mutex_t log_init_mutex;
194 privoxy_mutex_t connection_reuse_mutex;
196 #ifdef 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(const 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);
484 write_socket_delayed(csp->cfd, response, strlen(response),
485 get_write_delay(csp));
494 /*********************************************************************
496 * Function : client_has_unsupported_expectations
498 * Description : Checks if the client used an unsupported expectation
499 * in which case an error message is delivered.
502 * 1 : csp = Current client state (buffers, headers, etc...)
504 * Returns : TRUE if an error response has been generated, or
505 * FALSE if the request doesn't look invalid.
507 *********************************************************************/
508 static int client_has_unsupported_expectations(const struct client_state *csp)
510 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
512 log_error(LOG_LEVEL_ERROR,
513 "Rejecting request from client %s with unsupported Expect header value",
515 log_error(LOG_LEVEL_CLF,
516 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
517 write_socket_delayed(csp->cfd,
518 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
519 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
520 get_write_delay(csp));
530 /*********************************************************************
532 * Function : get_request_destination_elsewhere
534 * Description : If the client's request was redirected into
535 * Privoxy without the client's knowledge,
536 * the request line lacks the destination host.
538 * This function tries to get it elsewhere,
539 * provided accept-intercepted-requests is enabled.
541 * "Elsewhere" currently only means "Host: header",
542 * but in the future we may ask the redirecting
543 * packet filter to look the destination up.
545 * If the destination stays unknown, an error
546 * response is send to the client and headers
547 * are freed so that chat() can return directly.
550 * 1 : csp = Current client state (buffers, headers, etc...)
551 * 2 : headers = a header list
553 * Returns : JB_ERR_OK if the destination is now known, or
554 * JB_ERR_PARSE if it isn't.
556 *********************************************************************/
557 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
561 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
563 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
564 " Privoxy isn't configured to accept intercepted requests.",
565 csp->ip_addr_str, csp->http->cmd);
566 /* XXX: Use correct size */
567 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
568 csp->ip_addr_str, csp->http->cmd);
570 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
571 get_write_delay(csp));
572 destroy_list(headers);
576 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
578 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
579 /* Split the domain we just got for pattern matching */
580 init_domain_components(csp->http);
587 /* We can't work without destination. Go spread the news.*/
589 req = list_to_text(headers);
591 /* XXX: Use correct size */
592 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
593 csp->ip_addr_str, csp->http->cmd);
594 log_error(LOG_LEVEL_ERROR,
595 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
596 csp->ip_addr_str, csp->http->cmd, req);
599 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
600 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
601 destroy_list(headers);
606 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
607 * to get the destination IP address, use it as host directly
608 * or do a reverse DNS lookup first.
613 /*********************************************************************
615 * Function : get_server_headers
617 * Description : Parses server headers in iob and fills them
618 * into csp->headers so that they can later be
622 * 1 : csp = Current client state (buffers, headers, etc...)
624 * Returns : JB_ERR_OK if everything went fine, or
625 * JB_ERR_PARSE if the headers were incomplete.
627 *********************************************************************/
628 static jb_err get_server_headers(struct client_state *csp)
630 int continue_hack_in_da_house = 0;
633 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
638 * continue hack in da house. Ignore the ending of
639 * this head and continue enlisting header lines.
640 * The reason is described below.
642 enlist(csp->headers, "");
643 continue_hack_in_da_house = 0;
646 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
649 * It's a bodyless continue response, don't
650 * stop header parsing after reaching its end.
652 * As a result Privoxy will concatenate the
653 * next response's head and parse and deliver
654 * the headers as if they belonged to one request.
656 * The client will separate them because of the
657 * empty line between them.
659 * XXX: What we're doing here is clearly against
660 * the intended purpose of the continue header,
661 * and under some conditions (HTTP/1.0 client request)
662 * it's a standard violation.
664 * Anyway, "sort of against the spec" is preferable
665 * to "always getting confused by Continue responses"
666 * (Privoxy's behaviour before this hack was added)
668 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
669 continue_hack_in_da_house = 1;
671 else if (*header == '\0')
674 * If the header is empty, but the Continue hack
675 * isn't active, we can assume that we reached the
676 * end of the buffer before we hit the end of the
679 * Inform the caller an let it decide how to handle it.
684 if (JB_ERR_MEMORY == enlist(csp->headers, header))
687 * XXX: Should we quit the request and return a
688 * out of memory error page instead?
690 log_error(LOG_LEVEL_ERROR,
691 "Out of memory while enlisting server headers. %s lost.",
701 /*********************************************************************
703 * Function : crunch_reason
705 * Description : Translates the crunch reason code into a string.
708 * 1 : rsp = a http_response
710 * Returns : A string with the crunch reason or an error description.
712 *********************************************************************/
713 static const char *crunch_reason(const struct http_response *rsp)
715 char * reason = NULL;
720 return "Internal error while searching for crunch reason";
723 switch (rsp->crunch_reason)
726 reason = "Unsupported HTTP feature";
732 reason = "Untrusted";
735 reason = "Redirected";
741 reason = "DNS failure";
743 case FORWARDING_FAILED:
744 reason = "Forwarding failed";
747 reason = "Connection failure";
750 reason = "Out of memory (may mask other reasons)";
752 case CONNECTION_TIMEOUT:
753 reason = "Connection timeout";
756 reason = "No server data received";
759 reason = "No reason recorded";
767 /*********************************************************************
769 * Function : log_applied_actions
771 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
775 * 1 : actions = Current action spec to log
779 *********************************************************************/
780 static void log_applied_actions(const struct current_action_spec *actions)
783 * The conversion to text requires lots of memory allocations so
784 * we only do the conversion if the user is actually interested.
786 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
788 char *actions_as_text = actions_to_line_of_text(actions);
789 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
790 freez(actions_as_text);
795 /*********************************************************************
797 * Function : send_crunch_response
799 * Description : Delivers already prepared response for
800 * intercepted requests, logs the interception
801 * and frees the response.
804 * 1 : csp = Current client state (buffers, headers, etc...)
805 * 2 : rsp = Fully prepared response. Will be freed on exit.
809 *********************************************************************/
810 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
812 const struct http_request *http = csp->http;
816 assert(rsp->head != NULL);
820 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
824 * Extract the status code from the actual head
825 * that will be send to the client. It is the only
826 * way to get it right for all requests, including
827 * the fixed ones for out-of-memory problems.
829 * A head starts like this: 'HTTP/1.1 200...'
833 status_code[0] = rsp->head[9];
834 status_code[1] = rsp->head[10];
835 status_code[2] = rsp->head[11];
836 status_code[3] = '\0';
838 /* Log that the request was crunched and why. */
839 log_applied_actions(csp->action);
840 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
841 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
842 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
844 /* Write the answer to the client */
845 #ifdef FEATURE_HTTPS_INSPECTION
846 if (client_use_ssl(csp))
848 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
849 (const unsigned char *)rsp->head, rsp->head_length) < 0)
850 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
851 (const unsigned char *)rsp->body, rsp->content_length) < 0))
853 /* There is nothing we can do about it. */
854 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
855 "for %s through client socket %d using TLS/SSL",
856 http->url, csp->cfd);
862 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
863 get_write_delay(csp))
864 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
865 get_write_delay(csp)))
867 /* There is nothing we can do about it. */
868 log_error(LOG_LEVEL_CONNECT,
869 "Couldn't deliver the error message for %s through client socket %d: %E",
870 http->url, csp->cfd);
874 /* Clean up and return */
875 if (cgi_error_memory() != rsp)
877 free_http_response(rsp);
883 /*********************************************************************
885 * Function : crunch_response_triggered
887 * Description : Checks if the request has to be crunched,
888 * and delivers the crunch response if necessary.
891 * 1 : csp = Current client state (buffers, headers, etc...)
892 * 2 : crunchers = list of cruncher functions to run
894 * Returns : TRUE if the request was answered with a crunch response
897 *********************************************************************/
898 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
900 struct http_response *rsp = NULL;
901 const struct cruncher *c;
904 * If CGI request crunching is disabled,
905 * check the CGI dispatcher out of order to
906 * prevent unintentional blocks or redirects.
908 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
909 && (NULL != (rsp = dispatch_cgi(csp))))
911 /* Deliver, log and free the interception response. */
912 send_crunch_response(csp, rsp);
913 csp->flags |= CSP_FLAG_CRUNCHED;
917 for (c = crunchers; c->cruncher != NULL; c++)
920 * Check the cruncher if either Privoxy is toggled
921 * on and the request isn't forced, or if the cruncher
922 * applies to forced requests as well.
924 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
925 !(csp->flags & CSP_FLAG_FORCED)) ||
926 (c->flags & CF_IGNORE_FORCE))
928 rsp = c->cruncher(csp);
931 /* Deliver, log and free the interception response. */
932 send_crunch_response(csp, rsp);
933 csp->flags |= CSP_FLAG_CRUNCHED;
934 #ifdef FEATURE_STATISTICS
935 if (c->flags & CF_COUNT_AS_REJECT)
937 csp->flags |= CSP_FLAG_REJECTED;
939 #endif /* def FEATURE_STATISTICS */
950 /*********************************************************************
952 * Function : build_request_line
954 * Description : Builds the HTTP request line.
956 * If a HTTP forwarder is used it expects the whole URL,
957 * web servers only get the path.
960 * 1 : csp = Current client state (buffers, headers, etc...)
961 * 2 : fwd = The forwarding spec used for the request
962 * XXX: Should use http->fwd instead.
963 * 3 : request_line = The old request line which will be replaced.
965 * Returns : Nothing. Terminates in case of memory problems.
967 *********************************************************************/
968 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
970 struct http_request *http = csp->http;
973 * Downgrade http version from 1.1 to 1.0
974 * if +downgrade action applies.
976 if ((csp->action->flags & ACTION_DOWNGRADE)
977 && (!strcmpic(http->ver, "HTTP/1.1")))
980 http->ver = strdup_or_die("HTTP/1.0");
984 * Rebuild the request line.
986 freez(*request_line);
987 *request_line = strdup(http->gpc);
988 string_append(request_line, " ");
990 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
992 string_append(request_line, http->url);
996 string_append(request_line, http->path);
998 string_append(request_line, " ");
999 string_append(request_line, http->ver);
1001 if (*request_line == NULL)
1003 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1005 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1009 /*********************************************************************
1011 * Function : change_request_destination
1013 * Description : Parse a (rewritten) request line and regenerate
1014 * the http request data.
1017 * 1 : csp = Current client state (buffers, headers, etc...)
1019 * Returns : Forwards the parse_http_request() return code.
1020 * Terminates in case of memory problems.
1022 *********************************************************************/
1023 static jb_err change_request_destination(struct client_state *csp)
1025 struct http_request *http = csp->http;
1028 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1029 csp->headers->first->str);
1030 free_http_request(http);
1031 err = parse_http_request(csp->headers->first->str, http);
1032 if (JB_ERR_OK != err)
1034 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1035 jb_err_to_string(err));
1042 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1043 /*********************************************************************
1045 * Function : server_response_is_complete
1047 * Description : Determines whether we should stop reading
1048 * from the server socket.
1051 * 1 : csp = Current client state (buffers, headers, etc...)
1052 * 2 : content_length = Length of content received so far.
1054 * Returns : TRUE if the response is complete,
1057 *********************************************************************/
1058 static int server_response_is_complete(struct client_state *csp,
1059 unsigned long long content_length)
1061 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1063 if (!strcmpic(csp->http->gpc, "HEAD"))
1066 * "HEAD" implies no body, we are thus expecting
1067 * no content. XXX: incomplete "list" of methods?
1069 csp->expected_content_length = 0;
1070 content_length_known = TRUE;
1071 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1074 if (csp->http->status == 204 || csp->http->status == 304)
1077 * Expect no body. XXX: incomplete "list" of status codes?
1079 csp->expected_content_length = 0;
1080 content_length_known = TRUE;
1081 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1084 return (content_length_known && ((0 == csp->expected_content_length)
1085 || (csp->expected_content_length <= content_length)));
1089 #ifdef FEATURE_CONNECTION_SHARING
1090 /*********************************************************************
1092 * Function : wait_for_alive_connections
1094 * Description : Waits for alive connections to timeout.
1100 *********************************************************************/
1101 static void wait_for_alive_connections(void)
1103 int connections_alive = close_unusable_connections();
1105 while (0 < connections_alive)
1107 log_error(LOG_LEVEL_CONNECT,
1108 "Waiting for %d connections to timeout.",
1111 connections_alive = close_unusable_connections();
1114 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1117 #endif /* def FEATURE_CONNECTION_SHARING */
1120 /*********************************************************************
1122 * Function : save_connection_destination
1124 * Description : Remembers a connection for reuse later on.
1127 * 1 : sfd = Open socket to remember.
1128 * 2 : http = The destination for the connection.
1129 * 3 : fwd = The forwarder settings used.
1130 * 4 : server_connection = storage.
1134 *********************************************************************/
1135 void save_connection_destination(jb_socket sfd,
1136 const struct http_request *http,
1137 const struct forward_spec *fwd,
1138 struct reusable_connection *server_connection)
1140 assert(sfd != JB_INVALID_SOCKET);
1141 assert(NULL != http->host);
1143 server_connection->sfd = sfd;
1144 server_connection->host = strdup_or_die(http->host);
1145 server_connection->port = http->port;
1147 assert(NULL != fwd);
1148 assert(server_connection->gateway_host == NULL);
1149 assert(server_connection->gateway_port == 0);
1150 assert(server_connection->forwarder_type == 0);
1151 assert(server_connection->forward_host == NULL);
1152 assert(server_connection->forward_port == 0);
1154 server_connection->forwarder_type = fwd->type;
1155 if (NULL != fwd->gateway_host)
1157 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1161 server_connection->gateway_host = NULL;
1163 server_connection->gateway_port = fwd->gateway_port;
1165 if (NULL != fwd->forward_host)
1167 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1171 server_connection->forward_host = NULL;
1173 server_connection->forward_port = fwd->forward_port;
1177 /*********************************************************************
1179 * Function : verify_request_length
1181 * Description : Checks if we already got the whole client requests
1182 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1185 * Data that doesn't belong to the current request is
1186 * either thrown away to let the client retry on a clean
1187 * socket, or stashed to be dealt with after the current
1188 * request is served.
1191 * 1 : csp = Current client state (buffers, headers, etc...)
1195 *********************************************************************/
1196 static void verify_request_length(struct client_state *csp)
1198 unsigned long long buffered_request_bytes =
1199 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1201 if ((csp->expected_client_content_length != 0)
1202 && (buffered_request_bytes != 0))
1204 if (csp->expected_client_content_length >= buffered_request_bytes)
1206 csp->expected_client_content_length -= buffered_request_bytes;
1207 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1208 "to account for the %llu ones we already got.",
1209 csp->expected_client_content_length, buffered_request_bytes);
1213 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1214 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1215 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1216 "Marking the server socket tainted after throwing %llu bytes away.",
1217 buffered_request_bytes - csp->expected_client_content_length);
1218 csp->expected_client_content_length = 0;
1219 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1222 if (csp->expected_client_content_length == 0)
1224 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1228 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1229 && ((csp->client_iob->cur < csp->client_iob->eod)
1230 || (csp->expected_client_content_length != 0)))
1232 if (strcmpic(csp->http->gpc, "GET")
1233 && strcmpic(csp->http->gpc, "HEAD")
1234 && strcmpic(csp->http->gpc, "TRACE")
1235 && strcmpic(csp->http->gpc, "OPTIONS")
1236 && strcmpic(csp->http->gpc, "DELETE"))
1238 /* XXX: this is an incomplete hack */
1239 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1240 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1244 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1246 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1248 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1249 log_error(LOG_LEVEL_CONNECT,
1250 "Possible pipeline attempt detected. The connection will not "
1251 "be kept alive and we will only serve the first request.");
1252 /* Nuke the pipelined requests from orbit, just to be sure. */
1253 clear_iob(csp->client_iob);
1258 * Keep the pipelined data around for now, we'll deal with
1259 * it once we're done serving the current request.
1261 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1262 assert(csp->client_iob->eod >= csp->client_iob->cur);
1263 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1264 "%d bytes of pipelined data received.",
1265 (int)(csp->client_iob->eod - csp->client_iob->cur));
1271 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1272 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1275 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1278 /*********************************************************************
1280 * Function : mark_server_socket_tainted
1282 * Description : Makes sure we don't reuse a server socket
1283 * (if we didn't read everything the server sent
1284 * us reusing the socket would lead to garbage).
1287 * 1 : csp = Current client state (buffers, headers, etc...)
1291 *********************************************************************/
1292 static void mark_server_socket_tainted(struct client_state *csp)
1295 * For consistency we always mark the server socket
1296 * tainted, however, to reduce the log noise we only
1297 * emit a log message if the server socket could have
1298 * actually been reused.
1300 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1301 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1303 log_error(LOG_LEVEL_CONNECT,
1304 "Marking the server socket %d tainted.",
1305 csp->server_connection.sfd);
1307 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1310 /*********************************************************************
1312 * Function : get_request_line
1314 * Description : Read the client request line.
1317 * 1 : csp = Current client state (buffers, headers, etc...)
1319 * Returns : Pointer to request line or NULL in case of errors.
1321 *********************************************************************/
1322 static char *get_request_line(struct client_state *csp)
1324 char buf[BUFFER_SIZE];
1325 char *request_line = NULL;
1328 memset(buf, 0, sizeof(buf));
1330 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1333 * If there are multiple pipelined requests waiting,
1334 * the flag will be set again once the next request
1337 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1339 request_line = get_header(csp->client_iob);
1340 if ((NULL != request_line) && ('\0' != *request_line))
1342 return request_line;
1346 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1347 "received yet. Continuing reading from %d.", csp->cfd);
1355 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1357 !data_is_available(csp->cfd, csp->config->socket_timeout)
1360 if (socket_is_still_alive(csp->cfd))
1362 log_error(LOG_LEVEL_CONNECT,
1363 "No request line on socket %d received in time. Timeout: %d.",
1364 csp->cfd, csp->config->socket_timeout);
1365 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1366 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1367 get_write_delay(csp));
1371 log_error(LOG_LEVEL_CONNECT,
1372 "The client side of the connection on socket %d got "
1373 "closed without sending a complete request line.", csp->cfd);
1378 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1380 if (len <= 0) return NULL;
1383 * If there is no memory left for buffering the
1384 * request, there is nothing we can do but hang up
1386 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1391 request_line = get_header(csp->client_iob);
1393 } while ((NULL != request_line) && ('\0' == *request_line));
1395 return request_line;
1401 CHUNK_STATUS_MISSING_DATA,
1402 CHUNK_STATUS_BODY_COMPLETE,
1403 CHUNK_STATUS_PARSE_ERROR
1407 /*********************************************************************
1409 * Function : chunked_body_is_complete
1411 * Description : Figures out whether or not a chunked body is complete.
1413 * Currently it always starts at the beginning of the
1414 * buffer which is somewhat wasteful and prevents Privoxy
1415 * from starting to forward the correctly parsed chunks
1416 * as soon as theoretically possible.
1418 * Should be modified to work with a common buffer,
1419 * and allow the caller to skip already parsed chunks.
1421 * This would allow the function to be used for unbuffered
1422 * response bodies as well.
1425 * 1 : iob = Buffer with the body to check.
1426 * 2 : length = Length of complete body
1428 * Returns : Enum with the result of the check.
1430 *********************************************************************/
1431 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1433 unsigned int chunksize;
1439 * We need at least a single digit, followed by "\r\n",
1440 * followed by an unknown amount of data, followed by "\r\n".
1442 if (p + 5 > iob->eod)
1444 return CHUNK_STATUS_MISSING_DATA;
1446 if (sscanf(p, "%x", &chunksize) != 1)
1448 return CHUNK_STATUS_PARSE_ERROR;
1452 * We want at least a single digit, followed by "\r\n",
1453 * followed by the specified amount of data, followed by "\r\n".
1455 if (p + chunksize + 5 > iob->eod)
1457 return CHUNK_STATUS_MISSING_DATA;
1460 /* Skip chunk-size. */
1461 p = strstr(p, "\r\n");
1464 return CHUNK_STATUS_PARSE_ERROR;
1466 /* Move beyond the chunkdata. */
1469 /* There should be another "\r\n" to skip */
1470 if (memcmp(p, "\r\n", 2))
1472 return CHUNK_STATUS_PARSE_ERROR;
1475 } while (chunksize > 0U);
1477 *length = (size_t)(p - iob->cur);
1478 assert(*length <= (size_t)(iob->eod - iob->cur));
1479 assert(p <= iob->eod);
1481 return CHUNK_STATUS_BODY_COMPLETE;
1486 /*********************************************************************
1488 * Function : receive_chunked_client_request_body
1490 * Description : Read the chunk-encoded client request body.
1491 * Failures are dealt with.
1494 * 1 : csp = Current client state (buffers, headers, etc...)
1496 * Returns : JB_ERR_OK or JB_ERR_PARSE
1498 *********************************************************************/
1499 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1502 enum chunk_status status;
1504 while (CHUNK_STATUS_MISSING_DATA ==
1505 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1507 char buf[BUFFER_SIZE];
1510 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1512 log_error(LOG_LEVEL_ERROR,
1513 "Timeout while waiting for the client body.");
1516 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1519 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1522 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1527 if (status != CHUNK_STATUS_BODY_COMPLETE)
1529 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1530 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1531 log_error(LOG_LEVEL_CLF,
1532 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1533 return JB_ERR_PARSE;
1535 log_error(LOG_LEVEL_CONNECT,
1536 "Chunked client body completely read. Length: %d", body_length);
1537 csp->expected_client_content_length = body_length;
1545 /*********************************************************************
1547 * Function : fuzz_chunked_transfer_encoding
1549 * Description : Treat the fuzzed input as chunked transfer encoding
1550 * to check and dechunk.
1553 * 1 : csp = Used to store the data.
1554 * 2 : fuzz_input_file = File to read the input from.
1556 * Returns : Result of dechunking
1558 *********************************************************************/
1559 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1562 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1563 enum chunk_status status;
1565 status = chunked_body_is_complete(csp->iob, &length);
1566 if (CHUNK_STATUS_BODY_COMPLETE != status)
1568 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1571 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1576 /*********************************************************************
1578 * Function : fuzz_client_request
1580 * Description : Try to get a client request from the fuzzed input.
1583 * 1 : csp = Current client state (buffers, headers, etc...)
1584 * 2 : fuzz_input_file = File to read the input from.
1586 * Returns : Result of fuzzing.
1588 *********************************************************************/
1589 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1594 csp->ip_addr_str = "fuzzer";
1596 if (strcmp(fuzz_input_file, "-") != 0)
1598 log_error(LOG_LEVEL_FATAL,
1599 "Fuzzed client requests can currenty only be read from stdin (-).");
1601 err = receive_client_request(csp);
1602 if (err != JB_ERR_OK)
1606 err = parse_client_request(csp);
1607 if (err != JB_ERR_OK)
1615 #endif /* def FUZZ */
1618 #ifdef FEATURE_FORCE_LOAD
1619 /*********************************************************************
1621 * Function : force_required
1623 * Description : Checks a request line to see if it contains
1624 * the FORCE_PREFIX. If it does, it is removed
1625 * unless enforcing requests has beend disabled.
1628 * 1 : request_line = HTTP request line
1630 * Returns : TRUE if force is required, FALSE otherwise.
1632 *********************************************************************/
1633 static int force_required(const struct client_state *csp, char *request_line)
1637 p = strstr(request_line, "http://");
1641 p += strlen("http://");
1645 /* Intercepted request usually don't specify the protocol. */
1649 /* Go to the beginning of the path */
1654 * If the path is missing the request line is invalid and we
1655 * are done here. The client-visible rejection happens later on.
1660 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1662 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1664 /* XXX: Should clean more carefully */
1665 strclean(request_line, FORCE_PREFIX);
1666 log_error(LOG_LEVEL_FORCE,
1667 "Enforcing request: \"%s\".", request_line);
1671 log_error(LOG_LEVEL_FORCE,
1672 "Ignored force prefix in request: \"%s\".", request_line);
1678 #endif /* def FEATURE_FORCE_LOAD */
1681 /*********************************************************************
1683 * Function : receive_client_request
1685 * Description : Read the client's request (more precisely the
1686 * client headers) and answer it if necessary.
1689 * 1 : csp = Current client state (buffers, headers, etc...)
1691 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1693 *********************************************************************/
1694 static jb_err receive_client_request(struct client_state *csp)
1696 char buf[BUFFER_SIZE];
1699 struct http_request *http;
1703 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1704 struct list header_list;
1705 struct list *headers = &header_list;
1707 /* We don't care if the arriving data is a valid HTTP request or not. */
1708 csp->requests_received_total++;
1712 memset(buf, 0, sizeof(buf));
1714 req = get_request_line(csp);
1717 mark_server_socket_tainted(csp);
1718 return JB_ERR_PARSE;
1720 assert(*req != '\0');
1722 if (client_protocol_is_unsupported(csp, req))
1724 return JB_ERR_PARSE;
1727 #ifdef FEATURE_FORCE_LOAD
1728 if (force_required(csp, req))
1730 csp->flags |= CSP_FLAG_FORCED;
1732 #endif /* def FEATURE_FORCE_LOAD */
1734 err = parse_http_request(req, http);
1736 if (JB_ERR_OK != err)
1738 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1739 get_write_delay(csp));
1740 /* XXX: Use correct size */
1741 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1742 log_error(LOG_LEVEL_ERROR,
1743 "Couldn't parse request line received from %s: %s",
1744 csp->ip_addr_str, jb_err_to_string(err));
1746 free_http_request(http);
1747 return JB_ERR_PARSE;
1750 /* grab the rest of the client's headers */
1754 p = get_header(csp->client_iob);
1758 /* There are no additional headers to read. */
1765 * We didn't receive a complete header
1766 * line yet, get the rest of it.
1768 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1770 log_error(LOG_LEVEL_ERROR,
1771 "Stopped grabbing the client headers.");
1772 destroy_list(headers);
1773 return JB_ERR_PARSE;
1776 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1779 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1780 destroy_list(headers);
1781 return JB_ERR_PARSE;
1784 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1787 * If there is no memory left for buffering the
1788 * request, there is nothing we can do but hang up
1790 destroy_list(headers);
1791 return JB_ERR_MEMORY;
1796 if (!strncmpic(p, "Transfer-Encoding:", 18))
1799 * XXX: should be called through sed()
1800 * but currently can't.
1802 client_transfer_encoding(csp, &p);
1805 * We were able to read a complete
1806 * header and can finally enlist it.
1813 if (http->host == NULL)
1816 * If we still don't know the request destination,
1817 * the request is invalid or the client uses
1818 * Privoxy without its knowledge.
1820 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1823 * Our attempts to get the request destination
1824 * elsewhere failed or Privoxy is configured
1825 * to only accept proxy requests.
1827 * An error response has already been send
1828 * and we're done here.
1830 return JB_ERR_PARSE;
1834 #ifdef FEATURE_CLIENT_TAGS
1835 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1836 set_client_address(csp, headers);
1837 get_tag_list_for_client(csp->client_tags, csp->client_address);
1841 * Determine the actions for this URL
1843 #ifdef FEATURE_TOGGLE
1844 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1846 /* Most compatible set of actions (i.e. none) */
1847 init_current_action(csp->action);
1850 #endif /* ndef FEATURE_TOGGLE */
1852 get_url_actions(csp, http);
1855 enlist(csp->headers, http->cmd);
1857 /* Append the previously read headers */
1858 err = list_append_list_unique(csp->headers, headers);
1859 destroy_list(headers);
1866 /*********************************************************************
1868 * Function : parse_client_request
1870 * Description : Parses the client's request and decides what to do
1873 * Note that since we're not using select() we could get
1874 * blocked here if a client connected, then didn't say
1878 * 1 : csp = Current client state (buffers, headers, etc...)
1880 * Returns : JB_ERR_OK or JB_ERR_PARSE
1882 *********************************************************************/
1883 static jb_err parse_client_request(struct client_state *csp)
1885 struct http_request *http = csp->http;
1888 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1889 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1890 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1891 && (csp->http->ssl == 0))
1893 /* Assume persistence until further notice */
1894 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1897 if (csp->http->ssl == 0)
1900 * This whole block belongs to chat() but currently
1901 * has to be executed before sed().
1903 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1905 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1907 return JB_ERR_PARSE;
1912 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1914 verify_request_length(csp);
1918 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1920 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1922 err = sed(csp, FILTER_CLIENT_HEADERS);
1923 if (JB_ERR_OK != err)
1925 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1927 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1928 csp->ip_addr_str, csp->http->cmd);
1929 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1930 return JB_ERR_PARSE;
1932 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1934 /* Check request line for rewrites. */
1935 if ((NULL == csp->headers->first->str)
1936 || (strcmp(http->cmd, csp->headers->first->str) &&
1937 (JB_ERR_OK != change_request_destination(csp))))
1940 * A header filter broke the request line - bail out.
1942 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1943 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1944 /* XXX: Use correct size */
1945 log_error(LOG_LEVEL_CLF,
1946 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1947 log_error(LOG_LEVEL_ERROR,
1948 "Invalid request line after applying header filters.");
1949 free_http_request(http);
1951 return JB_ERR_PARSE;
1954 if (client_has_unsupported_expectations(csp))
1956 return JB_ERR_PARSE;
1964 /*********************************************************************
1966 * Function : send_http_request
1968 * Description : Sends the HTTP headers from the client request
1969 * and all the body data that has already been received.
1972 * 1 : csp = Current client state (buffers, headers, etc...)
1974 * Returns : 0 on success, anything else is an error.
1976 *********************************************************************/
1977 static int send_http_request(struct client_state *csp)
1982 hdr = list_to_text(csp->headers);
1985 /* FIXME Should handle error properly */
1986 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1988 list_remove_all(csp->headers);
1991 * Write the client's (modified) header to the server
1992 * (along with anything else that may be in the buffer)
1994 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1999 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2000 csp->http->hostport);
2002 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2003 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2006 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2007 csp->http->hostport);
2010 return write_failure;
2015 #ifdef FEATURE_HTTPS_INSPECTION
2016 /*********************************************************************
2018 * Function : receive_and_send_encrypted_post_data
2020 * Description : Reads remaining POST data from the client and sends
2024 * 1 : csp = Current client state (buffers, headers, etc...)
2026 * Returns : 0 on success, anything else is an error.
2028 *********************************************************************/
2029 static jb_err receive_and_send_encrypted_post_data(struct client_state *csp)
2031 int content_length_known = csp->expected_client_content_length != 0;
2033 while (is_ssl_pending(&(csp->mbedtls_client_attr.ssl)))
2035 unsigned char buf[BUFFER_SIZE];
2037 int max_bytes_to_read = sizeof(buf);
2039 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2041 max_bytes_to_read = (int)csp->expected_client_content_length;
2043 log_error(LOG_LEVEL_CONNECT,
2044 "Waiting for up to %d bytes of POST data from the client.",
2046 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl), buf,
2047 (unsigned)max_bytes_to_read);
2054 /* XXX: Does this actually happen? */
2057 log_error(LOG_LEVEL_HEADER, "Forwarding %d bytes of encrypted POST data",
2059 len = ssl_send_data(&(csp->mbedtls_server_attr.ssl), buf, (size_t)len);
2064 if (csp->expected_client_content_length != 0)
2066 if (csp->expected_client_content_length >= len)
2068 csp->expected_client_content_length -= (unsigned)len;
2070 if (csp->expected_client_content_length == 0)
2072 log_error(LOG_LEVEL_HEADER, "Forwarded the last %d bytes", len);
2078 log_error(LOG_LEVEL_HEADER, "Done forwarding encrypted POST data");
2085 /*********************************************************************
2087 * Function : send_https_request
2089 * Description : Sends the HTTP headers from the client request
2090 * and all the body data that has already been received.
2093 * 1 : csp = Current client state (buffers, headers, etc...)
2095 * Returns : 0 on success, anything else is an error.
2097 *********************************************************************/
2098 static int send_https_request(struct client_state *csp)
2104 hdr = list_to_text(csp->https_headers);
2107 /* FIXME Should handle error properly */
2108 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2110 list_remove_all(csp->https_headers);
2113 * Write the client's (modified) header to the server
2114 * (along with anything else that may be in the buffer)
2116 ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2117 (const unsigned char *)hdr, strlen(hdr));
2122 log_error(LOG_LEVEL_CONNECT,
2123 "Failed sending encrypted request headers to: %s: %E",
2124 csp->http->hostport);
2125 mark_server_socket_tainted(csp);
2129 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2130 && ((flushed = ssl_flush_socket(&(csp->mbedtls_server_attr.ssl),
2131 csp->client_iob)) < 0))
2133 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2134 csp->http->hostport);
2139 if (csp->expected_client_content_length != 0)
2141 if (csp->expected_client_content_length < flushed)
2143 log_error(LOG_LEVEL_ERROR,
2144 "Flushed %d bytes of request body while only expecting %llu",
2145 flushed, csp->expected_client_content_length);
2146 csp->expected_client_content_length = 0;
2150 log_error(LOG_LEVEL_CONNECT,
2151 "Flushed %d bytes of request body while expecting %llu",
2152 flushed, csp->expected_client_content_length);
2153 csp->expected_client_content_length -= (unsigned)flushed;
2154 if (receive_and_send_encrypted_post_data(csp))
2162 log_error(LOG_LEVEL_CONNECT,
2163 "Flushed %d bytes of request body", flushed);
2167 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2174 /*********************************************************************
2176 * Function : receive_encrypted_request
2178 * Description : Receives an encrypted request.
2181 * 1 : csp = Current client state (buffers, headers, etc...)
2183 * Returns : JB_ERR_OK on success,
2184 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2186 *********************************************************************/
2187 static jb_err receive_encrypted_request(struct client_state *csp)
2189 char buf[BUFFER_SIZE];
2195 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2196 if (!data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout))
2198 log_error(LOG_LEVEL_CONNECT,
2199 "Socket %d timed out while waiting for client headers", csp->cfd);
2200 return JB_ERR_PARSE;
2202 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2203 (unsigned char *)buf, sizeof(buf));
2206 return JB_ERR_PARSE;
2208 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2210 return JB_ERR_MEMORY;
2212 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2213 } while (p == NULL);
2215 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2221 /*********************************************************************
2223 * Function : process_encrypted_request
2225 * Description : Receives and parses an encrypted request.
2228 * 1 : csp = Current client state (buffers, headers, etc...)
2230 * Returns : JB_ERR_OK on success,
2231 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2233 *********************************************************************/
2234 static jb_err process_encrypted_request(struct client_state *csp)
2239 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2240 struct list header_list;
2241 struct list *headers = &header_list;
2243 err = receive_encrypted_request(csp);
2244 if (err != JB_ERR_OK)
2246 /* XXX: Also used for JB_ERR_MEMORY */
2247 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2248 jb_err_to_string(err));
2249 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2250 (const unsigned char *)CHEADER, strlen(CHEADER));
2254 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2255 request_line = get_header(csp->client_iob);
2256 if (request_line == NULL)
2258 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2259 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2260 (const unsigned char *)CHEADER, strlen(CHEADER));
2261 return JB_ERR_PARSE;
2263 assert(*request_line != '\0');
2265 if (client_protocol_is_unsupported(csp, request_line))
2267 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2268 (const unsigned char *)CHEADER, strlen(CHEADER));
2269 return JB_ERR_PARSE;
2272 #ifdef FEATURE_FORCE_LOAD
2273 if (force_required(csp, request_line))
2275 csp->flags |= CSP_FLAG_FORCED;
2277 #endif /* def FEATURE_FORCE_LOAD */
2279 free_http_request(csp->http);
2281 err = parse_http_request(request_line, csp->http);
2282 /* XXX: Restore ssl setting. This is ugly */
2283 csp->http->client_ssl = 1;
2284 csp->http->server_ssl = 1;
2286 freez(request_line);
2287 if (JB_ERR_OK != err)
2289 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2290 (const unsigned char *)CHEADER, strlen(CHEADER));
2291 /* XXX: Use correct size */
2292 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2293 log_error(LOG_LEVEL_ERROR,
2294 "Couldn't parse request line received from %s: %s",
2295 csp->ip_addr_str, jb_err_to_string(err));
2297 free_http_request(csp->http);
2298 return JB_ERR_PARSE;
2301 /* Parse the rest of the client's headers. */
2305 p = get_header(csp->client_iob);
2309 /* There are no additional headers to read. */
2316 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2319 * Our attempts to get the request destination
2322 log_error(LOG_LEVEL_ERROR,
2323 "Failed to get the encrypted request destination");
2324 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2325 (const unsigned char *)CHEADER, strlen(CHEADER));
2326 return JB_ERR_PARSE;
2329 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
2330 /* Split the domain we just got for pattern matching */
2331 init_domain_components(csp->http);
2334 #ifdef FEATURE_TOGGLE
2335 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2338 /* Determine the actions for this URL */
2339 get_url_actions(csp, csp->http);
2342 enlist(csp->https_headers, csp->http->cmd);
2344 /* Append the previously read headers */
2345 err = list_append_list_unique(csp->https_headers, headers);
2346 destroy_list(headers);
2347 if (JB_ERR_OK != err)
2349 /* XXX: Send error message */
2353 /* XXX: Work around crash */
2354 csp->error_message = NULL;
2356 /* XXX: Why do this here? */
2359 err = sed_https(csp);
2360 if (JB_ERR_OK != err)
2362 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2363 (const unsigned char *)CHEADER, strlen(CHEADER));
2364 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2366 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2367 csp->ip_addr_str, csp->http->cmd);
2368 return JB_ERR_PARSE;
2371 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2372 log_applied_actions(csp->action);
2380 /*********************************************************************
2382 * Function : handle_established_connection
2384 * Description : Shuffle data between client and server once the
2385 * connection has been established.
2388 * 1 : csp = Current client state (buffers, headers, etc...)
2390 * Returns : Nothing.
2392 *********************************************************************/
2393 static void handle_established_connection(struct client_state *csp)
2399 struct pollfd poll_fds[2];
2403 struct timeval timeout;
2406 int ms_iis5_hack = 0;
2407 unsigned long long byte_count = 0;
2408 struct http_request *http;
2409 long len = 0; /* for buffer sizes (and negative error codes) */
2410 int buffer_and_filter_content = 0;
2411 unsigned int write_delay;
2412 #ifdef FEATURE_HTTPS_INSPECTION
2414 int use_ssl_tunnel = 0;
2415 csp->dont_verify_certificate = 0;
2417 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2419 /* Pass encrypted content without filtering. */
2424 /* Skeleton for HTTP response, if we should intercept the request */
2425 struct http_response *rsp;
2426 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2427 int watch_client_socket;
2430 csp->receive_buffer_size = csp->config->receive_buffer_size;
2431 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2432 if (csp->receive_buffer == NULL)
2434 log_error(LOG_LEVEL_ERROR,
2435 "Out of memory. Failed to allocate the receive buffer.");
2436 rsp = cgi_error_memory();
2437 send_crunch_response(csp, rsp);
2444 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2445 csp->cfd : csp->server_connection.sfd;
2448 /* pass data between the client and server
2449 * until one or the other shuts down the connection.
2454 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2455 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2457 write_delay = get_write_delay(csp);
2464 * FD_ZERO here seems to point to an errant macro which crashes.
2465 * So do this by hand for now...
2467 memset(&rfds,0x00,sizeof(fd_set));
2471 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2472 if (!watch_client_socket)
2474 maxfd = csp->server_connection.sfd;
2477 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2479 FD_SET(csp->cfd, &rfds);
2482 FD_SET(csp->server_connection.sfd, &rfds);
2483 #endif /* ndef HAVE_POLL */
2485 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2486 if ((csp->flags & CSP_FLAG_CHUNKED)
2487 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2488 && ((csp->iob->eod - csp->iob->cur) >= 5)
2489 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2492 * XXX: This check should be obsolete now,
2493 * but let's wait a while to be sure.
2495 log_error(LOG_LEVEL_CONNECT,
2496 "Looks like we got the last chunk together with "
2497 "the server headers but didn't detect it earlier. "
2498 "We better stop reading.");
2499 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2500 csp->expected_content_length = byte_count;
2501 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2503 if (server_body && server_response_is_complete(csp, byte_count))
2505 if (csp->expected_content_length == byte_count)
2507 log_error(LOG_LEVEL_CONNECT,
2508 "Done reading from server. Content length: %llu as expected. "
2509 "Bytes most recently read: %d.",
2514 log_error(LOG_LEVEL_CONNECT,
2515 "Done reading from server. Expected content length: %llu. "
2516 "Actual content length: %llu. Bytes most recently read: %d.",
2517 csp->expected_content_length, byte_count, len);
2521 * XXX: Should not jump around, handle_established_connection()
2522 * is complicated enough already.
2526 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2529 poll_fds[0].fd = csp->cfd;
2530 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2531 if (!watch_client_socket)
2534 * Ignore incoming data, but still watch out
2535 * for disconnects etc. These flags are always
2536 * implied anyway but explicitly setting them
2539 poll_fds[0].events = POLLERR|POLLHUP;
2544 poll_fds[0].events = POLLIN;
2546 poll_fds[1].fd = csp->server_connection.sfd;
2547 poll_fds[1].events = POLLIN;
2548 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2550 timeout.tv_sec = csp->config->socket_timeout;
2551 timeout.tv_usec = 0;
2552 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
2553 #endif /* def HAVE_POLL */
2555 /*server or client not responding in timeout */
2558 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2559 csp->config->socket_timeout, http->url);
2560 if ((byte_count == 0) && (http->ssl == 0))
2562 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2564 mark_server_socket_tainted(csp);
2565 #ifdef FEATURE_HTTPS_INSPECTION
2566 close_client_and_server_ssl_connections(csp);
2573 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2575 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2577 mark_server_socket_tainted(csp);
2578 #ifdef FEATURE_HTTPS_INSPECTION
2579 close_client_and_server_ssl_connections(csp);
2585 * This is the body of the browser's request,
2586 * just read and write it.
2588 * Receives data from browser and sends it to server
2590 * XXX: Make sure the client doesn't use pipelining
2591 * behind Privoxy's back.
2594 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2596 log_error(LOG_LEVEL_CONNECT,
2597 "The client socket %d has become unusable while "
2598 "the server socket %d is still open.",
2599 csp->cfd, csp->server_connection.sfd);
2600 mark_server_socket_tainted(csp);
2604 if (poll_fds[0].revents != 0)
2606 if (FD_ISSET(csp->cfd, &rfds))
2607 #endif /* def HAVE_POLL*/
2609 int max_bytes_to_read = (int)csp->receive_buffer_size;
2611 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2612 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2614 if (data_is_available(csp->cfd, 0))
2617 * If the next request is already waiting, we have
2618 * to stop select()ing the client socket. Otherwise
2619 * we would always return right away and get nothing
2622 watch_client_socket = 0;
2623 log_error(LOG_LEVEL_CONNECT,
2624 "Stop watching client socket %d. "
2625 "There's already another request waiting.",
2630 * If the client socket is set, but there's no data
2631 * available on the socket, the client went fishing
2632 * and continuing talking to the server makes no sense.
2634 log_error(LOG_LEVEL_CONNECT,
2635 "The client closed socket %d while "
2636 "the server socket %d is still open.",
2637 csp->cfd, csp->server_connection.sfd);
2638 mark_server_socket_tainted(csp);
2641 if (csp->expected_client_content_length != 0)
2643 if (csp->expected_client_content_length < csp->receive_buffer_size)
2645 max_bytes_to_read = (int)csp->expected_client_content_length;
2647 log_error(LOG_LEVEL_CONNECT,
2648 "Waiting for up to %d bytes from the client.",
2651 assert(max_bytes_to_read <= csp->receive_buffer_size);
2652 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2654 #ifdef FEATURE_HTTPS_INSPECTION
2656 * Reading data from standard or secured connection (HTTP/HTTPS)
2658 if (client_use_ssl(csp))
2661 * Receiving HTTP request from client over TLS/SSL and sending
2662 * it to server over TLS/SSL.
2664 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2665 (unsigned char *)csp->receive_buffer, (size_t)max_bytes_to_read);
2669 mark_server_socket_tainted(csp);
2673 ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2674 (const unsigned char *)csp->receive_buffer, (size_t)len);
2678 log_error(LOG_LEVEL_ERROR,
2679 "Send request over TLS/SSL to: %s failed", http->host);
2680 mark_server_socket_tainted(csp);
2681 close_client_and_server_ssl_connections(csp);
2686 #endif /* def FEATURE_HTTPS_INSPECTION */
2688 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2692 /* XXX: not sure if this is necessary. */
2693 mark_server_socket_tainted(csp);
2694 break; /* "game over, man" */
2697 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2698 if (csp->expected_client_content_length != 0)
2700 assert(len <= max_bytes_to_read);
2701 csp->expected_client_content_length -= (unsigned)len;
2702 log_error(LOG_LEVEL_CONNECT,
2703 "Expected client content length set to %llu "
2704 "after reading %d bytes.",
2705 csp->expected_client_content_length, len);
2706 if (csp->expected_client_content_length == 0)
2708 log_error(LOG_LEVEL_CONNECT,
2709 "Done reading from the client.");
2710 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2713 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2715 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2717 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2718 mark_server_socket_tainted(csp);
2726 * The server wants to talk. It could be the header or the body.
2727 * If `hdr' is null, then it's the header otherwise it's the body.
2728 * FIXME: Does `hdr' really mean `host'? No.
2731 if (poll_fds[1].revents != 0)
2733 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2734 #endif /* HAVE_POLL */
2736 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2738 * If we are buffering content, we don't want to eat up to
2739 * buffer-limit bytes if the client no longer cares about them.
2740 * If we aren't buffering, however, a dead client socket will be
2741 * noticed pretty much right away anyway, so we can reduce the
2742 * overhead by skipping the check.
2744 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2747 log_error(LOG_LEVEL_CONNECT,
2748 "The server still wants to talk, but the client may already have hung up on us.");
2750 log_error(LOG_LEVEL_CONNECT,
2751 "The server still wants to talk, but the client hung up on us.");
2752 mark_server_socket_tainted(csp);
2753 #ifdef FEATURE_HTTPS_INSPECTION
2754 close_client_and_server_ssl_connections(csp);
2757 #endif /* def _WIN32 */
2759 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2761 #ifdef FEATURE_HTTPS_INSPECTION
2763 * Reading data from standard or secured connection (HTTP/HTTPS)
2765 if (server_use_ssl(csp))
2767 len = ssl_recv_data(&(csp->mbedtls_server_attr.ssl),
2768 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2773 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2774 (int)csp->receive_buffer_size);
2779 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2781 if ((http->ssl && (csp->fwd == NULL))
2782 #ifdef FEATURE_HTTPS_INSPECTION
2788 * Just hang up. We already confirmed the client's CONNECT
2789 * request with status code 200 and unencrypted content is
2790 * no longer welcome.
2792 log_error(LOG_LEVEL_ERROR,
2793 "CONNECT already confirmed. Unable to tell the client about the problem.");
2796 else if (byte_count)
2799 * Just hang up. We already transmitted the original headers
2800 * and parts of the original content and therefore missed the
2801 * chance to send an error message (without risking data corruption).
2803 * XXX: we could retry with a fancy range request here.
2805 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2806 "Unable to tell the client about the problem.");
2807 mark_server_socket_tainted(csp);
2808 #ifdef FEATURE_HTTPS_INSPECTION
2809 close_client_and_server_ssl_connections(csp);
2814 * XXX: Consider handling the cases above the same.
2816 mark_server_socket_tainted(csp);
2820 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2821 if (csp->flags & CSP_FLAG_CHUNKED)
2823 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2825 /* XXX: this is a temporary hack */
2826 log_error(LOG_LEVEL_CONNECT,
2827 "Looks like we reached the end of the last chunk. "
2828 "We better stop reading.");
2829 csp->expected_content_length = byte_count + (unsigned long long)len;
2830 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2834 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2837 * This is guaranteed by allocating with zalloc_or_die()
2838 * and never (intentionally) writing to the last byte.
2840 * csp->receive_buffer_size is the size of the part of the
2841 * buffer we intentionally write to, but we actually
2842 * allocated csp->receive_buffer_size+1 bytes so the assertion
2843 * stays within the allocated range.
2845 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2848 * Add a trailing zero to let be able to use string operations.
2849 * XXX: do we still need this with filter_popups gone?
2851 assert(len <= csp->receive_buffer_size);
2852 csp->receive_buffer[len] = '\0';
2855 * Normally, this would indicate that we've read
2856 * as much as the server has sent us and we can
2857 * close the client connection. However, Microsoft
2858 * in its wisdom has released IIS/5 with a bug that
2859 * prevents it from sending the trailing \r\n in
2860 * a 302 redirect header (and possibly other headers).
2861 * To work around this if we've haven't parsed
2862 * a full header we'll append a trailing \r\n
2863 * and see if this now generates a valid one.
2865 * This hack shouldn't have any impacts. If we've
2866 * already transmitted the header or if this is a
2867 * SSL connection, then we won't bother with this
2868 * hack. So we only work on partially received
2869 * headers. If we append a \r\n and this still
2870 * doesn't generate a valid header, then we won't
2871 * transmit anything to the client.
2876 if (server_body || (http->ssl
2877 #ifdef FEATURE_HTTPS_INSPECTION
2883 * If we have been buffering up the document,
2884 * now is the time to apply content modification
2885 * and send the result to the client.
2887 if (buffer_and_filter_content)
2889 p = execute_content_filters(csp);
2891 * If content filtering fails, use the original
2892 * buffer and length.
2893 * (see p != NULL ? p : csp->iob->cur below)
2897 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2899 #ifdef FEATURE_COMPRESSION
2900 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2901 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2903 char *compressed_content = compress_buffer(p,
2904 (size_t *)&csp->content_length, csp->config->compression_level);
2905 if (compressed_content != NULL)
2908 p = compressed_content;
2909 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2914 if (JB_ERR_OK != update_server_headers(csp))
2916 log_error(LOG_LEVEL_FATAL,
2917 "Failed to update server headers. after filtering.");
2920 hdr = list_to_text(csp->headers);
2923 /* FIXME Should handle error properly */
2924 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2927 #ifdef FEATURE_HTTPS_INSPECTION
2929 * Sending data with standard or secured connection (HTTP/HTTPS)
2931 if (client_use_ssl(csp))
2933 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2934 (const unsigned char *)hdr, strlen(hdr)) < 0)
2935 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2936 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
2937 csp->content_length) < 0))
2939 log_error(LOG_LEVEL_ERROR, "write modified content to "
2940 "client over TLS/SSL failed");
2943 mark_server_socket_tainted(csp);
2944 close_client_and_server_ssl_connections(csp);
2949 #endif /* def FEATURE_HTTPS_INSPECTION */
2951 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2952 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
2953 (size_t)csp->content_length, write_delay))
2955 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2958 mark_server_socket_tainted(csp);
2967 break; /* "game over, man" */
2971 * This is NOT the body, so
2972 * Let's pretend the server just sent us a blank line.
2974 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
2975 len = (int)strlen(csp->receive_buffer);
2978 * Now, let the normal header parsing algorithm below do its
2979 * job. If it fails, we'll exit instead of continuing.
2986 * If we're in the body of the server document, just write it to
2987 * the client, unless we need to buffer the body for later
2988 * content-filtering.
2990 if (server_body || (http->ssl
2991 #ifdef FEATURE_HTTPS_INSPECTION
2996 if (buffer_and_filter_content)
2999 * If there is no memory left for buffering the content, or the buffer limit
3000 * has been reached, switch to non-filtering mode, i.e. make & write the
3001 * header, flush the iob and buf, and get out of the way.
3003 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3008 log_error(LOG_LEVEL_INFO,
3009 "Flushing header and buffers. Stepping back from filtering.");
3011 hdr = list_to_text(csp->headers);
3015 * Memory is too tight to even generate the header.
3016 * Send our static "Out-of-memory" page.
3018 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3019 rsp = cgi_error_memory();
3020 send_crunch_response(csp, rsp);
3021 mark_server_socket_tainted(csp);
3022 #ifdef FEATURE_HTTPS_INSPECTION
3023 close_client_and_server_ssl_connections(csp);
3027 hdrlen = strlen(hdr);
3029 #ifdef FEATURE_HTTPS_INSPECTION
3031 * Sending data with standard or secured connection (HTTP/HTTPS)
3033 if (client_use_ssl(csp))
3035 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3036 (const unsigned char *)hdr, hdrlen) < 0)
3037 || ((flushed = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3039 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3040 (const unsigned char *)csp->receive_buffer, (size_t)len) < 0))
3042 log_error(LOG_LEVEL_CONNECT,
3043 "Flush header and buffers to client failed");
3045 mark_server_socket_tainted(csp);
3046 close_client_and_server_ssl_connections(csp);
3051 #endif /* def FEATURE_HTTPS_INSPECTION */
3053 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3054 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3055 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3058 log_error(LOG_LEVEL_CONNECT,
3059 "Flush header and buffers to client failed: %E");
3061 mark_server_socket_tainted(csp);
3067 * Reset the byte_count to the amount of bytes
3068 * we just flushed. len will be added a few lines below,
3069 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3071 byte_count = (unsigned long long)flushed;
3073 buffer_and_filter_content = 0;
3079 #ifdef FEATURE_HTTPS_INSPECTION
3081 * Sending data with standard or secured connection (HTTP/HTTPS)
3083 if (client_use_ssl(csp))
3085 ret = ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3086 (const unsigned char *)csp->receive_buffer, (size_t)len);
3089 log_error(LOG_LEVEL_ERROR,
3090 "Sending data to client failed");
3091 mark_server_socket_tainted(csp);
3092 close_client_and_server_ssl_connections(csp);
3097 #endif /* def FEATURE_HTTPS_INSPECTION */
3099 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3100 (size_t)len, write_delay))
3102 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3103 mark_server_socket_tainted(csp);
3108 byte_count += (unsigned long long)len;
3114 * We're still looking for the end of the server's header.
3115 * Buffer up the data we just read. If that fails, there's
3116 * little we can do but send our static out-of-memory page.
3118 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3120 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3121 rsp = cgi_error_memory();
3122 send_crunch_response(csp, rsp);
3123 mark_server_socket_tainted(csp);
3124 #ifdef FEATURE_HTTPS_INSPECTION
3125 close_client_and_server_ssl_connections(csp);
3130 /* Convert iob into something sed() can digest */
3131 if (JB_ERR_PARSE == get_server_headers(csp))
3136 * Well, we tried our MS IIS/5 hack and it didn't work.
3137 * The header is incomplete and there isn't anything
3138 * we can do about it.
3140 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3141 "Applying the MS IIS5 hack didn't help.");
3142 log_error(LOG_LEVEL_CLF,
3143 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3144 #ifdef FEATURE_HTTPS_INSPECTION
3146 * Sending data with standard or secured connection (HTTP/HTTPS)
3148 if (client_use_ssl(csp))
3150 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3151 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3152 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3155 #endif /* def FEATURE_HTTPS_INSPECTION */
3157 write_socket_delayed(csp->cfd,
3158 INVALID_SERVER_HEADERS_RESPONSE,
3159 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3161 mark_server_socket_tainted(csp);
3162 #ifdef FEATURE_HTTPS_INSPECTION
3163 close_client_and_server_ssl_connections(csp);
3170 * Since we have to wait for more from the server before
3171 * we can parse the headers we just continue here.
3173 log_error(LOG_LEVEL_CONNECT,
3174 "Continuing buffering server headers from socket %d. "
3175 "Bytes most recently read: %d.", csp->cfd, len);
3182 * Account for the content bytes we
3183 * might have gotten with the headers.
3185 assert(csp->iob->eod >= csp->iob->cur);
3186 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3189 /* Did we actually get anything? */
3190 if (NULL == csp->headers->first)
3192 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3194 log_error(LOG_LEVEL_ERROR,
3195 "No server or forwarder response received on socket %d. "
3196 "Closing client socket %d without sending data.",
3197 csp->server_connection.sfd, csp->cfd);
3198 log_error(LOG_LEVEL_CLF,
3199 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3203 log_error(LOG_LEVEL_ERROR,
3204 "No server or forwarder response received on socket %d.",
3205 csp->server_connection.sfd);
3206 send_crunch_response(csp, error_response(csp, "no-server-data"));
3208 free_http_request(http);
3209 mark_server_socket_tainted(csp);
3210 #ifdef FEATURE_HTTPS_INSPECTION
3211 close_client_and_server_ssl_connections(csp);
3216 if (!csp->headers->first->str)
3218 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3220 assert(csp->headers->first->str);
3222 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3223 strncmpic(csp->headers->first->str, "ICY", 3))
3226 * It doesn't look like a HTTP (or Shoutcast) response:
3227 * tell the client and log the problem.
3229 if (strlen(csp->headers->first->str) > 30)
3231 csp->headers->first->str[30] = '\0';
3233 log_error(LOG_LEVEL_ERROR,
3234 "Invalid server or forwarder response. Starts with: %s",
3235 csp->headers->first->str);
3236 log_error(LOG_LEVEL_CLF,
3237 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3238 #ifdef FEATURE_HTTPS_INSPECTION
3240 * Sending data with standard or secured connection (HTTP/HTTPS)
3242 if (client_use_ssl(csp))
3244 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3245 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3246 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3249 #endif /* def FEATURE_HTTPS_INSPECTION */
3251 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3252 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3254 free_http_request(http);
3255 mark_server_socket_tainted(csp);
3256 #ifdef FEATURE_HTTPS_INSPECTION
3257 close_client_and_server_ssl_connections(csp);
3263 * We have now received the entire server header,
3264 * filter it and send the result to the client
3266 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3268 log_error(LOG_LEVEL_CLF,
3269 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3270 #ifdef FEATURE_HTTPS_INSPECTION
3272 * Sending data with standard or secured connection (HTTP/HTTPS)
3274 if (client_use_ssl(csp))
3276 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3277 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3278 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3283 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3284 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3286 free_http_request(http);
3287 mark_server_socket_tainted(csp);
3288 #ifdef FEATURE_HTTPS_INSPECTION
3289 close_client_and_server_ssl_connections(csp);
3293 hdr = list_to_text(csp->headers);
3296 /* FIXME Should handle error properly */
3297 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3300 if ((csp->flags & CSP_FLAG_CHUNKED)
3301 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3302 && ((csp->iob->eod - csp->iob->cur) >= 5)
3303 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3305 log_error(LOG_LEVEL_CONNECT,
3306 "Looks like we got the last chunk together with "
3307 "the server headers. We better stop reading.");
3308 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3309 csp->expected_content_length = byte_count;
3310 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3313 csp->server_connection.response_received = time(NULL);
3315 if (crunch_response_triggered(csp, crunchers_light))
3318 * One of the tags created by a server-header
3319 * tagger triggered a crunch. We already
3320 * delivered the crunch response to the client
3321 * and are done here after cleaning up.
3324 mark_server_socket_tainted(csp);
3325 #ifdef FEATURE_HTTPS_INSPECTION
3326 close_client_and_server_ssl_connections(csp);
3331 /* Buffer and pcrs filter this if appropriate. */
3332 buffer_and_filter_content = content_requires_filtering(csp);
3334 if (!buffer_and_filter_content)
3337 * Write the server's (modified) header to
3338 * the client (along with anything else that
3339 * may be in the buffer). Use standard or secured
3342 #ifdef FEATURE_HTTPS_INSPECTION
3343 if (client_use_ssl(csp))
3345 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3346 (const unsigned char *)hdr, strlen(hdr)) < 0)
3347 || (len = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3350 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3353 * The write failed, so don't bother mentioning it
3354 * to the client... it probably can't hear us anyway.
3357 mark_server_socket_tainted(csp);
3358 #ifdef FEATURE_HTTPS_INSPECTION
3359 close_client_and_server_ssl_connections(csp);
3365 #endif /* def FEATURE_HTTPS_INSPECTION */
3367 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3368 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3370 log_error(LOG_LEVEL_ERROR,
3371 "write header to client failed");
3373 * The write failed, so don't bother mentioning it
3374 * to the client... it probably can't hear us anyway.
3377 mark_server_socket_tainted(csp);
3383 /* we're finished with the server's header */
3389 * If this was a MS IIS/5 hack then it means the server
3390 * has already closed the connection. Nothing more to read.
3395 log_error(LOG_LEVEL_ERROR,
3396 "Closed server connection detected. "
3397 "Applying the MS IIS5 hack didn't help.");
3398 log_error(LOG_LEVEL_CLF,
3399 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3400 #ifdef FEATURE_HTTPS_INSPECTION
3402 * Sending data with standard or secured connection (HTTP/HTTPS)
3404 if (client_use_ssl(csp))
3406 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3407 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3408 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3411 #endif /* def FEATURE_HTTPS_INSPECTION */
3413 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3414 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3416 mark_server_socket_tainted(csp);
3417 #ifdef FEATURE_HTTPS_INSPECTION
3418 close_client_and_server_ssl_connections(csp);
3425 mark_server_socket_tainted(csp);
3426 #ifdef FEATURE_HTTPS_INSPECTION
3427 close_client_and_server_ssl_connections(csp);
3429 return; /* huh? we should never get here */
3431 #ifdef FEATURE_HTTPS_INSPECTION
3432 close_client_and_server_ssl_connections(csp);
3434 if (csp->content_length == 0)
3437 * If Privoxy didn't recalculate the Content-Length,
3438 * byte_count is still correct.
3440 csp->content_length = byte_count;
3443 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3444 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3445 && (csp->expected_content_length != byte_count))
3447 log_error(LOG_LEVEL_CONNECT,
3448 "Received %llu bytes while expecting %llu.",
3449 byte_count, csp->expected_content_length);
3450 mark_server_socket_tainted(csp);
3454 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3455 csp->ip_addr_str, http->ocmd, csp->content_length);
3457 csp->server_connection.timestamp = time(NULL);
3461 /*********************************************************************
3465 * Description : Once a connection from the client has been accepted,
3466 * this function is called (via serve()) to handle the
3467 * main business of the communication. This function
3468 * returns after dealing with a single request. It can
3469 * be called multiple times with the same client socket
3470 * if the client is keeping the connection alive.
3472 * The decision whether or not a client connection will
3473 * be kept alive is up to the caller which also must
3474 * close the client socket when done.
3476 * FIXME: chat is nearly thousand lines long.
3480 * 1 : csp = Current client state (buffers, headers, etc...)
3482 * Returns : Nothing.
3484 *********************************************************************/
3485 static void chat(struct client_state *csp)
3487 const struct forward_spec *fwd;
3488 struct http_request *http;
3489 /* Skeleton for HTTP response, if we should intercept the request */
3490 struct http_response *rsp;
3491 #ifdef FEATURE_HTTPS_INSPECTION
3492 int use_ssl_tunnel = 0;
3497 if (receive_client_request(csp) != JB_ERR_OK)
3501 if (parse_client_request(csp) != JB_ERR_OK)
3506 /* decide how to route the HTTP request */
3507 fwd = forward_url(csp, http);
3510 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
3511 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3515 #ifdef FEATURE_HTTPS_INSPECTION
3517 * Setting flags to use old solution with SSL tunnel and to disable
3518 * certificates verification.
3520 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3525 if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3527 csp->dont_verify_certificate = 1;
3532 * build the http request to send to the server
3533 * we have to do one of the following:
3535 * create = use the original HTTP request to create a new
3536 * HTTP request that has either the path component
3537 * without the http://domainspec (w/path) or the
3538 * full orininal URL (w/url)
3539 * Note that the path and/or the HTTP version may
3540 * have been altered by now.
3542 * SSL proxy = Open a socket to the host:port of the server
3543 * and create TLS/SSL connection with server and
3544 * with client. Then behave like mediator between
3545 * client and server over TLS/SSL.
3547 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3548 * with request to a parent proxy. Note that we'll be sending
3549 * forwarding the CFAIL message ourselves if connecting to the parent
3550 * fails, but we won't send a CSUCCEED message if it works,
3551 * since that would result in a double message (ours and the
3552 * parent's). After sending the request to the parent, we
3553 * must parse answer and send it to client. If connection
3554 * with server is established, we do TLS/SSL proxy. Otherwise
3555 * we send parent response to client and close connections.
3557 * here's the matrix:
3560 * +--------+--------+
3562 * 0 | create | SSL |
3563 * | w/path | proxy |
3564 * Forwarding +--------+--------+
3566 * 1 | create | proxy |
3567 * | w/url |+forward|
3568 * +--------+--------+
3572 #ifdef FEATURE_HTTPS_INSPECTION
3574 * Presetting SSL client and server flags
3576 if (http->ssl && !use_ssl_tunnel)
3578 http->client_ssl = 1;
3579 http->server_ssl = 1;
3583 http->client_ssl = 0;
3584 http->server_ssl = 0;
3588 if (http->ssl && connect_port_is_forbidden(csp))
3590 const char *acceptable_connect_ports =
3591 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3592 assert(NULL != acceptable_connect_ports);
3593 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3594 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3595 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3596 csp->action->flags |= ACTION_BLOCK;
3598 #ifdef FEATURE_HTTPS_INSPECTION
3599 http->client_ssl = 0;
3600 http->server_ssl = 0;
3605 freez(csp->headers->first->str);
3606 build_request_line(csp, fwd, &csp->headers->first->str);
3609 * We have a request. Check if one of the crunchers wants it
3610 * unless the client wants to use TLS/SSL in which case we
3611 * haven't setup the TLS context yet and will send the crunch
3615 #ifdef FEATURE_HTTPS_INSPECTION
3616 !client_use_ssl(csp) &&
3618 crunch_response_triggered(csp, crunchers_all))
3621 * Yes. The client got the crunch response and we're done here.
3626 log_applied_actions(csp->action);
3627 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
3629 if (fwd->forward_host)
3631 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3632 fwd->forward_host, fwd->forward_port, http->hostport);
3636 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3639 /* here we connect to the server, gateway, or the forwarder */
3641 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3642 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3643 && socket_is_still_alive(csp->server_connection.sfd)
3644 && connection_destination_matches(&csp->server_connection, http, fwd))
3646 log_error(LOG_LEVEL_CONNECT,
3647 "Reusing server socket %d connected to %s. Total requests: %u.",
3648 csp->server_connection.sfd, csp->server_connection.host,
3649 csp->server_connection.requests_sent_total);
3653 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3655 #ifdef FEATURE_CONNECTION_SHARING
3656 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3658 remember_connection(&csp->server_connection);
3661 #endif /* def FEATURE_CONNECTION_SHARING */
3663 log_error(LOG_LEVEL_CONNECT,
3664 "Closing server socket %d connected to %s. Total requests: %u.",
3665 csp->server_connection.sfd, csp->server_connection.host,
3666 csp->server_connection.requests_sent_total);
3667 close_socket(csp->server_connection.sfd);
3669 mark_connection_closed(&csp->server_connection);
3671 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3672 #ifdef FEATURE_HTTPS_INSPECTION
3673 if (http->ssl && !use_ssl_tunnel)
3677 * Creating an SSL proxy. If forwarding is disabled, we must send
3678 * CSUCCEED mesage to client. Then TLS/SSL connection with client
3682 if (fwd->forward_host == NULL)
3685 * We're lying to the client as the connection hasn't actually
3686 * been established yet. We don't establish the connection until
3687 * we have seen and parsed the encrypted client headers.
3689 if (write_socket_delayed(csp->cfd, CSUCCEED,
3690 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3692 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3697 ret = create_client_ssl_connection(csp);
3700 log_error(LOG_LEVEL_ERROR,
3701 "Can't open secure connection with client");
3702 close_client_ssl_connection(csp); /* XXX: Is this needed? */
3705 if (JB_ERR_OK != process_encrypted_request(csp))
3707 log_error(LOG_LEVEL_ERROR, "Failed to parse encrypted request.");
3708 close_client_ssl_connection(csp);
3712 * We have an encrypted request. Check if one of the crunchers now
3713 * wants it (for example because the previously invisible path was
3714 * required to match).
3716 if (crunch_response_triggered(csp, crunchers_all))
3719 * Yes. The client got the crunch response and we're done here.
3721 close_client_ssl_connection(csp);
3727 * Connecting to destination server
3729 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3731 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3733 if (fwd->type != SOCKS_NONE)
3736 rsp = error_response(csp, "forwarding-failed");
3738 else if (errno == EINVAL)
3740 rsp = error_response(csp, "no-such-domain");
3744 rsp = error_response(csp, "connect-failed");
3747 /* Write the answer to the client */
3750 send_crunch_response(csp, rsp);
3754 * Temporary workaround to prevent already-read client
3755 * bodies from being parsed as new requests. For now we
3756 * err on the safe side and throw all the following
3757 * requests under the bus, even if no client body has been
3758 * buffered. A compliant client will repeat the dropped
3759 * requests on an untainted connection.
3761 * The proper fix is to discard the no longer needed
3762 * client body in the buffer (if there is one) and to
3763 * continue parsing the bytes that follow.
3765 drain_and_close_socket(csp->cfd);
3766 csp->cfd = JB_INVALID_SOCKET;
3771 #ifdef FEATURE_HTTPS_INSPECTION
3773 * Creating TLS/SSL connections with destination server or parent
3774 * proxy. If forwarding is enabled, we must send client request to
3775 * parent proxy and receive, parse and resend parent proxy answer.
3777 if (http->ssl && !use_ssl_tunnel)
3779 if (fwd->forward_host != NULL)
3781 char server_response[BUFFER_SIZE];
3784 char *hdr = list_to_text(csp->headers);
3785 memset(server_response, 0, sizeof(server_response));
3789 log_error(LOG_LEVEL_FATAL,
3790 "Out of memory parsing client header");
3792 list_remove_all(csp->headers);
3795 * Sending client's CONNECT request to the parent proxy
3797 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
3803 log_error(LOG_LEVEL_CONNECT,
3804 "Sending request headers to: %s failed", http->hostport);
3805 mark_server_socket_tainted(csp);
3806 close_client_ssl_connection(csp);
3810 /* Waiting for parent proxy server response */
3811 len = read_socket(csp->server_connection.sfd, server_response,
3812 sizeof(server_response)-1);
3816 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
3817 "server on socket %d.", csp->server_connection.sfd);
3819 rsp = error_response(csp, "no-server-data");
3822 send_crunch_response(csp, rsp);
3824 mark_server_socket_tainted(csp);
3825 close_client_ssl_connection(csp);
3830 * Test if connection with destination server was established
3831 * successfully by parent proxy. Then we can send response to
3832 * the client and continue or stop.
3834 if (!tunnel_established_successfully(server_response, (unsigned int)len))
3836 log_error(LOG_LEVEL_ERROR, "Forwarder hasn't established "
3837 "connection with destination server.");
3839 write_socket(csp->cfd, server_response, (size_t)len);
3840 mark_server_socket_tainted(csp);
3841 close_client_ssl_connection(csp);
3846 * Parent proxy has established connection with destination server.
3847 * Now we must create TLS/SSL connection with parent proxy.
3849 ret = create_server_ssl_connection(csp);
3852 * If TLS/SSL connection wasn't created and invalid certificate
3853 * wasn't detected, we can interrupt this function. Otherwise, we
3854 * must inform the client about invalid server certificate.
3857 && (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3858 || csp->server_cert_verification_result == SSL_CERT_VALID))
3860 rsp = error_response(csp, "connect-failed");
3863 send_crunch_response(csp, rsp);
3869 * TLS/SSL connection with parent proxy is established, we can
3870 * inform client about success.
3872 ret = write_socket(csp->cfd, server_response, (size_t)len);
3875 log_error(LOG_LEVEL_ERROR,
3876 "Sending parent proxy response to client failed");
3877 mark_server_socket_tainted(csp);
3878 close_client_ssl_connection(csp);
3881 }/* -END- if (fwd->forward_host != NULL) */
3885 * Parent proxy is not used, we can just create TLS/SSL connection
3886 * with destination server
3888 int ret = create_server_ssl_connection(csp);
3891 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
3892 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
3895 * If the server certificate is invalid, we must inform
3896 * the client and then close connection to the client.
3898 ssl_send_certificate_error(csp);
3899 close_client_and_server_ssl_connections(csp);
3902 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3903 || csp->server_cert_verification_result == SSL_CERT_VALID)
3906 * The TLS/SSL connection wasn't created but an invalid
3907 * certificate wasn't detected. Report it as connection
3910 rsp = error_response(csp, "connect-failed");
3913 send_crunch_response(csp, rsp);
3915 close_client_and_server_ssl_connections(csp);
3920 }/* -END- if (http->ssl) */
3921 #endif /* def FEATURE_HTTPS_INSPECTION */
3923 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3924 save_connection_destination(csp->server_connection.sfd,
3925 http, fwd, &csp->server_connection);
3926 csp->server_connection.keep_alive_timeout =
3927 (unsigned)csp->config->keep_alive_timeout;
3929 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3931 csp->server_connection.requests_sent_total++;
3933 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
3935 /* Client headers have been sent optimistically */
3936 assert(csp->headers->last == NULL);
3938 else if (http->ssl == 0 || (fwd->forward_host
3939 #ifdef FEATURE_HTTPS_INSPECTION
3944 if (send_http_request(csp))
3946 rsp = error_response(csp, "connect-failed");
3949 send_crunch_response(csp, rsp);
3957 * Using old solution with SSL tunnel or new solution with SSL proxy
3959 list_remove_all(csp->headers);
3960 #ifdef FEATURE_HTTPS_INSPECTION
3965 * We're running an SSL tunnel and we're not forwarding,
3966 * so just ditch the client headers, send the "connect succeeded"
3967 * message to the client, flush the rest, and get out of the way.
3969 if (write_socket_delayed(csp->cfd, CSUCCEED,
3970 strlen(CSUCCEED), get_write_delay(csp)))
3975 #ifdef FEATURE_HTTPS_INSPECTION
3979 * If server certificate is invalid, we must inform client and then
3980 * close connection with client.
3982 if (csp->server_cert_verification_result != SSL_CERT_VALID)
3984 ssl_send_certificate_error(csp);
3985 close_client_and_server_ssl_connections(csp);
3988 if (send_https_request(csp))
3990 rsp = error_response(csp, "connect-failed");
3993 send_crunch_response(csp, rsp);
3995 close_client_and_server_ssl_connections(csp);
3999 #endif /* def FEATURE_HTTPS_INSPECTION */
4000 clear_iob(csp->client_iob);
4001 }/* -END- else ... if (http->ssl == 1) */
4003 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4005 /* XXX: should the time start earlier for optimistically sent data? */
4006 csp->server_connection.request_sent = time(NULL);
4008 handle_established_connection(csp);
4009 freez(csp->receive_buffer);
4014 /*********************************************************************
4016 * Function : fuzz_server_response
4018 * Description : Treat the input as a whole server response.
4021 * 1 : csp = Current client state (buffers, headers, etc...)
4022 * 2 : fuzz_input_file = File to read the input from.
4026 *********************************************************************/
4027 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4029 static struct forward_spec fwd; /* Zero'd due to being static */
4032 if (strcmp(fuzz_input_file, "-") == 0)
4034 /* XXX: Doesn'T work yet. */
4035 csp->server_connection.sfd = 0;
4039 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4040 if (csp->server_connection.sfd == -1)
4042 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4047 csp->content_type |= CT_GIF;
4048 csp->action->flags |= ACTION_DEANIMATE;
4049 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4051 csp->http->path = strdup_or_die("/");
4052 csp->http->host = strdup_or_die("fuzz.example.org");
4053 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4054 /* Prevent client socket monitoring */
4055 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4056 csp->flags |= CSP_FLAG_CHUNKED;
4058 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4059 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4061 csp->content_type |= CT_DECLARED|CT_GIF;
4063 csp->config->socket_timeout = 0;
4065 cgi_init_error_messages();
4067 handle_established_connection(csp);
4068 freez(csp->receive_buffer);
4075 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4076 /*********************************************************************
4078 * Function : prepare_csp_for_next_request
4080 * Description : Put the csp in a mostly vergin state.
4083 * 1 : csp = Current client state (buffers, headers, etc...)
4087 *********************************************************************/
4088 static void prepare_csp_for_next_request(struct client_state *csp)
4090 csp->content_type = 0;
4091 csp->content_length = 0;
4092 csp->expected_content_length = 0;
4093 csp->expected_client_content_length = 0;
4094 list_remove_all(csp->headers);
4095 clear_iob(csp->iob);
4096 freez(csp->error_message);
4097 free_http_request(csp->http);
4098 destroy_list(csp->headers);
4099 destroy_list(csp->tags);
4100 #ifdef FEATURE_CLIENT_TAGS
4101 destroy_list(csp->client_tags);
4102 freez(csp->client_address);
4104 free_current_action(csp->action);
4105 if (NULL != csp->fwd)
4107 unload_forward_spec(csp->fwd);
4110 /* XXX: Store per-connection flags someplace else. */
4111 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4112 #ifdef FEATURE_TOGGLE
4113 if (global_toggle_state)
4114 #endif /* def FEATURE_TOGGLE */
4116 csp->flags |= CSP_FLAG_TOGGLED_ON;
4119 if (csp->client_iob->eod > csp->client_iob->cur)
4121 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4122 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4124 assert(bytes_to_shift > 0);
4125 assert(data_length > 0);
4127 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
4128 data_length, bytes_to_shift);
4129 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4130 csp->client_iob->cur = csp->client_iob->buf;
4131 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4132 csp->client_iob->eod = csp->client_iob->buf + data_length;
4133 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4135 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4140 * We mainly care about resetting client_iob->cur so we don't
4141 * waste buffer space at the beginning and don't mess up the
4142 * request restoration done by cgi_show_request().
4144 * Freeing the buffer itself isn't technically necessary,
4145 * but makes debugging more convenient.
4147 clear_iob(csp->client_iob);
4150 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4153 /*********************************************************************
4157 * Description : This is little more than chat. We only "serve" to
4158 * to close (or remember) any socket that chat may have
4162 * 1 : csp = Current client state (buffers, headers, etc...)
4166 *********************************************************************/
4167 static void serve(struct client_state *csp)
4169 int config_file_change_detected = 0; /* Only used for debugging */
4170 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4171 #ifdef FEATURE_CONNECTION_SHARING
4172 static int monitor_thread_running = 0;
4173 #endif /* def FEATURE_CONNECTION_SHARING */
4174 int continue_chatting = 0;
4176 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4177 csp->ip_addr_str, csp->cfd);
4181 unsigned int latency;
4186 * If the request has been crunched,
4187 * the calculated latency is zero.
4189 latency = (unsigned)(csp->server_connection.response_received -
4190 csp->server_connection.request_sent) / 2;
4192 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4193 && (csp->flags & CSP_FLAG_CRUNCHED)
4194 && (csp->expected_client_content_length != 0))
4196 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4197 log_error(LOG_LEVEL_CONNECT,
4198 "Tainting client socket %d due to unread data.", csp->cfd);
4201 continue_chatting = (csp->config->feature_flags
4202 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4203 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4204 && (csp->cfd != JB_INVALID_SOCKET)
4205 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4206 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4207 || (csp->flags & CSP_FLAG_CHUNKED));
4209 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4210 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4212 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4214 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4216 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4217 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4218 || !socket_is_still_alive(csp->server_connection.sfd)
4219 || !(latency < csp->server_connection.keep_alive_timeout))
4221 log_error(LOG_LEVEL_CONNECT,
4222 "Closing server socket %d connected to %s. "
4223 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
4224 csp->server_connection.sfd, csp->server_connection.host,
4225 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4226 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4227 socket_is_still_alive(csp->server_connection.sfd),
4228 csp->server_connection.keep_alive_timeout);
4229 #ifdef FEATURE_CONNECTION_SHARING
4230 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4232 forget_connection(csp->server_connection.sfd);
4234 #endif /* def FEATURE_CONNECTION_SHARING */
4235 close_socket(csp->server_connection.sfd);
4236 mark_connection_closed(&csp->server_connection);
4240 if (continue_chatting && any_loaded_file_changed(csp))
4242 continue_chatting = 0;
4243 config_file_change_detected = 1;
4246 if (continue_chatting)
4248 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4249 && socket_is_still_alive(csp->cfd))
4251 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4252 "pipelined on socket %d and the socket is still alive.",
4253 csp->requests_received_total+1, csp->cfd);
4254 prepare_csp_for_next_request(csp);
4258 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4260 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4262 log_error(LOG_LEVEL_CONNECT,
4263 "Waiting for the next client request on socket %d. "
4264 "Keeping the server socket %d to %s open.",
4265 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4269 log_error(LOG_LEVEL_CONNECT,
4270 "Waiting for the next client request on socket %d. "
4271 "No server socket to keep open.", csp->cfd);
4275 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4276 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4277 && socket_is_still_alive(csp->cfd))
4279 log_error(LOG_LEVEL_CONNECT,
4280 "Client request %u arrived in time on socket %d.",
4281 csp->requests_received_total+1, csp->cfd);
4282 prepare_csp_for_next_request(csp);
4286 #ifdef FEATURE_CONNECTION_SHARING
4287 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4288 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4289 && (socket_is_still_alive(csp->server_connection.sfd)))
4291 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4293 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4298 remember_connection(&csp->server_connection);
4299 csp->server_connection.sfd = JB_INVALID_SOCKET;
4300 drain_and_close_socket(csp->cfd);
4301 csp->cfd = JB_INVALID_SOCKET;
4302 privoxy_mutex_lock(&connection_reuse_mutex);
4303 if (!monitor_thread_running)
4305 monitor_thread_running = 1;
4306 privoxy_mutex_unlock(&connection_reuse_mutex);
4307 wait_for_alive_connections();
4308 privoxy_mutex_lock(&connection_reuse_mutex);
4309 monitor_thread_running = 0;
4311 privoxy_mutex_unlock(&connection_reuse_mutex);
4313 #endif /* def FEATURE_CONNECTION_SHARING */
4317 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4319 log_error(LOG_LEVEL_CONNECT,
4320 "Closing server socket %d connected to %s. Keep-alive: %u. "
4321 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4322 "Configuration file change detected: %u",
4323 csp->server_connection.sfd, csp->server_connection.host,
4324 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4325 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4326 socket_is_still_alive(csp->server_connection.sfd),
4327 csp->server_connection.keep_alive_timeout,
4328 config_file_change_detected);
4330 } while (continue_chatting);
4334 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4336 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4338 #ifdef FEATURE_CONNECTION_SHARING
4339 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4341 forget_connection(csp->server_connection.sfd);
4343 #endif /* def FEATURE_CONNECTION_SHARING */
4344 close_socket(csp->server_connection.sfd);
4347 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4348 mark_connection_closed(&csp->server_connection);
4351 if (csp->cfd != JB_INVALID_SOCKET)
4353 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4354 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4355 "Configuration file change detected: %u. Requests received: %u.",
4356 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4357 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4358 config_file_change_detected, csp->requests_received_total);
4359 drain_and_close_socket(csp->cfd);
4362 free_csp_resources(csp);
4364 csp->flags &= ~CSP_FLAG_ACTIVE;
4370 /*********************************************************************
4372 * Function : server_thread
4374 * Description : We only exist to call `serve' in a threaded environment.
4377 * 1 : data = Current client state (buffers, headers, etc...)
4379 * Returns : Always 0.
4381 *********************************************************************/
4382 static int32 server_thread(void *data)
4384 serve((struct client_state *) data);
4391 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4392 /*********************************************************************
4396 * Description : Print usage info & exit.
4398 * Parameters : Pointer to argv[0] for identifying ourselves
4402 *********************************************************************/
4403 static void usage(const char *name)
4405 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4406 "Usage: %s [--config-test] "
4409 #endif /* defined(unix) */
4412 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4413 #endif /* defined(unix) */
4414 "[--version] [configfile]\n",
4418 show_fuzz_usage(name);
4421 printf("Aborting\n");
4426 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4429 #ifdef MUTEX_LOCKS_AVAILABLE
4430 /*********************************************************************
4432 * Function : privoxy_mutex_lock
4434 * Description : Locks a mutex.
4437 * 1 : mutex = The mutex to lock.
4439 * Returns : Void. May exit in case of errors.
4441 *********************************************************************/
4442 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4444 #ifdef FEATURE_PTHREAD
4445 int err = pthread_mutex_lock(mutex);
4448 if (mutex != &log_mutex)
4450 log_error(LOG_LEVEL_FATAL,
4451 "Mutex locking failed: %s.\n", strerror(err));
4456 EnterCriticalSection(mutex);
4457 #endif /* def FEATURE_PTHREAD */
4461 /*********************************************************************
4463 * Function : privoxy_mutex_unlock
4465 * Description : Unlocks a mutex.
4468 * 1 : mutex = The mutex to unlock.
4470 * Returns : Void. May exit in case of errors.
4472 *********************************************************************/
4473 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4475 #ifdef FEATURE_PTHREAD
4476 int err = pthread_mutex_unlock(mutex);
4479 if (mutex != &log_mutex)
4481 log_error(LOG_LEVEL_FATAL,
4482 "Mutex unlocking failed: %s.\n", strerror(err));
4487 LeaveCriticalSection(mutex);
4488 #endif /* def FEATURE_PTHREAD */
4492 /*********************************************************************
4494 * Function : privoxy_mutex_init
4496 * Description : Prepares a mutex.
4499 * 1 : mutex = The mutex to initialize.
4501 * Returns : Void. May exit in case of errors.
4503 *********************************************************************/
4504 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4506 #ifdef FEATURE_PTHREAD
4507 int err = pthread_mutex_init(mutex, 0);
4510 printf("Fatal error. Mutex initialization failed: %s.\n",
4515 InitializeCriticalSection(mutex);
4516 #endif /* def FEATURE_PTHREAD */
4518 #endif /* def MUTEX_LOCKS_AVAILABLE */
4520 /*********************************************************************
4522 * Function : initialize_mutexes
4524 * Description : Prepares mutexes if mutex support is available.
4528 * Returns : Void, exits in case of errors.
4530 *********************************************************************/
4531 static void initialize_mutexes(void)
4533 #ifdef MUTEX_LOCKS_AVAILABLE
4535 * Prepare global mutex semaphores
4538 #ifdef FEATURE_HTTPS_INSPECTION
4539 privoxy_mutex_init(&certificate_mutex);
4540 privoxy_mutex_init(&rng_mutex);
4543 privoxy_mutex_init(&log_mutex);
4544 privoxy_mutex_init(&log_init_mutex);
4545 privoxy_mutex_init(&connection_reuse_mutex);
4546 #ifdef FEATURE_EXTERNAL_FILTERS
4547 privoxy_mutex_init(&external_filter_mutex);
4549 #ifdef FEATURE_CLIENT_TAGS
4550 privoxy_mutex_init(&client_tags_mutex);
4554 * XXX: The assumptions below are a bit naive
4555 * and can cause locks that aren't necessary.
4557 * For example older FreeBSD versions (< 6.x?)
4558 * have no gethostbyname_r, but gethostbyname is
4561 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4562 privoxy_mutex_init(&resolver_mutex);
4563 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4565 * XXX: should we use a single mutex for
4566 * localtime() and gmtime() as well?
4568 #ifndef HAVE_GMTIME_R
4569 privoxy_mutex_init(&gmtime_mutex);
4570 #endif /* ndef HAVE_GMTIME_R */
4572 #ifndef HAVE_LOCALTIME_R
4573 privoxy_mutex_init(&localtime_mutex);
4574 #endif /* ndef HAVE_GMTIME_R */
4576 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4577 privoxy_mutex_init(&rand_mutex);
4578 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4580 #endif /* def MUTEX_LOCKS_AVAILABLE */
4583 /*********************************************************************
4587 * Description : Load the config file and start the listen loop.
4588 * This function is a lot more *sane* with the `load_config'
4589 * and `listen_loop' functions; although it stills does
4590 * a *little* too much for my taste.
4593 * 1 : argc = Number of parameters (including $0).
4594 * 2 : argv = Array of (char *)'s to the parameters.
4596 * Returns : 1 if : can't open config file, unrecognized directive,
4597 * stats requested in multi-thread mode, can't open the
4598 * log file, can't open the jar file, listen port is invalid,
4599 * any load fails, and can't bind port.
4601 * Else main never returns, the process must be signaled
4602 * to terminate execution. Or, on Windows, use the
4603 * "File", "Exit" menu option.
4605 *********************************************************************/
4607 int real_main(int argc, char **argv)
4609 int main(int argc, char **argv)
4613 int do_config_test = 0;
4614 #ifndef HAVE_ARC4RANDOM
4615 unsigned int random_seed;
4618 struct passwd *pw = NULL;
4619 struct group *grp = NULL;
4621 char *pre_chroot_nslookup_to_load_resolver = NULL;
4624 char *fuzz_input_type = NULL;
4625 char *fuzz_input_file = NULL;
4632 #if !defined(_WIN32)
4639 /* Prepare mutexes if supported and necessary. */
4640 initialize_mutexes();
4642 /* Enable logging until further notice. */
4646 * Parse the command line arguments
4648 * XXX: simply printing usage information in case of
4649 * invalid arguments isn't particularly user friendly.
4651 while (++argc_pos < argc)
4654 /* Check to see if the service must be installed or uninstalled */
4655 if (strncmp(argv[argc_pos], "--install", 9) == 0)
4657 const char *pName = argv[argc_pos] + 9;
4660 exit((install_service(pName)) ? 0 : 1);
4662 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4664 const char *pName = argv[argc_pos] + 11;
4667 exit((uninstall_service(pName)) ? 0 : 1);
4669 else if (strcmp(argv[argc_pos], "--service") == 0)
4671 bRunAsService = TRUE;
4672 w32_set_service_cwd();
4673 atexit(w32_service_exit_notify);
4676 #endif /* defined(_WIN32) */
4679 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4681 if (strcmp(argv[argc_pos], "--help") == 0)
4686 else if (strcmp(argv[argc_pos], "--version") == 0)
4688 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4694 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4696 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4700 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4702 if (++argc_pos == argc) usage(argv[0]);
4703 pidfile = strdup_or_die(argv[argc_pos]);
4706 else if (strcmp(argv[argc_pos], "--user") == 0)
4711 if (++argc_pos == argc) usage(argv[argc_pos]);
4713 user_arg = strdup_or_die(argv[argc_pos]);
4714 group_name = strchr(user_arg, '.');
4715 if (NULL != group_name)
4717 /* Nul-terminate the user name */
4720 /* Skip the former delimiter to actually reach the group name */
4723 grp = getgrnam(group_name);
4726 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4729 pw = getpwnam(user_arg);
4732 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4738 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4740 if (++argc_pos == argc) usage(argv[0]);
4741 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4744 else if (strcmp(argv[argc_pos], "--chroot") == 0)
4748 #endif /* defined(unix) */
4750 else if (strcmp(argv[argc_pos], "--config-test") == 0)
4755 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4758 if (argc < argc_pos + 2) usage(argv[0]);
4759 fuzz_input_type = argv[argc_pos];
4761 fuzz_input_file = argv[argc_pos];
4763 else if (strcmp(argv[argc_pos], "--stfu") == 0)
4765 set_debug_level(LOG_LEVEL_STFU);
4768 else if (argc_pos + 1 != argc)
4771 * This is neither the last command line
4772 * option, nor was it recognized before,
4773 * therefore it must be invalid.
4779 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4781 configfile = argv[argc_pos];
4784 } /* -END- while (more arguments) */
4786 show_version(Argv[0]);
4789 if (*configfile != '/')
4791 char cwd[BUFFER_SIZE];
4793 size_t abs_file_size;
4795 /* make config-filename absolute here */
4796 if (NULL == getcwd(cwd, sizeof(cwd)))
4798 perror("failed to get current working directory");
4802 basedir = strdup_or_die(cwd);
4804 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4805 abs_file = malloc_or_die(abs_file_size);
4806 strlcpy(abs_file, basedir, abs_file_size);
4807 strlcat(abs_file, "/", abs_file_size);
4808 strlcat(abs_file, configfile, abs_file_size);
4809 configfile = abs_file;
4811 #endif /* defined unix */
4815 clients->next = NULL;
4817 /* XXX: factor out initialising after the next stable release. */
4822 #ifndef HAVE_ARC4RANDOM
4823 random_seed = (unsigned int)time(NULL);
4825 srandom(random_seed);
4828 #endif /* ifdef HAVE_RANDOM */
4829 #endif /* ifndef HAVE_ARC4RANDOM */
4832 * Unix signal handling
4834 * Catch the abort, interrupt and terminate signals for a graceful exit
4835 * Catch the hangup signal so the errlog can be reopened.
4837 * Ignore the broken pipe signal as connection failures
4838 * are handled when and where they occur without relying
4841 #if !defined(_WIN32) && !defined(__OS2__)
4844 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
4846 for (idx = 0; idx < SZ(catched_signals); idx++)
4848 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
4849 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
4851 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
4852 #endif /* ifdef sun */
4854 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
4858 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4860 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
4864 #else /* ifdef _WIN32 */
4865 # ifdef _WIN_CONSOLE
4867 * We *are* in a windows console app.
4868 * Print a verbose messages about FAQ's and such
4870 printf("%s", win32_blurb);
4871 # endif /* def _WIN_CONSOLE */
4872 #endif /* def _WIN32 */
4875 if (fuzz_input_type != NULL)
4877 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
4879 log_error(LOG_LEVEL_FATAL,
4880 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
4881 "Various data structures are static which is unsafe when using threads.");
4886 exit(NULL == load_config());
4889 /* Initialize the CGI subsystem */
4890 cgi_init_error_messages();
4893 * If running on unix and without the --no-daemon
4894 * option, become a daemon. I.e. fork, detach
4895 * from tty and get process group leadership
4904 if (pid < 0) /* error */
4909 else if (pid != 0) /* parent */
4914 * must check for errors
4915 * child died due to missing files aso
4918 wpid = waitpid(pid, &status, WNOHANG);
4930 * stderr (fd 2) will be closed later on,
4931 * when the config file has been parsed.
4937 * Reserve fd 0 and 1 to prevent abort() and friends
4938 * from sending stuff to the clients or servers.
4940 fd = open("/dev/null", O_RDONLY);
4943 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4947 if (dup2(fd, 0) == -1)
4949 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
4953 fd = open("/dev/null", O_WRONLY);
4956 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4960 if (dup2(fd, 1) == -1)
4962 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
4967 #ifdef FEATURE_EXTERNAL_FILTERS
4968 for (fd = 0; fd < 3; fd++)
4970 mark_socket_for_close_on_execute(fd);
4976 } /* -END- if (daemon_mode) */
4979 * As soon as we have written the PID file, we can switch
4980 * to the user and group ID indicated by the --user option
4982 if (pidfile != NULL)
4984 write_pid_file(pidfile);
4988 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
4990 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
4994 if (setgroups(1, &grp->gr_gid))
4996 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
4999 else if (initgroups(pw->pw_name, pw->pw_gid))
5001 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5007 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5009 /* Read the time zone file from /etc before doing chroot. */
5011 if (NULL != pre_chroot_nslookup_to_load_resolver
5012 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5014 /* Initialize resolver library. */
5015 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5017 if (chroot(pw->pw_dir) < 0)
5019 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5023 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5026 if (setuid(pw->pw_uid))
5028 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5032 char putenv_dummy[64];
5034 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5035 if (putenv(putenv_dummy) != 0)
5037 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5040 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5041 if (putenv(putenv_dummy) != 0)
5043 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5049 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5052 #endif /* defined unix */
5055 /* This will be FALSE unless the command line specified --service
5059 /* Yup, so now we must attempt to establish a connection
5060 * with the service dispatcher. This will only work if this
5061 * process was launched by the service control manager to
5062 * actually run as a service. If this isn't the case, i've
5063 * known it take around 30 seconds or so for the call to return.
5066 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5067 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5069 /* Service has run, and at this point is now being stopped, so just return */
5074 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5076 /* An error occurred. Usually it's because --service was wrongly specified
5077 * and we were unable to connect to the Service Control Dispatcher because
5078 * it wasn't expecting us and is therefore not listening.
5080 * For now, just continue below to call the listen_loop function.
5083 #endif /* def _WIN32 */
5093 /*********************************************************************
5095 * Function : bind_port_helper
5097 * Description : Bind the listen port. Handles logging, and aborts
5101 * 1 : haddr = Host address to bind to. Use NULL to bind to
5103 * 2 : hport = Specifies port to bind to.
5104 * 3 : backlog = Listen backlog.
5106 * Returns : Port that was opened.
5108 *********************************************************************/
5109 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5114 result = bind_port(haddr, hport, backlog, &bfd);
5118 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5122 log_error(LOG_LEVEL_FATAL,
5123 "can't bind to %s:%d: There may be another Privoxy "
5124 "or some other proxy running on port %d",
5125 bind_address, hport, hport);
5128 log_error(LOG_LEVEL_FATAL,
5129 "can't bind to %s:%d: The hostname is not resolvable",
5130 bind_address, hport);
5133 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5134 bind_address, hport);
5137 /* shouldn't get here */
5138 return JB_INVALID_SOCKET;
5143 if (bfd >= FD_SETSIZE)
5145 log_error(LOG_LEVEL_FATAL,
5146 "Bind socket number too high to use select(): %d >= %d",
5154 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5159 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5167 /*********************************************************************
5169 * Function : bind_ports_helper
5171 * Description : Bind the listen ports. Handles logging, and aborts
5175 * 1 : config = Privoxy configuration. Specifies ports
5177 * 2 : sockets = Preallocated array of opened sockets
5178 * corresponding to specification in config.
5179 * All non-opened sockets will be set to
5180 * JB_INVALID_SOCKET.
5182 * Returns : Nothing. Inspect sockets argument.
5184 *********************************************************************/
5185 static void bind_ports_helper(struct configuration_spec * config,
5186 jb_socket sockets[])
5190 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5192 if (config->hport[i])
5194 sockets[i] = bind_port_helper(config->haddr[i],
5195 config->hport[i], config->listen_backlog);
5196 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5197 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5199 struct accept_filter_arg af_options;
5200 bzero(&af_options, sizeof(af_options));
5201 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5202 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5203 sizeof(af_options)))
5205 log_error(LOG_LEVEL_ERROR,
5206 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5213 sockets[i] = JB_INVALID_SOCKET;
5216 config->need_bind = 0;
5220 /*********************************************************************
5222 * Function : close_ports_helper
5224 * Description : Close listenings ports.
5227 * 1 : sockets = Array of opened and non-opened sockets to
5228 * close. All sockets will be set to
5229 * JB_INVALID_SOCKET.
5231 * Returns : Nothing.
5233 *********************************************************************/
5234 static void close_ports_helper(jb_socket sockets[])
5238 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5240 if (JB_INVALID_SOCKET != sockets[i])
5242 close_socket(sockets[i]);
5244 sockets[i] = JB_INVALID_SOCKET;
5250 /* Without this simple workaround we get this compiler warning from _beginthread
5251 * warning C4028: formal parameter 1 different from declaration
5253 void w32_service_listen_loop(void *p)
5257 #endif /* def _WIN32 */
5260 /*********************************************************************
5262 * Function : listen_loop
5264 * Description : bind the listen port and enter a "FOREVER" listening loop.
5270 *********************************************************************/
5271 static void listen_loop(void)
5273 struct client_states *csp_list = NULL;
5274 struct client_state *csp = NULL;
5275 jb_socket bfds[MAX_LISTENING_SOCKETS];
5276 struct configuration_spec *config;
5277 unsigned int active_threads = 0;
5278 #if defined(FEATURE_PTHREAD)
5279 pthread_attr_t attrs;
5281 pthread_attr_init(&attrs);
5282 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5285 config = load_config();
5287 #ifdef FEATURE_CONNECTION_SHARING
5289 * XXX: Should be relocated once it no
5290 * longer needs to emit log messages.
5292 initialize_reusable_connections();
5293 #endif /* def FEATURE_CONNECTION_SHARING */
5295 bind_ports_helper(config, bfds);
5297 #ifdef FEATURE_GRACEFUL_TERMINATION
5298 while (!g_terminate)
5303 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
5304 while (waitpid(-1, NULL, WNOHANG) > 0)
5306 /* zombie children */
5308 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5311 * Free data that was used by died threads
5313 active_threads = sweep();
5317 * Re-open the errlog after HUP signal
5319 if (received_hup_signal)
5321 if (NULL != config->logfile)
5323 init_error_log(Argv[0], config->logfile);
5325 received_hup_signal = 0;
5329 csp_list = zalloc_or_die(sizeof(*csp_list));
5330 csp = &csp_list->csp;
5332 log_error(LOG_LEVEL_CONNECT,
5333 "Waiting for the next client connection. Currently active threads: %d",
5337 * This config may be outdated, but for accept_connection()
5338 * it's fresh enough.
5340 csp->config = config;
5342 if (!accept_connection(csp, bfds))
5344 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5349 csp->flags |= CSP_FLAG_ACTIVE;
5350 csp->server_connection.sfd = JB_INVALID_SOCKET;
5352 csp->config = config = load_config();
5354 if (config->need_bind)
5357 * Since we were listening to the "old port", we will not see
5358 * a "listen" param change until the next request. So, at
5359 * least 1 more request must be made for us to find the new
5360 * setting. I am simply closing the old socket and binding the
5363 * Which-ever is correct, we will serve 1 more page via the
5364 * old settings. This should probably be a "show-status"
5365 * request. This should not be a so common of an operation
5366 * that this will hurt people's feelings.
5369 close_ports_helper(bfds);
5371 bind_ports_helper(config, bfds);
5374 #ifdef FEATURE_TOGGLE
5375 if (global_toggle_state)
5376 #endif /* def FEATURE_TOGGLE */
5378 csp->flags |= CSP_FLAG_TOGGLED_ON;
5381 if (run_loader(csp))
5383 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5384 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5388 if (block_acl(NULL,csp))
5390 log_error(LOG_LEVEL_CONNECT,
5391 "Connection from %s on %s (socket %d) dropped due to ACL",
5392 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5393 close_socket(csp->cfd);
5394 freez(csp->ip_addr_str);
5395 freez(csp->listen_addr_str);
5399 #endif /* def FEATURE_ACL */
5401 if ((0 != config->max_client_connections)
5402 && (active_threads >= config->max_client_connections))
5404 log_error(LOG_LEVEL_CONNECT,
5405 "Rejecting connection from %s. Maximum number of connections reached.",
5407 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5408 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5409 close_socket(csp->cfd);
5410 freez(csp->ip_addr_str);
5411 freez(csp->listen_addr_str);
5416 /* add it to the list of clients */
5417 csp_list->next = clients->next;
5418 clients->next = csp_list;
5420 if (config->multi_threaded)
5424 /* this is a switch () statement in the C preprocessor - ugh */
5425 #undef SELECTED_ONE_OPTION
5427 /* Use Pthreads in preference to native code */
5428 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5429 #define SELECTED_ONE_OPTION
5431 pthread_t the_thread;
5433 errno = pthread_create(&the_thread, &attrs,
5434 (void * (*)(void *))serve, csp);
5435 child_id = errno ? -1 : 0;
5439 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5440 #define SELECTED_ONE_OPTION
5441 child_id = _beginthread(
5442 (void (*)(void *))serve,
5447 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
5448 #define SELECTED_ONE_OPTION
5449 child_id = _beginthread(
5450 (void(* _Optlink)(void*))serve,
5456 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5457 #define SELECTED_ONE_OPTION
5459 thread_id tid = spawn_thread
5460 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5462 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5464 child_id = (int) tid;
5473 #if !defined(SELECTED_ONE_OPTION)
5476 /* This block is only needed when using fork().
5477 * When using threads, the server thread was
5478 * created and run by the call to _beginthread().
5480 if (child_id == 0) /* child */
5483 #ifdef FEATURE_TOGGLE
5484 int inherited_toggle_state = global_toggle_state;
5485 #endif /* def FEATURE_TOGGLE */
5490 * If we've been toggled or we've blocked the request, tell Mom
5493 #ifdef FEATURE_TOGGLE
5494 if (inherited_toggle_state != global_toggle_state)
5496 rc |= RC_FLAG_TOGGLED;
5498 #endif /* def FEATURE_TOGGLE */
5500 #ifdef FEATURE_STATISTICS
5501 if (csp->flags & CSP_FLAG_REJECTED)
5503 rc |= RC_FLAG_BLOCKED;
5505 #endif /* ndef FEATURE_STATISTICS */
5509 else if (child_id > 0) /* parent */
5511 /* in a fork()'d environment, the parent's
5512 * copy of the client socket and the CSP
5516 #if !defined(_WIN32) && !defined(__CYGWIN__)
5518 wait(&child_status);
5521 * Evaluate child's return code: If the child has
5522 * - been toggled, toggle ourselves
5523 * - blocked its request, bump up the stats counter
5526 #ifdef FEATURE_TOGGLE
5527 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5529 global_toggle_state = !global_toggle_state;
5531 #endif /* def FEATURE_TOGGLE */
5533 #ifdef FEATURE_STATISTICS
5535 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5539 #endif /* def FEATURE_STATISTICS */
5541 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5542 close_socket(csp->cfd);
5543 csp->flags &= ~CSP_FLAG_ACTIVE;
5547 #undef SELECTED_ONE_OPTION
5548 /* end of cpp switch () */
5553 * Spawning the child failed, assume it's because
5554 * there are too many children running already.
5555 * XXX: If you assume ...
5557 log_error(LOG_LEVEL_ERROR,
5558 "Unable to take any additional connections: %E. Active threads: %d",
5560 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5561 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5562 close_socket(csp->cfd);
5563 csp->flags &= ~CSP_FLAG_ACTIVE;
5572 #if defined(FEATURE_PTHREAD)
5573 pthread_attr_destroy(&attrs);
5576 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5578 #ifdef FEATURE_HTTPS_INSPECTION
5579 /* Clean up. Aim: free all memory (no leaks) */
5580 if (rng_seeded == 1)
5582 mbedtls_ctr_drbg_free(&ctr_drbg);
5583 mbedtls_entropy_free(&entropy);
5587 #ifdef FEATURE_GRACEFUL_TERMINATION
5589 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
5591 unload_current_config_file();
5592 unload_current_actions_file();
5593 unload_current_re_filterfile();
5594 #ifdef FEATURE_TRUST
5595 unload_current_trust_file();
5598 if (config->multi_threaded)
5605 } while ((clients->next != NULL) && (--i > 0));
5609 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5619 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5620 /* Cleanup - remove taskbar icon etc. */
5625 #endif /* FEATURE_GRACEFUL_TERMINATION */