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 */
66 # include <sys/wait.h>
67 # include <sys/time.h>
68 # include <sys/stat.h>
69 # include <sys/ioctl.h>
72 #include <sys/termios.h>
83 # include <socket.h> /* BeOS has select() for sockets only. */
84 # include <OS.h> /* declarations for threads and stuff. */
92 #endif /* def __GLIBC__ */
97 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
98 #endif /* HAVE_POLL */
105 #ifdef FEATURE_HTTPS_INSPECTION
111 #include "miscutil.h"
113 #include "jbsockets.h"
118 #include "urlmatch.h"
119 #ifdef FEATURE_CLIENT_TAGS
120 #include "client-tags.h"
124 struct client_states clients[1];
125 struct file_list files[1];
127 #ifdef FEATURE_STATISTICS
128 int urls_read = 0; /* total nr of urls read inc rejected */
129 int urls_rejected = 0; /* total nr of urls rejected */
130 #endif /* def FEATURE_STATISTICS */
132 #ifdef FEATURE_GRACEFUL_TERMINATION
137 static void sig_handler(int the_signal);
139 static int client_protocol_is_unsupported(struct client_state *csp, char *req);
140 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
141 static jb_err get_server_headers(struct client_state *csp);
142 static const char *crunch_reason(const struct http_response *rsp);
143 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
144 static char *get_request_line(struct client_state *csp);
145 static jb_err receive_client_request(struct client_state *csp);
146 static jb_err parse_client_request(struct client_state *csp);
147 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
148 static jb_err change_request_destination(struct client_state *csp);
149 static void handle_established_connection(struct client_state *csp);
150 static void chat(struct client_state *csp);
151 static void serve(struct client_state *csp);
152 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
153 static void usage(const char *myname);
155 static void initialize_mutexes(void);
156 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
157 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
158 static void close_ports_helper(jb_socket sockets[]);
159 static void listen_loop(void);
160 static void serve(struct client_state *csp);
163 static int32 server_thread(void *data);
164 #endif /* def __BEOS__ */
167 #define sleep(N) Sleep(((N) * 1000))
171 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
172 void show_fuzz_usage(const char *name);
175 #ifdef MUTEX_LOCKS_AVAILABLE
177 * XXX: Does the locking stuff really belong in this file?
179 privoxy_mutex_t log_mutex;
180 privoxy_mutex_t log_init_mutex;
181 privoxy_mutex_t connection_reuse_mutex;
183 #ifdef FEATURE_HTTPS_INSPECTION
184 privoxy_mutex_t certificate_mutex;
185 privoxy_mutex_t ssl_init_mutex;
188 #ifdef FEATURE_EXTERNAL_FILTERS
189 privoxy_mutex_t external_filter_mutex;
191 #ifdef FEATURE_CLIENT_TAGS
192 privoxy_mutex_t client_tags_mutex;
194 #ifdef FEATURE_EXTENDED_STATISTICS
195 privoxy_mutex_t filter_statistics_mutex;
196 privoxy_mutex_t block_statistics_mutex;
199 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
200 privoxy_mutex_t resolver_mutex;
201 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
203 #ifndef HAVE_GMTIME_R
204 privoxy_mutex_t gmtime_mutex;
205 #endif /* ndef HAVE_GMTIME_R */
207 #ifndef HAVE_LOCALTIME_R
208 privoxy_mutex_t localtime_mutex;
209 #endif /* ndef HAVE_GMTIME_R */
211 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
212 privoxy_mutex_t rand_mutex;
213 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
215 #endif /* def MUTEX_LOCKS_AVAILABLE */
218 const char *basedir = NULL;
219 const char *pidfile = NULL;
220 static int received_hup_signal = 0;
221 #endif /* defined unix */
223 /* HTTP snipplets. */
224 static const char CSUCCEED[] =
225 "HTTP/1.1 200 Connection established\r\n\r\n";
227 static const char CHEADER[] =
228 "HTTP/1.1 400 Invalid header received from client\r\n"
229 "Content-Type: text/plain\r\n"
230 "Connection: close\r\n\r\n"
231 "Invalid header received from client.\r\n";
233 static const char FTP_RESPONSE[] =
234 "HTTP/1.1 400 Invalid request received from client\r\n"
235 "Content-Type: text/plain\r\n"
236 "Connection: close\r\n\r\n"
237 "Invalid request. Privoxy doesn't support FTP.\r\n";
239 static const char GOPHER_RESPONSE[] =
240 "HTTP/1.1 400 Invalid request received from client\r\n"
241 "Content-Type: text/plain\r\n"
242 "Connection: close\r\n\r\n"
243 "Invalid request. Privoxy doesn't support gopher.\r\n";
245 /* XXX: should be a template */
246 static const char MISSING_DESTINATION_RESPONSE[] =
247 "HTTP/1.1 400 Bad request received from client\r\n"
248 "Content-Type: text/plain\r\n"
249 "Connection: close\r\n\r\n"
250 "Bad request. Privoxy was unable to extract the destination.\r\n";
252 /* XXX: should be a template */
253 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
254 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
255 "Content-Type: text/plain\r\n"
256 "Connection: close\r\n\r\n"
257 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
259 /* XXX: should be a template */
260 static const char MESSED_UP_REQUEST_RESPONSE[] =
261 "HTTP/1.1 400 Malformed request after rewriting\r\n"
262 "Content-Type: text/plain\r\n"
263 "Connection: close\r\n\r\n"
264 "Bad request. Messed up with header filters.\r\n";
266 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
267 "HTTP/1.1 503 Too many open connections\r\n"
268 "Content-Type: text/plain\r\n"
269 "Connection: close\r\n\r\n"
270 "Maximum number of open connections reached.\r\n";
272 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
273 "HTTP/1.1 504 Connection timeout\r\n"
274 "Content-Type: text/plain\r\n"
275 "Connection: close\r\n\r\n"
276 "The connection timed out because the client request didn't arrive in time.\r\n";
278 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
279 "HTTP/1.1 400 Failed reading client body\r\n"
280 "Content-Type: text/plain\r\n"
281 "Connection: close\r\n\r\n"
282 "Failed parsing or buffering the chunk-encoded client body.\r\n";
284 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
285 "HTTP/1.1 417 Expecting too much\r\n"
286 "Content-Type: text/plain\r\n"
287 "Connection: close\r\n\r\n"
288 "Privoxy detected an unsupported Expect header value.\r\n";
290 /* A function to crunch a response */
291 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
293 /* Crunch function flags */
294 #define CF_NO_FLAGS 0
295 /* Cruncher applies to forced requests as well */
296 #define CF_IGNORE_FORCE 1
297 /* Crunched requests are counted for the block statistics */
298 #define CF_COUNT_AS_REJECT 2
300 /* A crunch function and its flags */
303 const crunch_func_ptr cruncher;
307 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
309 /* Complete list of cruncher functions */
310 static const struct cruncher crunchers_all[] = {
311 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
312 { block_url, CF_COUNT_AS_REJECT },
314 { trust_url, CF_COUNT_AS_REJECT },
315 #endif /* def FEATURE_TRUST */
316 { redirect_url, CF_NO_FLAGS },
317 { dispatch_cgi, CF_IGNORE_FORCE},
321 /* Light version, used after tags are applied */
322 static const struct cruncher crunchers_light[] = {
323 { block_url, CF_COUNT_AS_REJECT },
324 { redirect_url, CF_NO_FLAGS },
330 * XXX: Don't we really mean
337 /*********************************************************************
339 * Function : sig_handler
341 * Description : Signal handler for different signals.
342 * Exit gracefully on TERM and INT
343 * or set a flag that will cause the errlog
344 * to be reopened by the main thread on HUP.
347 * 1 : the_signal = the signal cause this function to call
351 *********************************************************************/
352 static void sig_handler(int the_signal)
358 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
370 received_hup_signal = 1;
376 * We shouldn't be here, unless we catch signals
377 * in main() that we can't handle here!
379 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
387 /*********************************************************************
389 * Function : get_write_delay
391 * Description : Parse the delay-response parameter.
394 * 1 : csp = Current client state (buffers, headers, etc...)
396 * Returns : Number of milliseconds to delay writes.
398 *********************************************************************/
399 static unsigned int get_write_delay(const struct client_state *csp)
405 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
409 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
411 delay = (unsigned)strtol(newval, &endptr, 0);
414 log_error(LOG_LEVEL_FATAL,
415 "Invalid delay-response{} parameter: '%s'", newval);
423 /*********************************************************************
425 * Function : client_protocol_is_unsupported
427 * Description : Checks if the client used a known unsupported
428 * protocol and deals with it by sending an error
432 * 1 : csp = Current client state (buffers, headers, etc...)
433 * 2 : req = the first request line send by the client
435 * Returns : TRUE if an error response has been generated, or
436 * FALSE if the request doesn't look invalid.
438 *********************************************************************/
439 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
442 * If it's a FTP or gopher request, we don't support it.
444 * These checks are better than nothing, but they might
445 * not work in all configurations and some clients might
446 * have problems digesting the answer.
448 * They should, however, never cause more problems than
449 * Privoxy's old behaviour (returning the misleading HTML
452 * "Could not resolve http://(ftp|gopher)://example.org").
454 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
456 const char *response = NULL;
457 const char *protocol = NULL;
459 if (!strncmpic(req, "GET ftp://", 10))
461 response = FTP_RESPONSE;
466 response = GOPHER_RESPONSE;
469 log_error(LOG_LEVEL_ERROR,
470 "%s tried to use Privoxy as %s proxy: %s",
471 csp->ip_addr_str, protocol, req);
472 log_error(LOG_LEVEL_CLF,
473 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
476 #ifdef FEATURE_HTTPS_INSPECTION
477 if (client_use_ssl(csp))
479 ssl_send_data_delayed(&(csp->ssl_client_attr),
480 (const unsigned char *)response, strlen(response),
481 get_write_delay(csp));
486 write_socket_delayed(csp->cfd, response, strlen(response),
487 get_write_delay(csp));
497 /*********************************************************************
499 * Function : client_has_unsupported_expectations
501 * Description : Checks if the client used an unsupported expectation
502 * in which case an error message is delivered.
505 * 1 : csp = Current client state (buffers, headers, etc...)
507 * Returns : TRUE if an error response has been generated, or
508 * FALSE if the request doesn't look invalid.
510 *********************************************************************/
511 static int client_has_unsupported_expectations(const struct client_state *csp)
513 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
515 log_error(LOG_LEVEL_ERROR,
516 "Rejecting request from client %s with unsupported Expect header value",
518 log_error(LOG_LEVEL_CLF,
519 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
520 write_socket_delayed(csp->cfd,
521 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
522 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
523 get_write_delay(csp));
533 /*********************************************************************
535 * Function : get_request_destination_elsewhere
537 * Description : If the client's request was redirected into
538 * Privoxy without the client's knowledge,
539 * the request line lacks the destination host.
541 * This function tries to get it elsewhere,
542 * provided accept-intercepted-requests is enabled.
544 * "Elsewhere" currently only means "Host: header",
545 * but in the future we may ask the redirecting
546 * packet filter to look the destination up.
548 * If the destination stays unknown, an error
549 * response is send to the client and headers
550 * are freed so that chat() can return directly.
553 * 1 : csp = Current client state (buffers, headers, etc...)
554 * 2 : headers = a header list
556 * Returns : JB_ERR_OK if the destination is now known, or
557 * JB_ERR_PARSE if it isn't.
559 *********************************************************************/
560 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
562 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
564 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
565 " Privoxy isn't configured to accept intercepted requests.",
566 csp->ip_addr_str, csp->http->cmd);
567 /* XXX: Use correct size */
568 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
569 csp->ip_addr_str, csp->http->cmd);
571 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
572 get_write_delay(csp));
573 destroy_list(headers);
577 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
579 /* Split the domain we just got for pattern matching */
580 init_domain_components(csp->http);
586 /* We can't work without destination. Go spread the news.*/
588 /* XXX: Use correct size */
589 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
590 csp->ip_addr_str, csp->http->cmd);
591 log_error(LOG_LEVEL_ERROR,
592 "Privoxy was unable to get the destination for %s's request: %s",
593 csp->ip_addr_str, csp->http->cmd);
595 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
596 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
597 destroy_list(headers);
602 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
603 * to get the destination IP address, use it as host directly
604 * or do a reverse DNS lookup first.
609 /*********************************************************************
611 * Function : get_server_headers
613 * Description : Parses server headers in iob and fills them
614 * into csp->headers so that they can later be
618 * 1 : csp = Current client state (buffers, headers, etc...)
620 * Returns : JB_ERR_OK if everything went fine, or
621 * JB_ERR_PARSE if the headers were incomplete.
623 *********************************************************************/
624 static jb_err get_server_headers(struct client_state *csp)
626 int continue_hack_in_da_house = 0;
629 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
634 * continue hack in da house. Ignore the ending of
635 * this head and continue enlisting header lines.
636 * The reason is described below.
638 enlist(csp->headers, "");
639 continue_hack_in_da_house = 0;
642 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
645 * It's a bodyless continue response, don't
646 * stop header parsing after reaching its end.
648 * As a result Privoxy will concatenate the
649 * next response's head and parse and deliver
650 * the headers as if they belonged to one request.
652 * The client will separate them because of the
653 * empty line between them.
655 * XXX: What we're doing here is clearly against
656 * the intended purpose of the continue header,
657 * and under some conditions (HTTP/1.0 client request)
658 * it's a standard violation.
660 * Anyway, "sort of against the spec" is preferable
661 * to "always getting confused by Continue responses"
662 * (Privoxy's behaviour before this hack was added)
664 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
665 continue_hack_in_da_house = 1;
667 else if (*header == '\0')
670 * If the header is empty, but the Continue hack
671 * isn't active, we can assume that we reached the
672 * end of the buffer before we hit the end of the
675 * Inform the caller an let it decide how to handle it.
680 if (JB_ERR_MEMORY == enlist(csp->headers, header))
683 * XXX: Should we quit the request and return a
684 * out of memory error page instead?
686 log_error(LOG_LEVEL_ERROR,
687 "Out of memory while enlisting server headers. %s lost.",
697 /*********************************************************************
699 * Function : crunch_reason
701 * Description : Translates the crunch reason code into a string.
704 * 1 : rsp = a http_response
706 * Returns : A string with the crunch reason or an error description.
708 *********************************************************************/
709 static const char *crunch_reason(const struct http_response *rsp)
711 char * reason = NULL;
716 return "Internal error while searching for crunch reason";
719 switch (rsp->crunch_reason)
722 reason = "Unsupported HTTP feature";
728 reason = "Untrusted";
731 reason = "Redirected";
737 reason = "DNS failure";
739 case FORWARDING_FAILED:
740 reason = "Forwarding failed";
743 reason = "Connection failure";
746 reason = "Out of memory (may mask other reasons)";
748 case CONNECTION_TIMEOUT:
749 reason = "Connection timeout";
752 reason = "No server data received";
755 reason = "No reason recorded";
763 /*********************************************************************
765 * Function : log_applied_actions
767 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
771 * 1 : actions = Current action spec to log
775 *********************************************************************/
776 static void log_applied_actions(const struct current_action_spec *actions)
779 * The conversion to text requires lots of memory allocations so
780 * we only do the conversion if the user is actually interested.
782 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
784 char *actions_as_text = actions_to_line_of_text(actions);
785 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
786 freez(actions_as_text);
791 /*********************************************************************
793 * Function : send_crunch_response
795 * Description : Delivers already prepared response for
796 * intercepted requests, logs the interception
797 * and frees the response.
800 * 1 : csp = Current client state (buffers, headers, etc...)
801 * 2 : rsp = Fully prepared response. Will be freed on exit.
805 *********************************************************************/
806 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
808 const struct http_request *http = csp->http;
812 assert(rsp->head != NULL);
816 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
820 * Extract the status code from the actual head
821 * that will be send to the client. It is the only
822 * way to get it right for all requests, including
823 * the fixed ones for out-of-memory problems.
825 * A head starts like this: 'HTTP/1.1 200...'
829 status_code[0] = rsp->head[9];
830 status_code[1] = rsp->head[10];
831 status_code[2] = rsp->head[11];
832 status_code[3] = '\0';
834 /* Log that the request was crunched and why. */
835 log_applied_actions(csp->action);
836 #ifdef FEATURE_HTTPS_INSPECTION
837 if (client_use_ssl(csp))
839 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
840 http->hostport, http->path);
841 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
842 csp->ip_addr_str, http->gpc, http->hostport, http->path,
843 http->version, status_code, rsp->content_length);
848 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
849 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
850 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
852 /* Write the answer to the client */
853 #ifdef FEATURE_HTTPS_INSPECTION
854 if (client_use_ssl(csp))
856 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
857 (const unsigned char *)rsp->head, rsp->head_length,
858 get_write_delay(csp)) < 0)
859 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
860 (const unsigned char *)rsp->body, rsp->content_length,
861 get_write_delay(csp)) < 0))
863 /* There is nothing we can do about it. */
864 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
865 "for https://%s%s through client socket %d using TLS/SSL",
866 http->hostport, http->url, csp->cfd);
872 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
873 get_write_delay(csp))
874 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
875 get_write_delay(csp)))
877 /* There is nothing we can do about it. */
878 log_error(LOG_LEVEL_CONNECT,
879 "Couldn't deliver the error message for %s through client socket %d: %E",
880 http->url, csp->cfd);
884 /* Clean up and return */
885 if (cgi_error_memory() != rsp)
887 free_http_response(rsp);
893 /*********************************************************************
895 * Function : crunch_response_triggered
897 * Description : Checks if the request has to be crunched,
898 * and delivers the crunch response if necessary.
901 * 1 : csp = Current client state (buffers, headers, etc...)
902 * 2 : crunchers = list of cruncher functions to run
904 * Returns : TRUE if the request was answered with a crunch response
907 *********************************************************************/
908 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
910 struct http_response *rsp = NULL;
911 const struct cruncher *c;
914 * If CGI request crunching is disabled,
915 * check the CGI dispatcher out of order to
916 * prevent unintentional blocks or redirects.
918 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
919 && (NULL != (rsp = dispatch_cgi(csp))))
921 /* Deliver, log and free the interception response. */
922 send_crunch_response(csp, rsp);
923 csp->flags |= CSP_FLAG_CRUNCHED;
927 for (c = crunchers; c->cruncher != NULL; c++)
930 * Check the cruncher if either Privoxy is toggled
931 * on and the request isn't forced, or if the cruncher
932 * applies to forced requests as well.
934 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
935 !(csp->flags & CSP_FLAG_FORCED)) ||
936 (c->flags & CF_IGNORE_FORCE))
938 rsp = c->cruncher(csp);
941 /* Deliver, log and free the interception response. */
942 send_crunch_response(csp, rsp);
943 csp->flags |= CSP_FLAG_CRUNCHED;
944 #ifdef FEATURE_STATISTICS
945 if (c->flags & CF_COUNT_AS_REJECT)
947 csp->flags |= CSP_FLAG_REJECTED;
949 #endif /* def FEATURE_STATISTICS */
960 /*********************************************************************
962 * Function : build_request_line
964 * Description : Builds the HTTP request line.
966 * If a HTTP forwarder is used it expects the whole URL,
967 * web servers only get the path.
970 * 1 : csp = Current client state (buffers, headers, etc...)
971 * 2 : fwd = The forwarding spec used for the request
972 * XXX: Should use http->fwd instead.
973 * 3 : request_line = The old request line which will be replaced.
975 * Returns : Nothing. Terminates in case of memory problems.
977 *********************************************************************/
978 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
980 struct http_request *http = csp->http;
983 * Downgrade http version from 1.1 to 1.0
984 * if +downgrade action applies.
986 if ((csp->action->flags & ACTION_DOWNGRADE)
987 && (!strcmpic(http->version, "HTTP/1.1")))
989 freez(http->version);
990 http->version = strdup_or_die("HTTP/1.0");
994 * Rebuild the request line.
996 freez(*request_line);
997 *request_line = strdup(http->gpc);
998 string_append(request_line, " ");
1000 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1002 string_append(request_line, http->url);
1006 string_append(request_line, http->path);
1008 string_append(request_line, " ");
1009 string_append(request_line, http->version);
1011 if (*request_line == NULL)
1013 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1015 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1019 /*********************************************************************
1021 * Function : change_request_destination
1023 * Description : Parse a (rewritten) request line and regenerate
1024 * the http request data.
1027 * 1 : csp = Current client state (buffers, headers, etc...)
1029 * Returns : Forwards the parse_http_request() return code.
1030 * Terminates in case of memory problems.
1032 *********************************************************************/
1033 static jb_err change_request_destination(struct client_state *csp)
1035 struct http_request *http = csp->http;
1038 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1039 csp->headers->first->str);
1040 free_http_request(http);
1041 err = parse_http_request(csp->headers->first->str, http);
1042 if (JB_ERR_OK != err)
1044 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1045 jb_err_to_string(err));
1052 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1053 /*********************************************************************
1055 * Function : server_response_is_complete
1057 * Description : Determines whether we should stop reading
1058 * from the server socket.
1061 * 1 : csp = Current client state (buffers, headers, etc...)
1062 * 2 : content_length = Length of content received so far.
1064 * Returns : TRUE if the response is complete,
1067 *********************************************************************/
1068 static int server_response_is_complete(struct client_state *csp,
1069 unsigned long long content_length)
1071 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1073 if (!strcmpic(csp->http->gpc, "HEAD"))
1076 * "HEAD" implies no body, we are thus expecting
1077 * no content. XXX: incomplete "list" of methods?
1079 csp->expected_content_length = 0;
1080 content_length_known = TRUE;
1081 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1084 if (csp->http->status == 204 || csp->http->status == 304)
1087 * Expect no body. XXX: incomplete "list" of status codes?
1089 csp->expected_content_length = 0;
1090 content_length_known = TRUE;
1091 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1094 return (content_length_known && ((0 == csp->expected_content_length)
1095 || (csp->expected_content_length <= content_length)));
1099 #ifdef FEATURE_CONNECTION_SHARING
1100 /*********************************************************************
1102 * Function : wait_for_alive_connections
1104 * Description : Waits for alive connections to timeout.
1110 *********************************************************************/
1111 static void wait_for_alive_connections(void)
1113 int connections_alive = close_unusable_connections();
1115 while (0 < connections_alive)
1117 log_error(LOG_LEVEL_CONNECT,
1118 "Waiting for %d connections to timeout.",
1121 connections_alive = close_unusable_connections();
1124 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1127 #endif /* def FEATURE_CONNECTION_SHARING */
1130 /*********************************************************************
1132 * Function : save_connection_destination
1134 * Description : Remembers a connection for reuse later on.
1137 * 1 : sfd = Open socket to remember.
1138 * 2 : http = The destination for the connection.
1139 * 3 : fwd = The forwarder settings used.
1140 * 4 : server_connection = storage.
1144 *********************************************************************/
1145 void save_connection_destination(jb_socket sfd,
1146 const struct http_request *http,
1147 const struct forward_spec *fwd,
1148 struct reusable_connection *server_connection)
1150 assert(sfd != JB_INVALID_SOCKET);
1151 assert(NULL != http->host);
1153 server_connection->sfd = sfd;
1154 server_connection->host = strdup_or_die(http->host);
1155 server_connection->port = http->port;
1157 assert(NULL != fwd);
1158 assert(server_connection->gateway_host == NULL);
1159 assert(server_connection->gateway_port == 0);
1160 assert(server_connection->forwarder_type == 0);
1161 assert(server_connection->forward_host == NULL);
1162 assert(server_connection->forward_port == 0);
1164 server_connection->forwarder_type = fwd->type;
1165 if (NULL != fwd->gateway_host)
1167 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1171 server_connection->gateway_host = NULL;
1173 server_connection->gateway_port = fwd->gateway_port;
1174 if (NULL != fwd->auth_username)
1176 server_connection->auth_username = strdup_or_die(fwd->auth_username);
1180 server_connection->auth_username = NULL;
1182 if (NULL != fwd->auth_password)
1184 server_connection->auth_password = strdup_or_die(fwd->auth_password);
1188 server_connection->auth_password = NULL;
1191 if (NULL != fwd->forward_host)
1193 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1197 server_connection->forward_host = NULL;
1199 server_connection->forward_port = fwd->forward_port;
1201 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1204 /*********************************************************************
1206 * Function : verify_request_length
1208 * Description : Checks if we already got the whole client requests
1209 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1212 * Data that doesn't belong to the current request is
1213 * either thrown away to let the client retry on a clean
1214 * socket, or stashed to be dealt with after the current
1215 * request is served.
1218 * 1 : csp = Current client state (buffers, headers, etc...)
1222 *********************************************************************/
1223 static void verify_request_length(struct client_state *csp)
1225 unsigned long long buffered_request_bytes =
1226 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1228 if ((csp->expected_client_content_length != 0)
1229 && (buffered_request_bytes != 0))
1231 if (csp->expected_client_content_length >= buffered_request_bytes)
1233 csp->expected_client_content_length -= buffered_request_bytes;
1234 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1235 "to account for the %llu ones we already got.",
1236 csp->expected_client_content_length, buffered_request_bytes);
1240 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1241 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1242 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1243 "Marking the server socket tainted after throwing %llu bytes away.",
1244 buffered_request_bytes - csp->expected_client_content_length);
1245 csp->expected_client_content_length = 0;
1246 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1249 if (csp->expected_client_content_length == 0)
1251 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1255 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1256 && ((csp->client_iob->cur < csp->client_iob->eod)
1257 || (csp->expected_client_content_length != 0)))
1259 if (strcmpic(csp->http->gpc, "GET")
1260 && strcmpic(csp->http->gpc, "HEAD")
1261 && strcmpic(csp->http->gpc, "TRACE")
1262 && strcmpic(csp->http->gpc, "OPTIONS")
1263 && strcmpic(csp->http->gpc, "DELETE"))
1265 /* XXX: this is an incomplete hack */
1266 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1267 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1271 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1273 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1275 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1276 log_error(LOG_LEVEL_CONNECT,
1277 "Possible pipeline attempt detected. The connection will not "
1278 "be kept alive and we will only serve the first request.");
1279 /* Nuke the pipelined requests from orbit, just to be sure. */
1280 clear_iob(csp->client_iob);
1285 * Keep the pipelined data around for now, we'll deal with
1286 * it once we're done serving the current request.
1288 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1289 assert(csp->client_iob->eod >= csp->client_iob->cur);
1290 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1291 "%d bytes of pipelined data received.",
1292 (int)(csp->client_iob->eod - csp->client_iob->cur));
1298 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1299 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1304 /*********************************************************************
1306 * Function : mark_server_socket_tainted
1308 * Description : Makes sure we don't reuse a server socket
1309 * (if we didn't read everything the server sent
1310 * us reusing the socket would lead to garbage).
1313 * 1 : csp = Current client state (buffers, headers, etc...)
1317 *********************************************************************/
1318 static void mark_server_socket_tainted(struct client_state *csp)
1321 * For consistency we always mark the server socket
1322 * tainted, however, to reduce the log noise we only
1323 * emit a log message if the server socket could have
1324 * actually been reused.
1326 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1327 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1329 log_error(LOG_LEVEL_CONNECT,
1330 "Marking the server socket %d tainted.",
1331 csp->server_connection.sfd);
1333 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1336 /*********************************************************************
1338 * Function : get_request_line
1340 * Description : Read the client request line.
1343 * 1 : csp = Current client state (buffers, headers, etc...)
1345 * Returns : Pointer to request line or NULL in case of errors.
1347 *********************************************************************/
1348 static char *get_request_line(struct client_state *csp)
1350 char buf[BUFFER_SIZE];
1351 char *request_line = NULL;
1354 memset(buf, 0, sizeof(buf));
1356 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1359 * If there are multiple pipelined requests waiting,
1360 * the flag will be set again once the next request
1363 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1365 request_line = get_header(csp->client_iob);
1366 if ((NULL != request_line) && ('\0' != *request_line))
1368 return request_line;
1372 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1373 "received yet. Continuing reading from %d.", csp->cfd);
1381 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1383 !data_is_available(csp->cfd, csp->config->socket_timeout)
1386 if (socket_is_still_alive(csp->cfd))
1388 log_error(LOG_LEVEL_CONNECT,
1389 "No request line on socket %d received in time. Timeout: %d.",
1390 csp->cfd, csp->config->socket_timeout);
1391 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1392 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1393 get_write_delay(csp));
1397 log_error(LOG_LEVEL_CONNECT,
1398 "The client side of the connection on socket %d got "
1399 "closed without sending a complete request line.", csp->cfd);
1404 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1406 if (len <= 0) return NULL;
1409 * If there is no memory left for buffering the
1410 * request, there is nothing we can do but hang up
1412 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1417 request_line = get_header(csp->client_iob);
1419 } while ((NULL != request_line) && ('\0' == *request_line));
1421 return request_line;
1427 CHUNK_STATUS_MISSING_DATA,
1428 CHUNK_STATUS_BODY_COMPLETE,
1429 CHUNK_STATUS_PARSE_ERROR
1433 /*********************************************************************
1435 * Function : chunked_body_is_complete
1437 * Description : Figures out whether or not a chunked body is complete.
1439 * Currently it always starts at the beginning of the
1440 * buffer which is somewhat wasteful and prevents Privoxy
1441 * from starting to forward the correctly parsed chunks
1442 * as soon as theoretically possible.
1444 * Should be modified to work with a common buffer,
1445 * and allow the caller to skip already parsed chunks.
1447 * This would allow the function to be used for unbuffered
1448 * response bodies as well.
1451 * 1 : iob = Buffer with the body to check.
1452 * 2 : length = Length of complete body
1454 * Returns : Enum with the result of the check.
1456 *********************************************************************/
1457 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1459 unsigned int chunksize;
1465 * We need at least a single digit, followed by "\r\n",
1466 * followed by an unknown amount of data, followed by "\r\n".
1468 if (p + 5 > iob->eod)
1470 return CHUNK_STATUS_MISSING_DATA;
1472 if (sscanf(p, "%x", &chunksize) != 1)
1474 return CHUNK_STATUS_PARSE_ERROR;
1478 * We want at least a single digit, followed by "\r\n",
1479 * followed by the specified amount of data, followed by "\r\n".
1481 if (p + chunksize + 5 > iob->eod)
1483 return CHUNK_STATUS_MISSING_DATA;
1486 /* Skip chunk-size. */
1487 p = strstr(p, "\r\n");
1490 return CHUNK_STATUS_PARSE_ERROR;
1492 /* Move beyond the chunkdata. */
1495 /* There should be another "\r\n" to skip */
1496 if (memcmp(p, "\r\n", 2))
1498 return CHUNK_STATUS_PARSE_ERROR;
1501 } while (chunksize > 0U);
1503 *length = (size_t)(p - iob->cur);
1504 assert(*length <= (size_t)(iob->eod - iob->cur));
1505 assert(p <= iob->eod);
1507 return CHUNK_STATUS_BODY_COMPLETE;
1512 /*********************************************************************
1514 * Function : receive_chunked_client_request_body
1516 * Description : Read the chunk-encoded client request body.
1517 * Failures are dealt with.
1520 * 1 : csp = Current client state (buffers, headers, etc...)
1522 * Returns : JB_ERR_OK or JB_ERR_PARSE
1524 *********************************************************************/
1525 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1528 enum chunk_status status;
1530 while (CHUNK_STATUS_MISSING_DATA ==
1531 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1533 char buf[BUFFER_SIZE];
1536 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1538 log_error(LOG_LEVEL_ERROR,
1539 "Timeout while waiting for the client body.");
1542 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1545 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1548 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1553 if (status != CHUNK_STATUS_BODY_COMPLETE)
1555 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1556 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1557 log_error(LOG_LEVEL_CLF,
1558 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1559 return JB_ERR_PARSE;
1561 log_error(LOG_LEVEL_CONNECT,
1562 "Chunked client body completely read. Length: %lu", body_length);
1563 csp->expected_client_content_length = body_length;
1571 /*********************************************************************
1573 * Function : fuzz_chunked_transfer_encoding
1575 * Description : Treat the fuzzed input as chunked transfer encoding
1576 * to check and dechunk.
1579 * 1 : csp = Used to store the data.
1580 * 2 : fuzz_input_file = File to read the input from.
1582 * Returns : Result of dechunking
1584 *********************************************************************/
1585 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1588 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1589 enum chunk_status status;
1591 status = chunked_body_is_complete(csp->iob, &length);
1592 if (CHUNK_STATUS_BODY_COMPLETE != status)
1594 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1597 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1602 /*********************************************************************
1604 * Function : fuzz_client_request
1606 * Description : Try to get a client request from the fuzzed input.
1609 * 1 : csp = Current client state (buffers, headers, etc...)
1610 * 2 : fuzz_input_file = File to read the input from.
1612 * Returns : Result of fuzzing.
1614 *********************************************************************/
1615 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1620 csp->ip_addr_str = "fuzzer";
1622 if (strcmp(fuzz_input_file, "-") != 0)
1624 log_error(LOG_LEVEL_FATAL,
1625 "Fuzzed client requests can currently only be read from stdin (-).");
1627 err = receive_client_request(csp);
1628 if (err != JB_ERR_OK)
1632 err = parse_client_request(csp);
1633 if (err != JB_ERR_OK)
1641 #endif /* def FUZZ */
1644 #ifdef FEATURE_FORCE_LOAD
1645 /*********************************************************************
1647 * Function : force_required
1649 * Description : Checks a request line to see if it contains
1650 * the FORCE_PREFIX. If it does, it is removed
1651 * unless enforcing requests has beend disabled.
1654 * 1 : request_line = HTTP request line
1656 * Returns : TRUE if force is required, FALSE otherwise.
1658 *********************************************************************/
1659 static int force_required(const struct client_state *csp, char *request_line)
1663 p = strstr(request_line, "http://");
1667 p += strlen("http://");
1671 /* Intercepted request usually don't specify the protocol. */
1675 /* Go to the beginning of the path */
1680 * If the path is missing the request line is invalid and we
1681 * are done here. The client-visible rejection happens later on.
1686 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1688 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1690 /* XXX: Should clean more carefully */
1691 strclean(request_line, FORCE_PREFIX);
1692 log_error(LOG_LEVEL_FORCE,
1693 "Enforcing request: \"%s\".", request_line);
1697 log_error(LOG_LEVEL_FORCE,
1698 "Ignored force prefix in request: \"%s\".", request_line);
1704 #endif /* def FEATURE_FORCE_LOAD */
1707 /*********************************************************************
1709 * Function : receive_client_request
1711 * Description : Read the client's request (more precisely the
1712 * client headers) and answer it if necessary.
1715 * 1 : csp = Current client state (buffers, headers, etc...)
1717 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1719 *********************************************************************/
1720 static jb_err receive_client_request(struct client_state *csp)
1722 char buf[BUFFER_SIZE];
1725 struct http_request *http;
1729 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1730 struct list header_list;
1731 struct list *headers = &header_list;
1733 /* We don't care if the arriving data is a valid HTTP request or not. */
1734 csp->requests_received_total++;
1738 memset(buf, 0, sizeof(buf));
1740 req = get_request_line(csp);
1743 mark_server_socket_tainted(csp);
1744 return JB_ERR_PARSE;
1746 assert(*req != '\0');
1748 if (client_protocol_is_unsupported(csp, req))
1750 return JB_ERR_PARSE;
1753 #ifdef FEATURE_FORCE_LOAD
1754 if (force_required(csp, req))
1756 csp->flags |= CSP_FLAG_FORCED;
1758 #endif /* def FEATURE_FORCE_LOAD */
1760 err = parse_http_request(req, http);
1762 if (JB_ERR_OK != err)
1764 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1765 get_write_delay(csp));
1766 /* XXX: Use correct size */
1767 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1768 log_error(LOG_LEVEL_ERROR,
1769 "Couldn't parse request line received from %s: %s",
1770 csp->ip_addr_str, jb_err_to_string(err));
1772 free_http_request(http);
1773 return JB_ERR_PARSE;
1776 /* grab the rest of the client's headers */
1780 p = get_header(csp->client_iob);
1784 /* There are no additional headers to read. */
1791 * We didn't receive a complete header
1792 * line yet, get the rest of it.
1794 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1796 log_error(LOG_LEVEL_ERROR,
1797 "Stopped grabbing the client headers.");
1798 destroy_list(headers);
1799 return JB_ERR_PARSE;
1802 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1805 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1806 destroy_list(headers);
1807 return JB_ERR_PARSE;
1810 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1813 * If there is no memory left for buffering the
1814 * request, there is nothing we can do but hang up
1816 destroy_list(headers);
1817 return JB_ERR_MEMORY;
1822 if (!strncmpic(p, "Transfer-Encoding:", 18))
1825 * XXX: should be called through sed()
1826 * but currently can't.
1828 client_transfer_encoding(csp, &p);
1831 * We were able to read a complete
1832 * header and can finally enlist it.
1839 if (http->host == NULL)
1842 * If we still don't know the request destination,
1843 * the request is invalid or the client uses
1844 * Privoxy without its knowledge.
1846 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1849 * Our attempts to get the request destination
1850 * elsewhere failed or Privoxy is configured
1851 * to only accept proxy requests.
1853 * An error response has already been send
1854 * and we're done here.
1856 return JB_ERR_PARSE;
1860 #ifdef FEATURE_CLIENT_TAGS
1861 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1862 set_client_address(csp, headers);
1863 get_tag_list_for_client(csp->client_tags, csp->client_address);
1867 * Determine the actions for this URL
1869 #ifdef FEATURE_TOGGLE
1870 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1872 /* Most compatible set of actions (i.e. none) */
1873 init_current_action(csp->action);
1876 #endif /* ndef FEATURE_TOGGLE */
1878 get_url_actions(csp, http);
1881 enlist(csp->headers, http->cmd);
1883 /* Append the previously read headers */
1884 err = list_append_list_unique(csp->headers, headers);
1885 destroy_list(headers);
1892 /*********************************************************************
1894 * Function : parse_client_request
1896 * Description : Parses the client's request and decides what to do
1899 * Note that since we're not using select() we could get
1900 * blocked here if a client connected, then didn't say
1904 * 1 : csp = Current client state (buffers, headers, etc...)
1906 * Returns : JB_ERR_OK or JB_ERR_PARSE
1908 *********************************************************************/
1909 static jb_err parse_client_request(struct client_state *csp)
1911 struct http_request *http = csp->http;
1914 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1915 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1916 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1917 && (csp->http->ssl == 0))
1919 /* Assume persistence until further notice */
1920 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1922 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1924 if (csp->http->ssl == 0)
1927 * This whole block belongs to chat() but currently
1928 * has to be executed before sed().
1930 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1932 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1934 return JB_ERR_PARSE;
1939 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1941 verify_request_length(csp);
1943 #ifndef FEATURE_HTTPS_INSPECTION
1946 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1950 err = sed(csp, FILTER_CLIENT_HEADERS);
1951 if (JB_ERR_OK != err)
1953 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1955 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1956 csp->ip_addr_str, csp->http->cmd);
1957 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1958 return JB_ERR_PARSE;
1960 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1962 /* Check request line for rewrites. */
1963 if ((NULL == csp->headers->first->str)
1964 || (strcmp(http->cmd, csp->headers->first->str) &&
1965 (JB_ERR_OK != change_request_destination(csp))))
1968 * A header filter broke the request line - bail out.
1970 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1971 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1972 /* XXX: Use correct size */
1973 log_error(LOG_LEVEL_CLF,
1974 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1975 log_error(LOG_LEVEL_ERROR,
1976 "Invalid request line after applying header filters.");
1977 free_http_request(http);
1979 return JB_ERR_PARSE;
1982 if (client_has_unsupported_expectations(csp))
1984 return JB_ERR_PARSE;
1992 /*********************************************************************
1994 * Function : read_http_request_body
1996 * Description : Reads remaining request body from the client.
1999 * 1 : csp = Current client state (buffers, headers, etc...)
2001 * Returns : 0 on success, anything else is an error.
2003 *********************************************************************/
2004 static int read_http_request_body(struct client_state *csp)
2006 size_t to_read = csp->expected_client_content_length;
2009 assert(to_read != 0);
2011 /* check if all data has been already read */
2012 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2017 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2018 to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2019 to_read -= (unsigned)len)
2021 char buf[BUFFER_SIZE];
2022 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2024 log_error(LOG_LEVEL_CONNECT,
2025 "Waiting for up to %d bytes of request body from the client.",
2027 len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2030 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2033 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2037 assert(to_read >= len);
2042 log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %d more bytes",
2043 csp->expected_client_content_length);
2046 log_error(LOG_LEVEL_CONNECT, "The last %d bytes of the request body have been read",
2047 csp->expected_client_content_length);
2052 /*********************************************************************
2054 * Function : update_client_headers
2056 * Description : Updates the HTTP headers from the client request.
2059 * 1 : csp = Current client state (buffers, headers, etc...)
2060 * 2 : new_content_length = new content length value to set
2062 * Returns : 0 on success, anything else is an error.
2064 *********************************************************************/
2065 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2067 static const char content_length[] = "Content-Length:";
2069 struct list_entry *p;
2071 #ifndef FEATURE_HTTPS_INSPECTION
2072 for (p = csp->headers->first;
2074 for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2076 !updated && (p != NULL); p = p->next)
2078 /* Header crunch()ed in previous run? -> ignore */
2084 /* Does the current parser handle this header? */
2085 if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2087 updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2099 /*********************************************************************
2101 * Function : can_filter_request_body
2103 * Description : Checks if the current request body can be stored in
2104 * the client_iob without hitting buffer limit.
2107 * 1 : csp = Current client state (buffers, headers, etc...)
2109 * Returns : TRUE if the current request size do not exceed buffer limit
2112 *********************************************************************/
2113 static int can_filter_request_body(const struct client_state *csp)
2115 if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2116 csp->expected_client_content_length))
2118 log_error(LOG_LEVEL_INFO,
2119 "Not filtering request body from %s: buffer limit %d will be exceeded "
2120 "(content length %d)", csp->ip_addr_str, csp->config->buffer_limit,
2121 csp->expected_client_content_length);
2128 /*********************************************************************
2130 * Function : send_http_request
2132 * Description : Sends the HTTP headers from the client request
2133 * and all the body data that has already been received.
2136 * 1 : csp = Current client state (buffers, headers, etc...)
2138 * Returns : 0 on success, anything else is an error.
2140 *********************************************************************/
2141 static int send_http_request(struct client_state *csp)
2145 const char *to_send;
2147 int filter_client_body = csp->expected_client_content_length != 0 &&
2148 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2150 if (filter_client_body)
2152 if (read_http_request_body(csp))
2156 to_send_len = csp->expected_client_content_length;
2157 to_send = execute_client_body_filters(csp, &to_send_len);
2158 if (to_send == NULL)
2160 /* just flush client_iob */
2161 filter_client_body = FALSE;
2163 else if (to_send_len != csp->expected_client_content_length &&
2164 update_client_headers(csp, to_send_len))
2166 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2169 csp->expected_client_content_length = 0;
2172 hdr = list_to_text(csp->headers);
2175 /* FIXME Should handle error properly */
2176 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2178 list_remove_all(csp->headers);
2181 * Write the client's (modified) header to the server
2182 * (along with anything else that may be in the buffer)
2184 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2189 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2190 csp->http->hostport);
2194 if (filter_client_body)
2196 write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2200 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2201 csp->http->hostport);
2206 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2207 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2209 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2210 csp->http->hostport);
2217 #ifdef FEATURE_HTTPS_INSPECTION
2218 /*********************************************************************
2220 * Function : read_https_request_body
2222 * Description : Reads remaining request body from the client.
2225 * 1 : csp = Current client state (buffers, headers, etc...)
2227 * Returns : 0 on success, anything else is an error.
2229 *********************************************************************/
2230 static int read_https_request_body(struct client_state *csp)
2232 size_t to_read = csp->expected_client_content_length;
2235 assert(to_read != 0);
2237 /* check if all data has been already read */
2238 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2243 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2244 to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2245 data_is_available(csp->cfd, csp->config->socket_timeout));
2246 to_read -= (unsigned)len)
2248 unsigned char buf[BUFFER_SIZE];
2249 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2251 log_error(LOG_LEVEL_CONNECT,
2252 "Waiting for up to %d bytes of request body from the client.",
2254 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2255 (unsigned)max_bytes_to_read);
2258 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2261 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2265 assert(to_read >= len);
2270 log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %d more bytes", to_read);
2274 log_error(LOG_LEVEL_CONNECT, "The last %d bytes of the request body have been read",
2275 csp->expected_client_content_length);
2280 /*********************************************************************
2282 * Function : receive_and_send_encrypted_post_data
2284 * Description : Reads remaining request body from the client and sends
2288 * 1 : csp = Current client state (buffers, headers, etc...)
2290 * Returns : 0 on success, anything else is an error.
2292 *********************************************************************/
2293 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2295 int content_length_known = csp->expected_client_content_length != 0;
2297 while (is_ssl_pending(&(csp->ssl_client_attr))
2298 || (content_length_known && csp->expected_client_content_length != 0))
2300 unsigned char buf[BUFFER_SIZE];
2302 int max_bytes_to_read = sizeof(buf);
2304 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2306 max_bytes_to_read = (int)csp->expected_client_content_length;
2308 log_error(LOG_LEVEL_CONNECT,
2309 "Waiting for up to %d bytes of request body from the client.",
2311 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2312 (unsigned)max_bytes_to_read);
2319 /* XXX: Does this actually happen? */
2322 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2324 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2329 if (csp->expected_client_content_length != 0)
2331 if (csp->expected_client_content_length >= len)
2333 csp->expected_client_content_length -= (unsigned)len;
2335 if (csp->expected_client_content_length == 0)
2337 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2343 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2350 /*********************************************************************
2352 * Function : send_https_request
2354 * Description : Sends the HTTP headers from the client request
2355 * and all the body data that has already been received.
2358 * 1 : csp = Current client state (buffers, headers, etc...)
2360 * Returns : 0 on success, anything else is an error.
2362 *********************************************************************/
2363 static int send_https_request(struct client_state *csp)
2368 const char *to_send;
2370 int filter_client_body = csp->expected_client_content_length != 0 &&
2371 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2373 if (filter_client_body)
2375 if (read_https_request_body(csp))
2379 to_send_len = csp->expected_client_content_length;
2380 to_send = execute_client_body_filters(csp, &to_send_len);
2381 if (to_send == NULL)
2383 /* just flush client_iob */
2384 filter_client_body = FALSE;
2386 else if (to_send_len != csp->expected_client_content_length &&
2387 update_client_headers(csp, to_send_len))
2389 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2392 csp->expected_client_content_length = 0;
2395 hdr = list_to_text(csp->https_headers);
2398 /* FIXME Should handle error properly */
2399 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2401 list_remove_all(csp->https_headers);
2404 * Write the client's (modified) header to the server
2405 * (along with anything else that may be in the buffer)
2407 ret = ssl_send_data(&(csp->ssl_server_attr),
2408 (const unsigned char *)hdr, strlen(hdr));
2413 log_error(LOG_LEVEL_CONNECT,
2414 "Failed sending encrypted request headers to: %s: %E",
2415 csp->http->hostport);
2416 mark_server_socket_tainted(csp);
2420 if (filter_client_body)
2422 ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2426 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2427 csp->http->hostport);
2432 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2433 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2434 csp->client_iob)) < 0))
2436 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2437 csp->http->hostport);
2440 if (flushed != 0 || csp->expected_client_content_length != 0)
2442 if (csp->expected_client_content_length != 0)
2444 if (csp->expected_client_content_length < flushed)
2446 log_error(LOG_LEVEL_ERROR,
2447 "Flushed %ld bytes of request body while only expecting %llu",
2448 flushed, csp->expected_client_content_length);
2449 csp->expected_client_content_length = 0;
2453 log_error(LOG_LEVEL_CONNECT,
2454 "Flushed %ld bytes of request body while expecting %llu",
2455 flushed, csp->expected_client_content_length);
2456 csp->expected_client_content_length -= (unsigned)flushed;
2457 if (receive_and_send_encrypted_post_data(csp))
2465 log_error(LOG_LEVEL_CONNECT,
2466 "Flushed %ld bytes of request body", flushed);
2470 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2477 /*********************************************************************
2479 * Function : receive_encrypted_request
2481 * Description : Receives an encrypted request.
2484 * 1 : csp = Current client state (buffers, headers, etc...)
2486 * Returns : JB_ERR_OK on success,
2487 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2489 *********************************************************************/
2490 static jb_err receive_encrypted_request(struct client_state *csp)
2492 char buf[BUFFER_SIZE];
2498 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2499 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2500 !data_is_available(csp->cfd, csp->config->socket_timeout))
2502 log_error(LOG_LEVEL_CONNECT,
2503 "Socket %d timed out while waiting for client headers", csp->cfd);
2504 return JB_ERR_PARSE;
2506 len = ssl_recv_data(&(csp->ssl_client_attr),
2507 (unsigned char *)buf, sizeof(buf));
2510 log_error(LOG_LEVEL_CONNECT,
2511 "Socket %d closed while waiting for client headers", csp->cfd);
2512 return JB_ERR_PARSE;
2516 return JB_ERR_PARSE;
2518 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2520 return JB_ERR_MEMORY;
2522 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2523 } while (p == NULL);
2525 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2531 /*********************************************************************
2533 * Function : process_encrypted_request
2535 * Description : Receives and parses an encrypted request.
2538 * 1 : csp = Current client state (buffers, headers, etc...)
2540 * Returns : JB_ERR_OK on success,
2541 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2543 *********************************************************************/
2544 static jb_err process_encrypted_request(struct client_state *csp)
2549 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2550 struct list header_list;
2551 struct list *headers = &header_list;
2553 assert(csp->ssl_with_client_is_opened);
2555 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2556 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2558 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2561 err = receive_encrypted_request(csp);
2562 if (err != JB_ERR_OK)
2564 if (csp->client_iob->cur == NULL ||
2565 csp->client_iob->cur == csp->client_iob->eod)
2568 * We did not receive any data, most likely because the
2569 * client is done. Don't log this as a parse failure.
2571 return JB_ERR_PARSE;
2573 /* XXX: Also used for JB_ERR_MEMORY */
2574 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2575 jb_err_to_string(err));
2576 ssl_send_data_delayed(&(csp->ssl_client_attr),
2577 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2581 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2582 request_line = get_header(csp->client_iob);
2583 if (request_line == NULL)
2585 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2586 ssl_send_data_delayed(&(csp->ssl_client_attr),
2587 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2588 return JB_ERR_PARSE;
2590 assert(*request_line != '\0');
2592 if (client_protocol_is_unsupported(csp, request_line))
2595 * If the protocol is unsupported we're done here.
2596 * client_protocol_is_unsupported() took care of sending
2597 * the error response and logging the error message.
2599 return JB_ERR_PARSE;
2602 #ifdef FEATURE_FORCE_LOAD
2603 if (force_required(csp, request_line))
2605 csp->flags |= CSP_FLAG_FORCED;
2607 #endif /* def FEATURE_FORCE_LOAD */
2609 free_http_request(csp->http);
2611 err = parse_http_request(request_line, csp->http);
2612 /* XXX: Restore ssl setting. This is ugly */
2613 csp->http->client_ssl = 1;
2614 csp->http->server_ssl = 1;
2616 freez(request_line);
2617 if (JB_ERR_OK != err)
2619 ssl_send_data_delayed(&(csp->ssl_client_attr),
2620 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2621 /* XXX: Use correct size */
2622 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2623 log_error(LOG_LEVEL_ERROR,
2624 "Couldn't parse request line received from %s: %s",
2625 csp->ip_addr_str, jb_err_to_string(err));
2627 free_http_request(csp->http);
2628 return JB_ERR_PARSE;
2631 /* Parse the rest of the client's headers. */
2635 p = get_header(csp->client_iob);
2639 /* There are no additional headers to read. */
2646 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2649 * Our attempts to get the request destination
2652 log_error(LOG_LEVEL_ERROR,
2653 "Failed to get the encrypted request destination");
2654 ssl_send_data_delayed(&(csp->ssl_client_attr),
2655 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2656 return JB_ERR_PARSE;
2659 /* Split the domain we just got for pattern matching */
2660 init_domain_components(csp->http);
2662 #ifdef FEATURE_CLIENT_TAGS
2663 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2664 if (csp->client_address == NULL)
2666 set_client_address(csp, headers);
2667 get_tag_list_for_client(csp->client_tags, csp->client_address);
2671 #ifdef FEATURE_TOGGLE
2672 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2676 * Determine the actions for this request after
2677 * clearing the ones from the previous one.
2679 free_current_action(csp->action);
2680 get_url_actions(csp, csp->http);
2683 enlist(csp->https_headers, csp->http->cmd);
2685 /* Append the previously read headers */
2686 err = list_append_list_unique(csp->https_headers, headers);
2687 destroy_list(headers);
2688 if (JB_ERR_OK != err)
2690 /* XXX: Send error message */
2694 /* XXX: Work around crash */
2695 csp->error_message = NULL;
2697 /* XXX: Why do this here? */
2700 err = sed_https(csp);
2701 if (JB_ERR_OK != err)
2703 ssl_send_data_delayed(&(csp->ssl_client_attr),
2704 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2705 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2707 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2708 csp->ip_addr_str, csp->http->cmd);
2709 return JB_ERR_PARSE;
2712 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2713 log_applied_actions(csp->action);
2714 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2721 /*********************************************************************
2723 * Function : cgi_page_requested
2725 * Description : Checks if a request is for an internal CGI page.
2728 * 1 : host = The host requested by the client.
2730 * Returns : 1 if a CGI page has been requested, 0 otherwise
2732 *********************************************************************/
2733 static int cgi_page_requested(const char *host)
2735 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2736 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2737 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2738 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2748 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2749 /*********************************************************************
2751 * Function : continue_https_chat
2753 * Description : Behaves similar to chat() but only deals with
2754 * https-inspected requests that arrive on an already
2755 * established connection. The first request is always
2756 * served by chat() which is a lot more complex as it
2757 * has to deal with forwarding settings and connection
2760 * If a connection to the server has already been
2761 * opened it is reused unless the request is blocked
2762 * or the forwarder changed.
2764 * If a connection to the server has not yet been
2765 * opened (because the previous request was crunched),
2766 * or the forwarder changed, the connection is dropped
2767 * so that the client retries on a fresh one.
2770 * 1 : csp = Current client state (buffers, headers, etc...)
2772 * Returns : Nothing.
2774 *********************************************************************/
2775 static void continue_https_chat(struct client_state *csp)
2777 const struct forward_spec *fwd;
2779 if (JB_ERR_OK != process_encrypted_request(csp))
2784 csp->requests_received_total++;
2787 * We have an encrypted request. Check if one of the crunchers wants it.
2789 if (crunch_response_triggered(csp, crunchers_all))
2792 * Yes. The client got the crunch response and we're done here.
2796 if (csp->ssl_with_server_is_opened == 0)
2798 log_error(LOG_LEVEL_CONNECT,
2799 "Dropping the client connection on socket %d. "
2800 "The server connection has not been established yet.",
2802 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2805 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2807 fwd = forward_url(csp, csp->http);
2808 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2810 log_error(LOG_LEVEL_CONNECT,
2811 "Dropping the client connection on socket %d with "
2812 "server socket %d connected to %s. The forwarder has changed.",
2813 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2814 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2818 log_error(LOG_LEVEL_CONNECT,
2819 "Reusing server socket %d connected to %s. Requests already sent: %u.",
2820 csp->server_connection.sfd, csp->server_connection.host,
2821 csp->server_connection.requests_sent_total);
2823 if (send_https_request(csp))
2826 * Most likely the server connection timed out. We can't easily
2827 * create a new one so simply drop the client connection without a
2828 * error response to let the client retry.
2830 log_error(LOG_LEVEL_CONNECT,
2831 "Dropping client connection on socket %d. "
2832 "Forwarding the encrypted client request failed.",
2836 csp->server_connection.requests_sent_total++;
2837 handle_established_connection(csp);
2838 freez(csp->receive_buffer);
2840 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2844 /*********************************************************************
2846 * Function : handle_established_connection
2848 * Description : Shuffle data between client and server once the
2849 * connection has been established.
2852 * 1 : csp = Current client state (buffers, headers, etc...)
2854 * Returns : Nothing.
2856 *********************************************************************/
2857 static void handle_established_connection(struct client_state *csp)
2863 struct pollfd poll_fds[2];
2867 struct timeval timeout;
2870 int ms_iis5_hack = 0;
2871 unsigned long long byte_count = 0;
2872 struct http_request *http;
2873 long len = 0; /* for buffer sizes (and negative error codes) */
2874 int buffer_and_filter_content = 0;
2875 unsigned int write_delay;
2876 #ifdef FEATURE_HTTPS_INSPECTION
2878 int use_ssl_tunnel = 0;
2879 csp->dont_verify_certificate = 0;
2881 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2883 /* Pass encrypted content without filtering. */
2888 /* Skeleton for HTTP response, if we should intercept the request */
2889 struct http_response *rsp;
2890 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2891 int watch_client_socket;
2894 csp->receive_buffer_size = csp->config->receive_buffer_size;
2895 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2896 if (csp->receive_buffer == NULL)
2898 log_error(LOG_LEVEL_ERROR,
2899 "Out of memory. Failed to allocate the receive buffer.");
2900 rsp = cgi_error_memory();
2901 send_crunch_response(csp, rsp);
2908 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2909 csp->cfd : csp->server_connection.sfd;
2912 /* pass data between the client and server
2913 * until one or the other shuts down the connection.
2918 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2919 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2921 write_delay = get_write_delay(csp);
2927 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2928 if (!watch_client_socket)
2930 maxfd = csp->server_connection.sfd;
2933 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2935 FD_SET(csp->cfd, &rfds);
2938 FD_SET(csp->server_connection.sfd, &rfds);
2939 #endif /* ndef HAVE_POLL */
2941 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2942 if ((csp->flags & CSP_FLAG_CHUNKED)
2943 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2944 && ((csp->iob->eod - csp->iob->cur) >= 5)
2945 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2948 * XXX: This check should be obsolete now,
2949 * but let's wait a while to be sure.
2951 log_error(LOG_LEVEL_CONNECT,
2952 "Looks like we got the last chunk together with "
2953 "the server headers but didn't detect it earlier. "
2954 "We better stop reading.");
2955 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2956 csp->expected_content_length = byte_count;
2957 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2959 if (server_body && server_response_is_complete(csp, byte_count))
2961 if (csp->expected_content_length == byte_count)
2963 log_error(LOG_LEVEL_CONNECT,
2964 "Done reading from server. Content length: %llu as expected. "
2965 "Bytes most recently read: %ld.",
2970 log_error(LOG_LEVEL_CONNECT,
2971 "Done reading from server. Expected content length: %llu. "
2972 "Actual content length: %llu. Bytes most recently read: %ld.",
2973 csp->expected_content_length, byte_count, len);
2977 * XXX: Should not jump around, handle_established_connection()
2978 * is complicated enough already.
2982 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2985 poll_fds[0].fd = csp->cfd;
2986 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2987 if (!watch_client_socket)
2990 * Ignore incoming data, but still watch out
2991 * for disconnects etc. These flags are always
2992 * implied anyway but explicitly setting them
2995 poll_fds[0].events = POLLERR|POLLHUP;
3000 poll_fds[0].events = POLLIN;
3002 poll_fds[1].fd = csp->server_connection.sfd;
3003 poll_fds[1].events = POLLIN;
3004 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3006 timeout.tv_sec = csp->config->socket_timeout;
3007 timeout.tv_usec = 0;
3008 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3009 #endif /* def HAVE_POLL */
3011 /*server or client not responding in timeout */
3014 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3015 csp->config->socket_timeout, http->url);
3016 if ((byte_count == 0) && (http->ssl == 0))
3018 send_crunch_response(csp, error_response(csp, "connection-timeout"));
3020 mark_server_socket_tainted(csp);
3021 #ifdef FEATURE_HTTPS_INSPECTION
3022 close_client_and_server_ssl_connections(csp);
3029 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3031 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3033 mark_server_socket_tainted(csp);
3034 #ifdef FEATURE_HTTPS_INSPECTION
3035 close_client_and_server_ssl_connections(csp);
3041 * This is the body of the browser's request,
3042 * just read and write it.
3044 * Receives data from browser and sends it to server
3046 * XXX: Make sure the client doesn't use pipelining
3047 * behind Privoxy's back.
3050 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3052 log_error(LOG_LEVEL_CONNECT,
3053 "The client socket %d has become unusable while "
3054 "the server socket %d is still open.",
3055 csp->cfd, csp->server_connection.sfd);
3056 mark_server_socket_tainted(csp);
3060 if (poll_fds[0].revents != 0)
3062 if (FD_ISSET(csp->cfd, &rfds))
3063 #endif /* def HAVE_POLL*/
3065 int max_bytes_to_read = (int)csp->receive_buffer_size;
3067 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3068 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3070 if (data_is_available(csp->cfd, 0))
3073 * If the next request is already waiting, we have
3074 * to stop select()ing the client socket. Otherwise
3075 * we would always return right away and get nothing
3078 watch_client_socket = 0;
3079 log_error(LOG_LEVEL_CONNECT,
3080 "Stop watching client socket %d. "
3081 "There's already another request waiting.",
3086 * If the client socket is set, but there's no data
3087 * available on the socket, the client went fishing
3088 * and continuing talking to the server makes no sense.
3090 log_error(LOG_LEVEL_CONNECT,
3091 "The client closed socket %d while "
3092 "the server socket %d is still open.",
3093 csp->cfd, csp->server_connection.sfd);
3094 mark_server_socket_tainted(csp);
3097 if (csp->expected_client_content_length != 0)
3099 if (csp->expected_client_content_length < csp->receive_buffer_size)
3101 max_bytes_to_read = (int)csp->expected_client_content_length;
3103 log_error(LOG_LEVEL_CONNECT,
3104 "Waiting for up to %d bytes from the client.",
3107 assert(max_bytes_to_read <= csp->receive_buffer_size);
3108 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3110 #ifdef FEATURE_HTTPS_INSPECTION
3111 if (client_use_ssl(csp))
3113 if (csp->http->status == 101)
3115 len = ssl_recv_data(&(csp->ssl_client_attr),
3116 (unsigned char *)csp->receive_buffer,
3117 (size_t)max_bytes_to_read);
3120 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3121 "on client socket %d for an upgraded connection",
3127 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3128 "on client socket %d for an upgraded connection",
3132 byte_count += (unsigned long long)len;
3133 len = ssl_send_data(&(csp->ssl_server_attr),
3134 (unsigned char *)csp->receive_buffer, (size_t)len);
3137 log_error(LOG_LEVEL_ERROR, "Failed to send data "
3138 "on server socket %d for an upgraded connection",
3139 csp->server_connection.sfd);
3144 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3148 #endif /* def FEATURE_HTTPS_INSPECTION */
3150 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3154 /* XXX: not sure if this is necessary. */
3155 mark_server_socket_tainted(csp);
3156 break; /* "game over, man" */
3159 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3160 if (csp->expected_client_content_length != 0)
3162 assert(len <= max_bytes_to_read);
3163 csp->expected_client_content_length -= (unsigned)len;
3164 log_error(LOG_LEVEL_CONNECT,
3165 "Expected client content length set to %llu "
3166 "after reading %ld bytes.",
3167 csp->expected_client_content_length, len);
3168 if (csp->expected_client_content_length == 0)
3170 log_error(LOG_LEVEL_CONNECT,
3171 "Done reading from the client.");
3172 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3175 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3177 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3179 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3180 mark_server_socket_tainted(csp);
3188 * The server wants to talk. It could be the header or the body.
3189 * If `hdr' is null, then it's the header otherwise it's the body.
3190 * FIXME: Does `hdr' really mean `host'? No.
3193 if (poll_fds[1].revents != 0)
3195 if (FD_ISSET(csp->server_connection.sfd, &rfds))
3196 #endif /* HAVE_POLL */
3198 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3200 * If we are buffering content, we don't want to eat up to
3201 * buffer-limit bytes if the client no longer cares about them.
3202 * If we aren't buffering, however, a dead client socket will be
3203 * noticed pretty much right away anyway, so we can reduce the
3204 * overhead by skipping the check.
3206 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3209 log_error(LOG_LEVEL_CONNECT,
3210 "The server still wants to talk, but the client may already have hung up on us.");
3212 log_error(LOG_LEVEL_CONNECT,
3213 "The server still wants to talk, but the client hung up on us.");
3214 mark_server_socket_tainted(csp);
3215 #ifdef FEATURE_HTTPS_INSPECTION
3216 close_client_and_server_ssl_connections(csp);
3219 #endif /* def _WIN32 */
3221 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3223 #ifdef FEATURE_HTTPS_INSPECTION
3225 * Reading data from standard or secured connection (HTTP/HTTPS)
3227 if (server_use_ssl(csp))
3229 len = ssl_recv_data(&(csp->ssl_server_attr),
3230 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3235 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3236 (int)csp->receive_buffer_size);
3241 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3243 if ((http->ssl && (csp->fwd == NULL))
3244 #ifdef FEATURE_HTTPS_INSPECTION
3250 * Just hang up. We already confirmed the client's CONNECT
3251 * request with status code 200 and unencrypted content is
3252 * no longer welcome.
3254 log_error(LOG_LEVEL_ERROR,
3255 "CONNECT already confirmed. Unable to tell the client about the problem.");
3258 else if (byte_count)
3261 * Just hang up. We already transmitted the original headers
3262 * and parts of the original content and therefore missed the
3263 * chance to send an error message (without risking data corruption).
3265 * XXX: we could retry with a fancy range request here.
3267 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3268 "Unable to tell the client about the problem.");
3269 mark_server_socket_tainted(csp);
3270 #ifdef FEATURE_HTTPS_INSPECTION
3271 close_client_and_server_ssl_connections(csp);
3276 * XXX: Consider handling the cases above the same.
3278 mark_server_socket_tainted(csp);
3282 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3283 if (csp->flags & CSP_FLAG_CHUNKED)
3285 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3287 /* XXX: this is a temporary hack */
3288 log_error(LOG_LEVEL_CONNECT,
3289 "Looks like we reached the end of the last chunk. "
3290 "We better stop reading.");
3291 csp->expected_content_length = byte_count + (unsigned long long)len;
3292 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3296 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3299 * This is guaranteed by allocating with zalloc_or_die()
3300 * and never (intentionally) writing to the last byte.
3302 * csp->receive_buffer_size is the size of the part of the
3303 * buffer we intentionally write to, but we actually
3304 * allocated csp->receive_buffer_size+1 bytes so the assertion
3305 * stays within the allocated range.
3307 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3310 * Add a trailing zero to let be able to use string operations.
3311 * XXX: do we still need this with filter_popups gone?
3313 assert(len <= csp->receive_buffer_size);
3314 csp->receive_buffer[len] = '\0';
3317 * Normally, this would indicate that we've read
3318 * as much as the server has sent us and we can
3319 * close the client connection. However, Microsoft
3320 * in its wisdom has released IIS/5 with a bug that
3321 * prevents it from sending the trailing \r\n in
3322 * a 302 redirect header (and possibly other headers).
3323 * To work around this if we've haven't parsed
3324 * a full header we'll append a trailing \r\n
3325 * and see if this now generates a valid one.
3327 * This hack shouldn't have any impacts. If we've
3328 * already transmitted the header or if this is a
3329 * SSL connection, then we won't bother with this
3330 * hack. So we only work on partially received
3331 * headers. If we append a \r\n and this still
3332 * doesn't generate a valid header, then we won't
3333 * transmit anything to the client.
3338 if (server_body || (http->ssl
3339 #ifdef FEATURE_HTTPS_INSPECTION
3345 * If we have been buffering up the document,
3346 * now is the time to apply content modification
3347 * and send the result to the client.
3349 if (buffer_and_filter_content)
3351 p = execute_content_filters(csp);
3353 * If content filtering fails, use the original
3354 * buffer and length.
3355 * (see p != NULL ? p : csp->iob->cur below)
3359 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3361 #ifdef FEATURE_COMPRESSION
3362 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3363 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3365 char *compressed_content = compress_buffer(p,
3366 (size_t *)&csp->content_length, csp->config->compression_level);
3367 if (compressed_content != NULL)
3370 p = compressed_content;
3371 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3376 if (JB_ERR_OK != update_server_headers(csp))
3378 log_error(LOG_LEVEL_FATAL,
3379 "Failed to update server headers. after filtering.");
3382 hdr = list_to_text(csp->headers);
3385 /* FIXME Should handle error properly */
3386 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3389 #ifdef FEATURE_HTTPS_INSPECTION
3391 * Sending data with standard or secured connection (HTTP/HTTPS)
3393 if (client_use_ssl(csp))
3395 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3396 (const unsigned char *)hdr, strlen(hdr),
3397 get_write_delay(csp)) < 0)
3398 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3399 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3400 csp->content_length, get_write_delay(csp)) < 0))
3402 log_error(LOG_LEVEL_ERROR, "write modified content to "
3403 "client over TLS/SSL failed");
3406 mark_server_socket_tainted(csp);
3407 close_client_and_server_ssl_connections(csp);
3412 #endif /* def FEATURE_HTTPS_INSPECTION */
3414 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3415 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3416 (size_t)csp->content_length, write_delay))
3418 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3421 mark_server_socket_tainted(csp);
3430 break; /* "game over, man" */
3434 * This is NOT the body, so
3435 * Let's pretend the server just sent us a blank line.
3437 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3438 len = (int)strlen(csp->receive_buffer);
3441 * Now, let the normal header parsing algorithm below do its
3442 * job. If it fails, we'll exit instead of continuing.
3449 * If we're in the body of the server document, just write it to
3450 * the client, unless we need to buffer the body for later
3451 * content-filtering.
3453 if (server_body || (http->ssl
3454 #ifdef FEATURE_HTTPS_INSPECTION
3459 if (buffer_and_filter_content)
3462 * If there is no memory left for buffering the content, or the buffer limit
3463 * has been reached, switch to non-filtering mode, i.e. make & write the
3464 * header, flush the iob and buf, and get out of the way.
3466 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3471 log_error(LOG_LEVEL_INFO,
3472 "Flushing header and buffers. Stepping back from filtering.");
3474 hdr = list_to_text(csp->headers);
3478 * Memory is too tight to even generate the header.
3479 * Send our static "Out-of-memory" page.
3481 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3482 rsp = cgi_error_memory();
3483 send_crunch_response(csp, rsp);
3484 mark_server_socket_tainted(csp);
3485 #ifdef FEATURE_HTTPS_INSPECTION
3486 close_client_and_server_ssl_connections(csp);
3490 hdrlen = strlen(hdr);
3492 #ifdef FEATURE_HTTPS_INSPECTION
3494 * Sending data with standard or secured connection (HTTP/HTTPS)
3496 if (client_use_ssl(csp))
3498 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3499 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3500 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3502 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3503 (const unsigned char *)csp->receive_buffer, (size_t)len,
3504 get_write_delay(csp)) < 0))
3506 log_error(LOG_LEVEL_CONNECT,
3507 "Flush header and buffers to client failed");
3509 mark_server_socket_tainted(csp);
3510 close_client_and_server_ssl_connections(csp);
3515 #endif /* def FEATURE_HTTPS_INSPECTION */
3517 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3518 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3519 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3522 log_error(LOG_LEVEL_CONNECT,
3523 "Flush header and buffers to client failed: %E");
3525 mark_server_socket_tainted(csp);
3531 * Reset the byte_count to the amount of bytes
3532 * we just flushed. len will be added a few lines below,
3533 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3535 byte_count = (unsigned long long)flushed;
3537 buffer_and_filter_content = 0;
3543 #ifdef FEATURE_HTTPS_INSPECTION
3545 * Sending data with standard or secured connection (HTTP/HTTPS)
3547 if (client_use_ssl(csp))
3549 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3550 (const unsigned char *)csp->receive_buffer, (size_t)len,
3551 get_write_delay(csp));
3554 log_error(LOG_LEVEL_ERROR,
3555 "Sending data to client failed");
3556 mark_server_socket_tainted(csp);
3557 close_client_and_server_ssl_connections(csp);
3562 #endif /* def FEATURE_HTTPS_INSPECTION */
3564 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3565 (size_t)len, write_delay))
3567 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3568 mark_server_socket_tainted(csp);
3573 byte_count += (unsigned long long)len;
3579 * We're still looking for the end of the server's header.
3580 * Buffer up the data we just read. If that fails, there's
3581 * little we can do but send our static out-of-memory page.
3583 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3585 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3586 rsp = cgi_error_memory();
3587 send_crunch_response(csp, rsp);
3588 mark_server_socket_tainted(csp);
3589 #ifdef FEATURE_HTTPS_INSPECTION
3590 close_client_and_server_ssl_connections(csp);
3595 /* Convert iob into something sed() can digest */
3596 if (JB_ERR_PARSE == get_server_headers(csp))
3601 * Well, we tried our MS IIS/5 hack and it didn't work.
3602 * The header is incomplete and there isn't anything
3603 * we can do about it.
3605 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3606 "Applying the MS IIS5 hack didn't help.");
3607 log_error(LOG_LEVEL_CLF,
3608 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3609 #ifdef FEATURE_HTTPS_INSPECTION
3611 * Sending data with standard or secured connection (HTTP/HTTPS)
3613 if (client_use_ssl(csp))
3615 ssl_send_data_delayed(&(csp->ssl_client_attr),
3616 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3617 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3620 #endif /* def FEATURE_HTTPS_INSPECTION */
3622 write_socket_delayed(csp->cfd,
3623 INVALID_SERVER_HEADERS_RESPONSE,
3624 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3626 mark_server_socket_tainted(csp);
3627 #ifdef FEATURE_HTTPS_INSPECTION
3628 close_client_and_server_ssl_connections(csp);
3635 * Since we have to wait for more from the server before
3636 * we can parse the headers we just continue here.
3638 log_error(LOG_LEVEL_CONNECT,
3639 "Continuing buffering server headers from socket %d. "
3640 "Bytes most recently read: %ld.", csp->cfd, len);
3647 * Account for the content bytes we
3648 * might have gotten with the headers.
3650 assert(csp->iob->eod >= csp->iob->cur);
3651 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3654 /* Did we actually get anything? */
3655 if (NULL == csp->headers->first)
3657 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3659 log_error(LOG_LEVEL_ERROR,
3660 "No server or forwarder response received on socket %d. "
3661 "Closing client socket %d without sending data.",
3662 csp->server_connection.sfd, csp->cfd);
3663 log_error(LOG_LEVEL_CLF,
3664 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3668 log_error(LOG_LEVEL_ERROR,
3669 "No server or forwarder response received on socket %d.",
3670 csp->server_connection.sfd);
3671 send_crunch_response(csp, error_response(csp, "no-server-data"));
3673 free_http_request(http);
3674 mark_server_socket_tainted(csp);
3675 #ifdef FEATURE_HTTPS_INSPECTION
3676 close_client_and_server_ssl_connections(csp);
3681 if (!csp->headers->first->str)
3683 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3685 assert(csp->headers->first->str);
3687 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3688 strncmpic(csp->headers->first->str, "ICY", 3))
3691 * It doesn't look like a HTTP (or Shoutcast) response:
3692 * tell the client and log the problem.
3694 if (strlen(csp->headers->first->str) > 30)
3696 csp->headers->first->str[30] = '\0';
3698 log_error(LOG_LEVEL_ERROR,
3699 "Invalid server or forwarder response. Starts with: %s",
3700 csp->headers->first->str);
3701 log_error(LOG_LEVEL_CLF,
3702 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3703 #ifdef FEATURE_HTTPS_INSPECTION
3705 * Sending data with standard or secured connection (HTTP/HTTPS)
3707 if (client_use_ssl(csp))
3709 ssl_send_data_delayed(&(csp->ssl_client_attr),
3710 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3711 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3712 get_write_delay(csp));
3715 #endif /* def FEATURE_HTTPS_INSPECTION */
3717 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3718 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3720 free_http_request(http);
3721 mark_server_socket_tainted(csp);
3722 #ifdef FEATURE_HTTPS_INSPECTION
3723 close_client_and_server_ssl_connections(csp);
3729 * We have now received the entire server header,
3730 * filter it and send the result to the client
3732 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3734 log_error(LOG_LEVEL_CLF,
3735 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3736 #ifdef FEATURE_HTTPS_INSPECTION
3738 * Sending data with standard or secured connection (HTTP/HTTPS)
3740 if (client_use_ssl(csp))
3742 ssl_send_data_delayed(&(csp->ssl_client_attr),
3743 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3744 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3745 get_write_delay(csp));
3750 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3751 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3753 free_http_request(http);
3754 mark_server_socket_tainted(csp);
3755 #ifdef FEATURE_HTTPS_INSPECTION
3756 close_client_and_server_ssl_connections(csp);
3760 hdr = list_to_text(csp->headers);
3763 /* FIXME Should handle error properly */
3764 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3767 if ((csp->flags & CSP_FLAG_CHUNKED)
3768 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3769 && ((csp->iob->eod - csp->iob->cur) >= 5)
3770 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3772 log_error(LOG_LEVEL_CONNECT,
3773 "Looks like we got the last chunk together with "
3774 "the server headers. We better stop reading.");
3775 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3776 csp->expected_content_length = byte_count;
3777 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3780 csp->server_connection.response_received = time(NULL);
3782 if (crunch_response_triggered(csp, crunchers_light))
3785 * One of the tags created by a server-header
3786 * tagger triggered a crunch. We already
3787 * delivered the crunch response to the client
3788 * and are done here after cleaning up.
3791 mark_server_socket_tainted(csp);
3792 #ifdef FEATURE_HTTPS_INSPECTION
3793 close_client_and_server_ssl_connections(csp);
3798 /* Buffer and pcrs filter this if appropriate. */
3799 buffer_and_filter_content = content_requires_filtering(csp);
3801 if (!buffer_and_filter_content)
3804 * Write the server's (modified) header to
3805 * the client (along with anything else that
3806 * may be in the buffer). Use standard or secured
3809 #ifdef FEATURE_HTTPS_INSPECTION
3810 if (client_use_ssl(csp))
3812 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3813 (const unsigned char *)hdr, strlen(hdr),
3814 get_write_delay(csp)) < 0)
3815 || (len = ssl_flush_socket(&(csp->ssl_client_attr),
3818 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3821 * The write failed, so don't bother mentioning it
3822 * to the client... it probably can't hear us anyway.
3825 mark_server_socket_tainted(csp);
3826 #ifdef FEATURE_HTTPS_INSPECTION
3827 close_client_and_server_ssl_connections(csp);
3833 #endif /* def FEATURE_HTTPS_INSPECTION */
3835 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3836 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3838 log_error(LOG_LEVEL_ERROR,
3839 "write header to client failed");
3841 * The write failed, so don't bother mentioning it
3842 * to the client... it probably can't hear us anyway.
3845 mark_server_socket_tainted(csp);
3851 /* we're finished with the server's header */
3857 * If this was a MS IIS/5 hack then it means the server
3858 * has already closed the connection. Nothing more to read.
3863 log_error(LOG_LEVEL_ERROR,
3864 "Closed server connection detected. "
3865 "Applying the MS IIS5 hack didn't help.");
3866 log_error(LOG_LEVEL_CLF,
3867 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3868 #ifdef FEATURE_HTTPS_INSPECTION
3870 * Sending data with standard or secured connection (HTTP/HTTPS)
3872 if (client_use_ssl(csp))
3874 ssl_send_data_delayed(&(csp->ssl_client_attr),
3875 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3876 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3877 get_write_delay(csp));
3880 #endif /* def FEATURE_HTTPS_INSPECTION */
3882 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3883 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3885 mark_server_socket_tainted(csp);
3886 #ifdef FEATURE_HTTPS_INSPECTION
3887 close_client_and_server_ssl_connections(csp);
3894 mark_server_socket_tainted(csp);
3895 #ifdef FEATURE_HTTPS_INSPECTION
3896 close_client_and_server_ssl_connections(csp);
3898 return; /* huh? we should never get here */
3901 if (csp->content_length == 0)
3904 * If Privoxy didn't recalculate the Content-Length,
3905 * byte_count is still correct.
3907 csp->content_length = byte_count;
3910 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3911 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3912 && (csp->expected_content_length != byte_count))
3914 log_error(LOG_LEVEL_CONNECT,
3915 "Received %llu bytes while expecting %llu.",
3916 byte_count, csp->expected_content_length);
3917 mark_server_socket_tainted(csp);
3921 #ifdef FEATURE_HTTPS_INSPECTION
3922 if (client_use_ssl(csp))
3924 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
3925 csp->ip_addr_str, http->gpc, http->hostport, http->path,
3926 http->version, csp->content_length);
3931 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3932 csp->ip_addr_str, http->ocmd, csp->content_length);
3934 csp->server_connection.timestamp = time(NULL);
3938 /*********************************************************************
3942 * Description : Once a connection from the client has been accepted,
3943 * this function is called (via serve()) to handle the
3944 * main business of the communication. This function
3945 * returns after dealing with a single request. It can
3946 * be called multiple times with the same client socket
3947 * if the client is keeping the connection alive.
3949 * The decision whether or not a client connection will
3950 * be kept alive is up to the caller which also must
3951 * close the client socket when done.
3953 * FIXME: chat is nearly thousand lines long.
3957 * 1 : csp = Current client state (buffers, headers, etc...)
3959 * Returns : Nothing.
3961 *********************************************************************/
3962 static void chat(struct client_state *csp)
3964 const struct forward_spec *fwd;
3965 struct http_request *http;
3966 /* Skeleton for HTTP response, if we should intercept the request */
3967 struct http_response *rsp;
3968 #ifdef FEATURE_HTTPS_INSPECTION
3969 int use_ssl_tunnel = 0;
3974 if (receive_client_request(csp) != JB_ERR_OK)
3978 if (parse_client_request(csp) != JB_ERR_OK)
3983 /* decide how to route the HTTP request */
3984 fwd = forward_url(csp, http);
3986 #ifdef FEATURE_HTTPS_INSPECTION
3988 * Setting flags to use old solution with SSL tunnel and to disable
3989 * certificate verification.
3991 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
3992 && !cgi_page_requested(csp->http->host))
3997 if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
3999 csp->dont_verify_certificate = 1;
4004 * build the http request to send to the server
4005 * we have to do one of the following:
4007 * create = use the original HTTP request to create a new
4008 * HTTP request that has either the path component
4009 * without the http://domainspec (w/path) or the
4010 * full orininal URL (w/url)
4011 * Note that the path and/or the HTTP version may
4012 * have been altered by now.
4014 * SSL proxy = Open a socket to the host:port of the server
4015 * and create TLS/SSL connection with server and
4016 * with client. Then behave like mediator between
4017 * client and server over TLS/SSL.
4019 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4020 * with request to a parent proxy. Note that we'll be sending
4021 * forwarding the CFAIL message ourselves if connecting to the parent
4022 * fails, but we won't send a CSUCCEED message if it works,
4023 * since that would result in a double message (ours and the
4024 * parent's). After sending the request to the parent, we
4025 * must parse answer and send it to client. If connection
4026 * with server is established, we do TLS/SSL proxy. Otherwise
4027 * we send parent response to client and close connections.
4029 * here's the matrix:
4032 * +--------+--------+
4034 * 0 | create | SSL |
4035 * | w/path | proxy |
4036 * Forwarding +--------+--------+
4038 * 1 | create | proxy |
4039 * | w/url |+forward|
4040 * +--------+--------+
4044 #ifdef FEATURE_HTTPS_INSPECTION
4046 * Presetting SSL client and server flags
4048 if (http->ssl && !use_ssl_tunnel)
4050 http->client_ssl = 1;
4051 http->server_ssl = 1;
4055 http->client_ssl = 0;
4056 http->server_ssl = 0;
4060 #ifdef FEATURE_HTTPS_INSPECTION
4062 * Log the request unless we're https inspecting
4063 * in which case we don't have the path yet and
4064 * will log the request later.
4066 if (!client_use_ssl(csp))
4069 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4072 if (http->ssl && connect_port_is_forbidden(csp))
4074 const char *acceptable_connect_ports =
4075 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4076 assert(NULL != acceptable_connect_ports);
4077 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4078 "limit-connect{%s} doesn't allow CONNECT requests to %s",
4079 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4080 csp->action->flags |= ACTION_BLOCK;
4082 #ifdef FEATURE_HTTPS_INSPECTION
4083 http->client_ssl = 0;
4084 http->server_ssl = 0;
4089 freez(csp->headers->first->str);
4090 build_request_line(csp, fwd, &csp->headers->first->str);
4093 * We have a request. Check if one of the crunchers wants it
4094 * unless the client wants to use TLS/SSL in which case we
4095 * haven't setup the TLS context yet and will send the crunch
4099 #ifdef FEATURE_HTTPS_INSPECTION
4100 !client_use_ssl(csp) &&
4102 crunch_response_triggered(csp, crunchers_all))
4105 * Yes. The client got the crunch response and we're done here.
4110 log_applied_actions(csp->action);
4111 if (fwd->forward_host)
4113 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4114 fwd->forward_host, fwd->forward_port, http->hostport);
4118 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4121 /* here we connect to the server, gateway, or the forwarder */
4123 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4124 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4125 && socket_is_still_alive(csp->server_connection.sfd)
4126 && connection_destination_matches(&csp->server_connection, http, fwd))
4128 log_error(LOG_LEVEL_CONNECT,
4129 "Reusing server socket %d connected to %s. Total requests: %u.",
4130 csp->server_connection.sfd, csp->server_connection.host,
4131 csp->server_connection.requests_sent_total);
4135 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4137 #ifdef FEATURE_CONNECTION_SHARING
4138 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4139 #ifdef FEATURE_HTTPS_INSPECTION
4140 && !server_use_ssl(csp)
4144 remember_connection(&csp->server_connection);
4147 #endif /* def FEATURE_CONNECTION_SHARING */
4149 log_error(LOG_LEVEL_CONNECT,
4150 "Closing server socket %d connected to %s. Total requests: %u.",
4151 csp->server_connection.sfd, csp->server_connection.host,
4152 csp->server_connection.requests_sent_total);
4153 close_socket(csp->server_connection.sfd);
4155 mark_connection_closed(&csp->server_connection);
4157 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4158 #ifdef FEATURE_HTTPS_INSPECTION
4159 if (http->ssl && !use_ssl_tunnel)
4163 * Creating a SSL proxy.
4165 * By sending the CSUCCEED message we're lying to the client as
4166 * the connection hasn't actually been established yet. We don't
4167 * establish the connection until we have seen and parsed the
4168 * encrypted client headers.
4170 if (write_socket_delayed(csp->cfd, CSUCCEED,
4171 strlen(CSUCCEED), get_write_delay(csp)) != 0)
4173 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4177 ret = create_client_ssl_connection(csp);
4180 log_error(LOG_LEVEL_ERROR,
4181 "Failed to open a secure connection with the client");
4184 if (JB_ERR_OK != process_encrypted_request(csp))
4186 close_client_ssl_connection(csp);
4190 * We have an encrypted request. Check if one of the crunchers now
4191 * wants it (for example because the previously invisible path was
4192 * required to match).
4194 if (crunch_response_triggered(csp, crunchers_all))
4197 * Yes. The client got the crunch response and we're done here.
4204 * Connecting to destination server
4206 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4208 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4210 if (fwd->type != SOCKS_NONE)
4213 rsp = error_response(csp, "forwarding-failed");
4215 else if (errno == EINVAL)
4217 rsp = error_response(csp, "no-such-domain");
4221 rsp = error_response(csp, "connect-failed");
4224 /* Write the answer to the client */
4227 send_crunch_response(csp, rsp);
4231 * Temporary workaround to prevent already-read client
4232 * bodies from being parsed as new requests. For now we
4233 * err on the safe side and throw all the following
4234 * requests under the bus, even if no client body has been
4235 * buffered. A compliant client will repeat the dropped
4236 * requests on an untainted connection.
4238 * The proper fix is to discard the no longer needed
4239 * client body in the buffer (if there is one) and to
4240 * continue parsing the bytes that follow.
4242 #ifdef FEATURE_HTTPS_INSPECTION
4243 close_client_ssl_connection(csp);
4245 drain_and_close_socket(csp->cfd);
4246 csp->cfd = JB_INVALID_SOCKET;
4251 #ifdef FEATURE_HTTPS_INSPECTION
4253 * Creating TLS/SSL connections with destination server or parent
4254 * proxy. If forwarding is enabled, we must send client request to
4255 * parent proxy and receive, parse and resend parent proxy answer.
4257 if (http->ssl && !use_ssl_tunnel)
4259 if (fwd->forward_host != NULL)
4261 char server_response[BUFFER_SIZE];
4264 char *hdr = list_to_text(csp->headers);
4265 memset(server_response, 0, sizeof(server_response));
4269 log_error(LOG_LEVEL_FATAL,
4270 "Out of memory parsing client header");
4272 list_remove_all(csp->headers);
4275 * Sending client's CONNECT request to the parent proxy
4277 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4283 log_error(LOG_LEVEL_CONNECT,
4284 "Sending request headers to: %s failed", http->hostport);
4285 mark_server_socket_tainted(csp);
4286 close_client_ssl_connection(csp);
4290 /* Waiting for parent proxy server response */
4291 len = read_socket(csp->server_connection.sfd, server_response,
4292 sizeof(server_response)-1);
4296 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4297 "server on socket %d.", csp->server_connection.sfd);
4299 rsp = error_response(csp, "no-server-data");
4302 send_crunch_response(csp, rsp);
4304 mark_server_socket_tainted(csp);
4305 close_client_ssl_connection(csp);
4310 * Test if the connection to the destination server was
4311 * established successfully by the parent proxy.
4313 if (!tunnel_established_successfully(server_response, (unsigned int)len))
4315 log_error(LOG_LEVEL_ERROR,
4316 "The forwarder %s failed to establish a connection with %s",
4317 fwd->forward_host, http->host);
4318 rsp = error_response(csp, "connect-failed");
4321 send_crunch_response(csp, rsp);
4323 mark_server_socket_tainted(csp);
4324 close_client_ssl_connection(csp);
4327 } /* -END- if (fwd->forward_host != NULL) */
4330 * We can now create the TLS/SSL connection with the destination server.
4332 int ret = create_server_ssl_connection(csp);
4335 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4336 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4339 * If the server certificate is invalid, we must inform
4340 * the client and then close connection to the client.
4342 ssl_send_certificate_error(csp);
4343 close_client_and_server_ssl_connections(csp);
4346 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4347 || csp->server_cert_verification_result == SSL_CERT_VALID)
4350 * The TLS/SSL connection wasn't created but an invalid
4351 * certificate wasn't detected. Report it as connection
4354 rsp = error_response(csp, "connect-failed");
4357 send_crunch_response(csp, rsp);
4359 close_client_and_server_ssl_connections(csp);
4363 }/* -END- if (http->ssl) */
4364 #endif /* def FEATURE_HTTPS_INSPECTION */
4366 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4367 save_connection_destination(csp->server_connection.sfd,
4368 http, fwd, &csp->server_connection);
4369 csp->server_connection.keep_alive_timeout =
4370 (unsigned)csp->config->keep_alive_timeout;
4372 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4374 csp->server_connection.requests_sent_total++;
4376 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4378 /* Client headers have been sent optimistically */
4379 assert(csp->headers->last == NULL);
4381 else if (http->ssl == 0 || (fwd->forward_host
4382 #ifdef FEATURE_HTTPS_INSPECTION
4387 if (send_http_request(csp))
4389 rsp = error_response(csp, "connect-failed");
4392 send_crunch_response(csp, rsp);
4400 * Using old solution with SSL tunnel or new solution with SSL proxy
4402 list_remove_all(csp->headers);
4403 #ifdef FEATURE_HTTPS_INSPECTION
4408 * We're running an SSL tunnel and we're not forwarding,
4409 * so just ditch the client headers, send the "connect succeeded"
4410 * message to the client, flush the rest, and get out of the way.
4412 if (write_socket_delayed(csp->cfd, CSUCCEED,
4413 strlen(CSUCCEED), get_write_delay(csp)))
4418 #ifdef FEATURE_HTTPS_INSPECTION
4422 * If server certificate has been verified and is invalid,
4423 * we must inform the client and then close the connection
4424 * with client and server.
4426 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4427 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4429 ssl_send_certificate_error(csp);
4430 close_client_and_server_ssl_connections(csp);
4433 if (send_https_request(csp))
4435 rsp = error_response(csp, "connect-failed");
4438 send_crunch_response(csp, rsp);
4440 close_client_and_server_ssl_connections(csp);
4444 #endif /* def FEATURE_HTTPS_INSPECTION */
4445 clear_iob(csp->client_iob);
4446 }/* -END- else ... if (http->ssl == 1) */
4448 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4450 /* XXX: should the time start earlier for optimistically sent data? */
4451 csp->server_connection.request_sent = time(NULL);
4453 handle_established_connection(csp);
4454 freez(csp->receive_buffer);
4459 /*********************************************************************
4461 * Function : fuzz_server_response
4463 * Description : Treat the input as a whole server response.
4466 * 1 : csp = Current client state (buffers, headers, etc...)
4467 * 2 : fuzz_input_file = File to read the input from.
4471 *********************************************************************/
4472 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4474 static struct forward_spec fwd; /* Zero'd due to being static */
4477 if (strcmp(fuzz_input_file, "-") == 0)
4479 /* XXX: Doesn't work yet. */
4480 csp->server_connection.sfd = 0;
4484 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4485 if (csp->server_connection.sfd == -1)
4487 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4492 csp->content_type |= CT_GIF;
4493 csp->action->flags |= ACTION_DEANIMATE;
4494 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4496 csp->http->path = strdup_or_die("/");
4497 csp->http->host = strdup_or_die("fuzz.example.org");
4498 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4499 /* Prevent client socket monitoring */
4500 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4501 csp->flags |= CSP_FLAG_CHUNKED;
4503 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4504 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4506 csp->content_type |= CT_DECLARED|CT_GIF;
4508 csp->config->socket_timeout = 0;
4510 cgi_init_error_messages();
4512 handle_established_connection(csp);
4513 freez(csp->receive_buffer);
4520 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4521 /*********************************************************************
4523 * Function : prepare_csp_for_next_request
4525 * Description : Put the csp in a mostly vergin state.
4528 * 1 : csp = Current client state (buffers, headers, etc...)
4532 *********************************************************************/
4533 static void prepare_csp_for_next_request(struct client_state *csp)
4535 csp->content_type = 0;
4536 csp->content_length = 0;
4537 csp->expected_content_length = 0;
4538 csp->expected_client_content_length = 0;
4539 list_remove_all(csp->headers);
4540 clear_iob(csp->iob);
4541 freez(csp->error_message);
4542 free_http_request(csp->http);
4543 destroy_list(csp->headers);
4544 #ifdef FEATURE_HTTPS_INSPECTION
4545 destroy_list(csp->https_headers);
4547 destroy_list(csp->tags);
4548 #ifdef FEATURE_CLIENT_TAGS
4549 destroy_list(csp->client_tags);
4550 freez(csp->client_address);
4552 free_current_action(csp->action);
4553 if (NULL != csp->fwd)
4555 unload_forward_spec(csp->fwd);
4558 /* XXX: Store per-connection flags someplace else. */
4559 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4560 #ifdef FEATURE_TOGGLE
4561 if (global_toggle_state)
4562 #endif /* def FEATURE_TOGGLE */
4564 csp->flags |= CSP_FLAG_TOGGLED_ON;
4567 if (csp->client_iob->eod > csp->client_iob->cur)
4569 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4570 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4572 assert(bytes_to_shift > 0);
4573 assert(data_length > 0);
4575 log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4576 data_length, bytes_to_shift);
4577 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4578 csp->client_iob->cur = csp->client_iob->buf;
4579 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4580 csp->client_iob->eod = csp->client_iob->buf + data_length;
4581 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4583 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4588 * We mainly care about resetting client_iob->cur so we don't
4589 * waste buffer space at the beginning and don't mess up the
4590 * request restoration done by cgi_show_request().
4592 * Freeing the buffer itself isn't technically necessary,
4593 * but makes debugging more convenient.
4595 clear_iob(csp->client_iob);
4598 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4601 /*********************************************************************
4605 * Description : This is little more than chat. We only "serve" to
4606 * to close (or remember) any socket that chat may have
4610 * 1 : csp = Current client state (buffers, headers, etc...)
4614 *********************************************************************/
4615 static void serve(struct client_state *csp)
4617 int config_file_change_detected = 0; /* Only used for debugging */
4618 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4619 #ifdef FEATURE_CONNECTION_SHARING
4620 static int monitor_thread_running = 0;
4621 #endif /* def FEATURE_CONNECTION_SHARING */
4622 int continue_chatting = 0;
4624 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4625 csp->ip_addr_str, csp->cfd);
4629 unsigned int latency;
4631 #ifdef FEATURE_HTTPS_INSPECTION
4632 if (continue_chatting && client_use_ssl(csp))
4634 continue_https_chat(csp);
4643 * If the request has been crunched,
4644 * the calculated latency is zero.
4646 latency = (unsigned)(csp->server_connection.response_received -
4647 csp->server_connection.request_sent) / 2;
4649 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4650 && (csp->flags & CSP_FLAG_CRUNCHED)
4651 && (csp->expected_client_content_length != 0))
4653 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4654 log_error(LOG_LEVEL_CONNECT,
4655 "Tainting client socket %d due to unread data.", csp->cfd);
4658 continue_chatting = (csp->config->feature_flags
4659 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4660 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4661 && (csp->cfd != JB_INVALID_SOCKET)
4662 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4663 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4664 || (csp->flags & CSP_FLAG_CHUNKED));
4666 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4667 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4669 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4671 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4673 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4674 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4675 || !socket_is_still_alive(csp->server_connection.sfd)
4676 || !(latency < csp->server_connection.keep_alive_timeout))
4678 log_error(LOG_LEVEL_CONNECT,
4679 "Closing server socket %d connected to %s. "
4680 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4681 csp->server_connection.sfd, csp->server_connection.host,
4682 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4683 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4684 socket_is_still_alive(csp->server_connection.sfd),
4685 csp->server_connection.keep_alive_timeout);
4686 #ifdef FEATURE_CONNECTION_SHARING
4687 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4689 forget_connection(csp->server_connection.sfd);
4691 #endif /* def FEATURE_CONNECTION_SHARING */
4692 #ifdef FEATURE_HTTPS_INSPECTION
4693 close_server_ssl_connection(csp);
4695 close_socket(csp->server_connection.sfd);
4696 mark_connection_closed(&csp->server_connection);
4700 if (continue_chatting && any_loaded_file_changed(csp))
4702 continue_chatting = 0;
4703 config_file_change_detected = 1;
4705 #ifdef FEATURE_HTTPS_INSPECTION
4706 if (continue_chatting && client_use_ssl(csp) &&
4707 csp->ssl_with_client_is_opened == 0)
4709 continue_chatting = 0;
4710 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4711 "The TLS session has been terminated.", csp->cfd);
4715 if (continue_chatting)
4717 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4718 && socket_is_still_alive(csp->cfd))
4720 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4721 "pipelined on socket %d and the socket is still alive.",
4722 csp->requests_received_total+1, csp->cfd);
4723 prepare_csp_for_next_request(csp);
4727 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4729 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4731 log_error(LOG_LEVEL_CONNECT,
4732 "Waiting for the next client request on socket %d. "
4733 "Keeping the server socket %d to %s open.",
4734 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4738 log_error(LOG_LEVEL_CONNECT,
4739 "Waiting for the next client request on socket %d. "
4740 "No server socket to keep open.", csp->cfd);
4744 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4745 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4746 && socket_is_still_alive(csp->cfd))
4748 log_error(LOG_LEVEL_CONNECT,
4749 "Data arrived in time on client socket %d. Requests so far: %u",
4750 csp->cfd, csp->requests_received_total);
4751 prepare_csp_for_next_request(csp);
4755 #ifdef FEATURE_CONNECTION_SHARING
4756 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4757 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4758 && (socket_is_still_alive(csp->server_connection.sfd))
4759 #ifdef FEATURE_HTTPS_INSPECTION
4760 && !server_use_ssl(csp)
4764 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4766 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4771 remember_connection(&csp->server_connection);
4772 csp->server_connection.sfd = JB_INVALID_SOCKET;
4773 drain_and_close_socket(csp->cfd);
4774 csp->cfd = JB_INVALID_SOCKET;
4775 privoxy_mutex_lock(&connection_reuse_mutex);
4776 if (!monitor_thread_running)
4778 monitor_thread_running = 1;
4779 privoxy_mutex_unlock(&connection_reuse_mutex);
4780 wait_for_alive_connections();
4781 privoxy_mutex_lock(&connection_reuse_mutex);
4782 monitor_thread_running = 0;
4784 privoxy_mutex_unlock(&connection_reuse_mutex);
4786 #endif /* def FEATURE_CONNECTION_SHARING */
4790 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4792 log_error(LOG_LEVEL_CONNECT,
4793 "Closing server socket %d connected to %s. Keep-alive: %u. "
4794 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4795 "Configuration file change detected: %u",
4796 csp->server_connection.sfd, csp->server_connection.host,
4797 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4798 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4799 socket_is_still_alive(csp->server_connection.sfd),
4800 csp->server_connection.keep_alive_timeout,
4801 config_file_change_detected);
4803 } while (continue_chatting);
4807 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4809 if (csp->cfd != JB_INVALID_SOCKET)
4811 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4812 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4813 "Configuration file change detected: %u. Requests received: %u.",
4814 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4815 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4816 config_file_change_detected, csp->requests_received_total);
4817 #ifdef FEATURE_HTTPS_INSPECTION
4818 close_client_ssl_connection(csp);
4820 drain_and_close_socket(csp->cfd);
4823 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4825 #ifdef FEATURE_CONNECTION_SHARING
4826 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4828 forget_connection(csp->server_connection.sfd);
4830 #endif /* def FEATURE_CONNECTION_SHARING */
4832 #ifdef FEATURE_HTTPS_INSPECTION
4833 close_server_ssl_connection(csp);
4834 #endif /* def FEATURE_HTTPS_INSPECTION */
4836 close_socket(csp->server_connection.sfd);
4839 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4840 mark_connection_closed(&csp->server_connection);
4843 free_csp_resources(csp);
4845 csp->flags &= ~CSP_FLAG_ACTIVE;
4851 /*********************************************************************
4853 * Function : server_thread
4855 * Description : We only exist to call `serve' in a threaded environment.
4858 * 1 : data = Current client state (buffers, headers, etc...)
4860 * Returns : Always 0.
4862 *********************************************************************/
4863 static int32 server_thread(void *data)
4865 serve((struct client_state *) data);
4872 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4873 /*********************************************************************
4877 * Description : Print usage info & exit.
4879 * Parameters : Pointer to argv[0] for identifying ourselves
4883 *********************************************************************/
4884 static void usage(const char *name)
4886 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4887 "Usage: %s [--config-test] "
4890 #endif /* defined(unix) */
4893 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4894 #endif /* defined(unix) */
4895 "[--version] [configfile]\n",
4899 show_fuzz_usage(name);
4902 printf("Aborting\n");
4907 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4910 #ifdef MUTEX_LOCKS_AVAILABLE
4911 /*********************************************************************
4913 * Function : privoxy_mutex_lock
4915 * Description : Locks a mutex.
4918 * 1 : mutex = The mutex to lock.
4920 * Returns : Void. May exit in case of errors.
4922 *********************************************************************/
4923 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4925 #ifdef FEATURE_PTHREAD
4926 int err = pthread_mutex_lock(mutex);
4929 if (mutex != &log_mutex)
4931 log_error(LOG_LEVEL_FATAL,
4932 "Mutex locking failed: %s.\n", strerror(err));
4937 EnterCriticalSection(mutex);
4938 #endif /* def FEATURE_PTHREAD */
4942 /*********************************************************************
4944 * Function : privoxy_mutex_unlock
4946 * Description : Unlocks a mutex.
4949 * 1 : mutex = The mutex to unlock.
4951 * Returns : Void. May exit in case of errors.
4953 *********************************************************************/
4954 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4956 #ifdef FEATURE_PTHREAD
4957 int err = pthread_mutex_unlock(mutex);
4960 if (mutex != &log_mutex)
4962 log_error(LOG_LEVEL_FATAL,
4963 "Mutex unlocking failed: %s.\n", strerror(err));
4968 LeaveCriticalSection(mutex);
4969 #endif /* def FEATURE_PTHREAD */
4973 /*********************************************************************
4975 * Function : privoxy_mutex_init
4977 * Description : Prepares a mutex.
4980 * 1 : mutex = The mutex to initialize.
4982 * Returns : Void. May exit in case of errors.
4984 *********************************************************************/
4985 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4987 #ifdef FEATURE_PTHREAD
4988 int err = pthread_mutex_init(mutex, 0);
4991 printf("Fatal error. Mutex initialization failed: %s.\n",
4996 InitializeCriticalSection(mutex);
4997 #endif /* def FEATURE_PTHREAD */
4999 #endif /* def MUTEX_LOCKS_AVAILABLE */
5001 /*********************************************************************
5003 * Function : initialize_mutexes
5005 * Description : Prepares mutexes if mutex support is available.
5009 * Returns : Void, exits in case of errors.
5011 *********************************************************************/
5012 static void initialize_mutexes(void)
5014 #ifdef MUTEX_LOCKS_AVAILABLE
5016 * Prepare global mutex semaphores
5019 #ifdef FEATURE_HTTPS_INSPECTION
5020 privoxy_mutex_init(&certificate_mutex);
5021 privoxy_mutex_init(&ssl_init_mutex);
5024 privoxy_mutex_init(&log_mutex);
5025 privoxy_mutex_init(&log_init_mutex);
5026 privoxy_mutex_init(&connection_reuse_mutex);
5027 #ifdef FEATURE_EXTERNAL_FILTERS
5028 privoxy_mutex_init(&external_filter_mutex);
5030 #ifdef FEATURE_CLIENT_TAGS
5031 privoxy_mutex_init(&client_tags_mutex);
5033 #ifdef FEATURE_EXTENDED_STATISTICS
5034 privoxy_mutex_init(&filter_statistics_mutex);
5035 privoxy_mutex_init(&block_statistics_mutex);
5039 * XXX: The assumptions below are a bit naive
5040 * and can cause locks that aren't necessary.
5042 * For example older FreeBSD versions (< 6.x?)
5043 * have no gethostbyname_r, but gethostbyname is
5046 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5047 privoxy_mutex_init(&resolver_mutex);
5048 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5050 * XXX: should we use a single mutex for
5051 * localtime() and gmtime() as well?
5053 #ifndef HAVE_GMTIME_R
5054 privoxy_mutex_init(&gmtime_mutex);
5055 #endif /* ndef HAVE_GMTIME_R */
5057 #ifndef HAVE_LOCALTIME_R
5058 privoxy_mutex_init(&localtime_mutex);
5059 #endif /* ndef HAVE_GMTIME_R */
5061 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5062 privoxy_mutex_init(&rand_mutex);
5063 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5065 #endif /* def MUTEX_LOCKS_AVAILABLE */
5068 /*********************************************************************
5072 * Description : Load the config file and start the listen loop.
5073 * This function is a lot more *sane* with the `load_config'
5074 * and `listen_loop' functions; although it stills does
5075 * a *little* too much for my taste.
5078 * 1 : argc = Number of parameters (including $0).
5079 * 2 : argv = Array of (char *)'s to the parameters.
5081 * Returns : 1 if : can't open config file, unrecognized directive,
5082 * stats requested in multi-thread mode, can't open the
5083 * log file, can't open the jar file, listen port is invalid,
5084 * any load fails, and can't bind port.
5086 * Else main never returns, the process must be signaled
5087 * to terminate execution. Or, on Windows, use the
5088 * "File", "Exit" menu option.
5090 *********************************************************************/
5092 int real_main(int argc, char **argv)
5094 int main(int argc, char **argv)
5098 int do_config_test = 0;
5099 #ifndef HAVE_ARC4RANDOM
5100 unsigned int random_seed;
5103 struct passwd *pw = NULL;
5104 struct group *grp = NULL;
5106 char *pre_chroot_nslookup_to_load_resolver = NULL;
5109 char *fuzz_input_type = NULL;
5110 char *fuzz_input_file = NULL;
5117 #if !defined(_WIN32)
5124 /* Prepare mutexes if supported and necessary. */
5125 initialize_mutexes();
5127 /* Enable logging until further notice. */
5131 * Parse the command line arguments
5133 * XXX: simply printing usage information in case of
5134 * invalid arguments isn't particularly user friendly.
5136 while (++argc_pos < argc)
5139 /* Check to see if the service must be installed or uninstalled */
5140 if (strncmp(argv[argc_pos], "--install", 9) == 0)
5142 const char *pName = argv[argc_pos] + 9;
5145 exit((install_service(pName)) ? 0 : 1);
5147 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5149 const char *pName = argv[argc_pos] + 11;
5152 exit((uninstall_service(pName)) ? 0 : 1);
5154 else if (strcmp(argv[argc_pos], "--service") == 0)
5156 bRunAsService = TRUE;
5157 w32_set_service_cwd();
5158 atexit(w32_service_exit_notify);
5161 #endif /* defined(_WIN32) */
5164 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5166 if (strcmp(argv[argc_pos], "--help") == 0)
5171 else if (strcmp(argv[argc_pos], "--version") == 0)
5173 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5179 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5181 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5185 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5187 if (++argc_pos == argc) usage(argv[0]);
5188 pidfile = strdup_or_die(argv[argc_pos]);
5191 else if (strcmp(argv[argc_pos], "--user") == 0)
5196 if (++argc_pos == argc) usage(argv[argc_pos]);
5198 user_arg = strdup_or_die(argv[argc_pos]);
5199 group_name = strchr(user_arg, '.');
5200 if (NULL != group_name)
5202 /* Nul-terminate the user name */
5205 /* Skip the former delimiter to actually reach the group name */
5208 grp = getgrnam(group_name);
5211 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5214 pw = getpwnam(user_arg);
5217 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5223 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5225 if (++argc_pos == argc) usage(argv[0]);
5226 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5229 else if (strcmp(argv[argc_pos], "--chroot") == 0)
5233 #endif /* defined(unix) */
5235 else if (strcmp(argv[argc_pos], "--config-test") == 0)
5240 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5243 if (argc < argc_pos + 2) usage(argv[0]);
5244 fuzz_input_type = argv[argc_pos];
5246 fuzz_input_file = argv[argc_pos];
5248 else if (strcmp(argv[argc_pos], "--stfu") == 0)
5250 set_debug_level(LOG_LEVEL_STFU);
5253 else if (argc_pos + 1 != argc)
5256 * This is neither the last command line
5257 * option, nor was it recognized before,
5258 * therefore it must be invalid.
5264 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5266 configfile = argv[argc_pos];
5269 } /* -END- while (more arguments) */
5271 show_version(Argv[0]);
5274 if (*configfile != '/')
5276 char cwd[BUFFER_SIZE];
5278 size_t abs_file_size;
5280 /* make config-filename absolute here */
5281 if (NULL == getcwd(cwd, sizeof(cwd)))
5283 perror("failed to get current working directory");
5287 basedir = strdup_or_die(cwd);
5289 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5290 abs_file = malloc_or_die(abs_file_size);
5291 strlcpy(abs_file, basedir, abs_file_size);
5292 strlcat(abs_file, "/", abs_file_size);
5293 strlcat(abs_file, configfile, abs_file_size);
5294 configfile = abs_file;
5296 #endif /* defined unix */
5300 clients->next = NULL;
5302 /* XXX: factor out initialising after the next stable release. */
5307 #ifndef HAVE_ARC4RANDOM
5308 random_seed = (unsigned int)time(NULL);
5310 srandom(random_seed);
5313 #endif /* ifdef HAVE_RANDOM */
5314 #endif /* ifndef HAVE_ARC4RANDOM */
5317 * Unix signal handling
5319 * Catch the abort, interrupt and terminate signals for a graceful exit
5320 * Catch the hangup signal so the errlog can be reopened.
5322 * Ignore the broken pipe signal as connection failures
5323 * are handled when and where they occur without relying
5326 #if !defined(_WIN32)
5329 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5331 for (idx = 0; idx < SZ(catched_signals); idx++)
5333 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5334 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5336 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5337 #endif /* ifdef sun */
5339 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5343 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5345 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5349 #else /* ifdef _WIN32 */
5350 # ifdef _WIN_CONSOLE
5352 * We *are* in a windows console app.
5353 * Print a verbose messages about FAQ's and such
5355 printf("%s", win32_blurb);
5356 # endif /* def _WIN_CONSOLE */
5357 #endif /* def _WIN32 */
5360 if (fuzz_input_type != NULL)
5362 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5364 log_error(LOG_LEVEL_FATAL,
5365 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5366 "Various data structures are static which is unsafe when using threads.");
5371 exit(NULL == load_config());
5374 /* Initialize the CGI subsystem */
5375 cgi_init_error_messages();
5378 * If running on unix and without the --no-daemon
5379 * option, become a daemon. I.e. fork, detach
5380 * from tty and get process group leadership
5389 if (pid < 0) /* error */
5394 else if (pid != 0) /* parent */
5399 * must check for errors
5400 * child died due to missing files aso
5403 wpid = waitpid(pid, &status, WNOHANG);
5415 * stderr (fd 2) will be closed later on,
5416 * when the config file has been parsed.
5422 * Reserve fd 0 and 1 to prevent abort() and friends
5423 * from sending stuff to the clients or servers.
5425 fd = open("/dev/null", O_RDONLY);
5428 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5432 if (dup2(fd, 0) == -1)
5434 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5438 fd = open("/dev/null", O_WRONLY);
5441 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5445 if (dup2(fd, 1) == -1)
5447 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5452 #ifdef FEATURE_EXTERNAL_FILTERS
5453 for (fd = 0; fd < 3; fd++)
5455 mark_socket_for_close_on_execute(fd);
5459 if (chdir("/") != 0)
5461 log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5464 } /* -END- if (daemon_mode) */
5467 * As soon as we have written the PID file, we can switch
5468 * to the user and group ID indicated by the --user option
5470 if (pidfile != NULL)
5472 write_pid_file(pidfile);
5476 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5478 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5482 if (setgroups(1, &grp->gr_gid))
5484 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5487 else if (initgroups(pw->pw_name, pw->pw_gid))
5489 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5495 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5497 /* Read the time zone file from /etc before doing chroot. */
5499 if (NULL != pre_chroot_nslookup_to_load_resolver
5500 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5502 /* Initialize resolver library. */
5503 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5505 if (chroot(pw->pw_dir) < 0)
5507 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5511 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5514 if (setuid(pw->pw_uid))
5516 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5520 char putenv_dummy[64];
5522 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5523 if (putenv(putenv_dummy) != 0)
5525 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5528 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5529 if (putenv(putenv_dummy) != 0)
5531 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5537 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5540 #endif /* defined unix */
5543 /* This will be FALSE unless the command line specified --service
5547 /* Yup, so now we must attempt to establish a connection
5548 * with the service dispatcher. This will only work if this
5549 * process was launched by the service control manager to
5550 * actually run as a service. If this isn't the case, i've
5551 * known it take around 30 seconds or so for the call to return.
5554 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5555 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5557 /* Service has run, and at this point is now being stopped, so just return */
5562 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5564 /* An error occurred. Usually it's because --service was wrongly specified
5565 * and we were unable to connect to the Service Control Dispatcher because
5566 * it wasn't expecting us and is therefore not listening.
5568 * For now, just continue below to call the listen_loop function.
5571 #endif /* def _WIN32 */
5581 /*********************************************************************
5583 * Function : bind_port_helper
5585 * Description : Bind the listen port. Handles logging, and aborts
5589 * 1 : haddr = Host address to bind to. Use NULL to bind to
5591 * 2 : hport = Specifies port to bind to.
5592 * 3 : backlog = Listen backlog.
5594 * Returns : Port that was opened.
5596 *********************************************************************/
5597 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5602 result = bind_port(haddr, hport, backlog, &bfd);
5606 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5610 log_error(LOG_LEVEL_FATAL,
5611 "can't bind to %s:%d: There may be another Privoxy "
5612 "or some other proxy running on port %d",
5613 bind_address, hport, hport);
5616 log_error(LOG_LEVEL_FATAL,
5617 "can't bind to %s:%d: The hostname is not resolvable",
5618 bind_address, hport);
5621 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5622 bind_address, hport);
5625 /* shouldn't get here */
5626 return JB_INVALID_SOCKET;
5631 if (bfd >= FD_SETSIZE)
5633 log_error(LOG_LEVEL_FATAL,
5634 "Bind socket number too high to use select(): %d >= %d",
5642 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5647 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5655 /*********************************************************************
5657 * Function : bind_ports_helper
5659 * Description : Bind the listen ports. Handles logging, and aborts
5663 * 1 : config = Privoxy configuration. Specifies ports
5665 * 2 : sockets = Preallocated array of opened sockets
5666 * corresponding to specification in config.
5667 * All non-opened sockets will be set to
5668 * JB_INVALID_SOCKET.
5670 * Returns : Nothing. Inspect sockets argument.
5672 *********************************************************************/
5673 static void bind_ports_helper(struct configuration_spec * config,
5674 jb_socket sockets[])
5678 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5680 if (config->hport[i])
5682 sockets[i] = bind_port_helper(config->haddr[i],
5683 config->hport[i], config->listen_backlog);
5684 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5685 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5687 struct accept_filter_arg af_options;
5688 bzero(&af_options, sizeof(af_options));
5689 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5690 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5691 sizeof(af_options)))
5693 log_error(LOG_LEVEL_ERROR,
5694 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5701 sockets[i] = JB_INVALID_SOCKET;
5704 config->need_bind = 0;
5708 /*********************************************************************
5710 * Function : close_ports_helper
5712 * Description : Close listenings ports.
5715 * 1 : sockets = Array of opened and non-opened sockets to
5716 * close. All sockets will be set to
5717 * JB_INVALID_SOCKET.
5719 * Returns : Nothing.
5721 *********************************************************************/
5722 static void close_ports_helper(jb_socket sockets[])
5726 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5728 if (JB_INVALID_SOCKET != sockets[i])
5730 close_socket(sockets[i]);
5732 sockets[i] = JB_INVALID_SOCKET;
5738 /* Without this simple workaround we get this compiler warning from _beginthread
5739 * warning C4028: formal parameter 1 different from declaration
5741 void w32_service_listen_loop(void *p)
5745 #endif /* def _WIN32 */
5748 /*********************************************************************
5750 * Function : listen_loop
5752 * Description : bind the listen port and enter a "FOREVER" listening loop.
5758 *********************************************************************/
5759 static void listen_loop(void)
5761 struct client_states *csp_list = NULL;
5762 struct client_state *csp = NULL;
5763 jb_socket bfds[MAX_LISTENING_SOCKETS];
5764 struct configuration_spec *config;
5765 unsigned int active_threads = 0;
5766 #if defined(FEATURE_PTHREAD)
5767 pthread_attr_t attrs;
5769 pthread_attr_init(&attrs);
5770 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5773 config = load_config();
5775 #ifdef FEATURE_CONNECTION_SHARING
5777 * XXX: Should be relocated once it no
5778 * longer needs to emit log messages.
5780 initialize_reusable_connections();
5781 #endif /* def FEATURE_CONNECTION_SHARING */
5783 bind_ports_helper(config, bfds);
5785 #ifdef FEATURE_GRACEFUL_TERMINATION
5786 while (!g_terminate)
5791 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
5792 while (waitpid(-1, NULL, WNOHANG) > 0)
5794 /* zombie children */
5796 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5799 * Free data that was used by died threads
5801 active_threads = sweep();
5805 * Re-open the errlog after HUP signal
5807 if (received_hup_signal)
5809 if (NULL != config->logfile)
5811 init_error_log(Argv[0], config->logfile);
5813 received_hup_signal = 0;
5817 csp_list = zalloc_or_die(sizeof(*csp_list));
5818 csp = &csp_list->csp;
5820 log_error(LOG_LEVEL_CONNECT,
5821 "Waiting for the next client connection. Currently active threads: %u",
5825 * This config may be outdated, but for accept_connection()
5826 * it's fresh enough.
5828 csp->config = config;
5830 if (!accept_connection(csp, bfds))
5832 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5837 csp->flags |= CSP_FLAG_ACTIVE;
5838 csp->server_connection.sfd = JB_INVALID_SOCKET;
5840 csp->config = config = load_config();
5842 if (config->need_bind)
5845 * Since we were listening to the "old port", we will not see
5846 * a "listen" param change until the next request. So, at
5847 * least 1 more request must be made for us to find the new
5848 * setting. I am simply closing the old socket and binding the
5851 * Which-ever is correct, we will serve 1 more page via the
5852 * old settings. This should probably be a "show-status"
5853 * request. This should not be a so common of an operation
5854 * that this will hurt people's feelings.
5857 close_ports_helper(bfds);
5859 bind_ports_helper(config, bfds);
5862 #ifdef FEATURE_TOGGLE
5863 if (global_toggle_state)
5864 #endif /* def FEATURE_TOGGLE */
5866 csp->flags |= CSP_FLAG_TOGGLED_ON;
5869 if (run_loader(csp))
5871 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5872 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5876 if (block_acl(NULL,csp))
5878 log_error(LOG_LEVEL_CONNECT,
5879 "Connection from %s on %s (socket %d) dropped due to ACL",
5880 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5881 close_socket(csp->cfd);
5882 freez(csp->ip_addr_str);
5883 freez(csp->listen_addr_str);
5887 #endif /* def FEATURE_ACL */
5889 if ((0 != config->max_client_connections)
5890 && (active_threads >= config->max_client_connections))
5892 log_error(LOG_LEVEL_CONNECT,
5893 "Rejecting connection from %s. Maximum number of connections reached.",
5895 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5896 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5897 close_socket(csp->cfd);
5898 freez(csp->ip_addr_str);
5899 freez(csp->listen_addr_str);
5904 /* add it to the list of clients */
5905 csp_list->next = clients->next;
5906 clients->next = csp_list;
5908 if (config->multi_threaded)
5912 /* this is a switch () statement in the C preprocessor - ugh */
5913 #undef SELECTED_ONE_OPTION
5915 /* Use Pthreads in preference to native code */
5916 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5917 #define SELECTED_ONE_OPTION
5919 pthread_t the_thread;
5922 ret = pthread_create(&the_thread, &attrs,
5923 (void * (*)(void *))serve, csp);
5924 child_id = ret ? -1 : 0;
5928 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5929 #define SELECTED_ONE_OPTION
5930 child_id = _beginthread(
5931 (void (*)(void *))serve,
5936 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5937 #define SELECTED_ONE_OPTION
5939 thread_id tid = spawn_thread
5940 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5942 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5944 child_id = (int) tid;
5953 #if !defined(SELECTED_ONE_OPTION)
5956 /* This block is only needed when using fork().
5957 * When using threads, the server thread was
5958 * created and run by the call to _beginthread().
5960 if (child_id == 0) /* child */
5963 #ifdef FEATURE_TOGGLE
5964 int inherited_toggle_state = global_toggle_state;
5965 #endif /* def FEATURE_TOGGLE */
5970 * If we've been toggled or we've blocked the request, tell Mom
5973 #ifdef FEATURE_TOGGLE
5974 if (inherited_toggle_state != global_toggle_state)
5976 rc |= RC_FLAG_TOGGLED;
5978 #endif /* def FEATURE_TOGGLE */
5980 #ifdef FEATURE_STATISTICS
5981 if (csp->flags & CSP_FLAG_REJECTED)
5983 rc |= RC_FLAG_BLOCKED;
5985 #endif /* ndef FEATURE_STATISTICS */
5989 else if (child_id > 0) /* parent */
5991 /* in a fork()'d environment, the parent's
5992 * copy of the client socket and the CSP
5996 #if !defined(_WIN32) && !defined(__CYGWIN__)
5998 wait(&child_status);
6001 * Evaluate child's return code: If the child has
6002 * - been toggled, toggle ourselves
6003 * - blocked its request, bump up the stats counter
6006 #ifdef FEATURE_TOGGLE
6007 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6009 global_toggle_state = !global_toggle_state;
6011 #endif /* def FEATURE_TOGGLE */
6013 #ifdef FEATURE_STATISTICS
6015 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6019 #endif /* def FEATURE_STATISTICS */
6021 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6022 close_socket(csp->cfd);
6023 csp->flags &= ~CSP_FLAG_ACTIVE;
6027 #undef SELECTED_ONE_OPTION
6028 /* end of cpp switch () */
6033 * Spawning the child failed, assume it's because
6034 * there are too many children running already.
6035 * XXX: If you assume ...
6037 log_error(LOG_LEVEL_ERROR,
6038 "Unable to take any additional connections: %E. Active threads: %u",
6040 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6041 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6042 close_socket(csp->cfd);
6043 csp->flags &= ~CSP_FLAG_ACTIVE;
6052 #if defined(FEATURE_PTHREAD)
6053 pthread_attr_destroy(&attrs);
6056 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6058 #ifdef FEATURE_HTTPS_INSPECTION
6059 /* Clean up. Aim: free all memory (no leaks) */
6063 #ifdef FEATURE_GRACEFUL_TERMINATION
6065 log_error(LOG_LEVEL_INFO, "Graceful termination requested");
6067 unload_current_config_file();
6068 unload_current_actions_file();
6069 unload_current_re_filterfile();
6070 #ifdef FEATURE_TRUST
6071 unload_current_trust_file();
6074 if (config->multi_threaded)
6081 } while ((clients->next != NULL) && (--i > 0));
6085 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
6095 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6096 /* Cleanup - remove taskbar icon etc. */
6101 #endif /* FEATURE_GRACEFUL_TERMINATION */