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)
564 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
566 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
567 " Privoxy isn't configured to accept intercepted requests.",
568 csp->ip_addr_str, csp->http->cmd);
569 /* XXX: Use correct size */
570 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
571 csp->ip_addr_str, csp->http->cmd);
573 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
574 get_write_delay(csp));
575 destroy_list(headers);
579 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
581 /* Split the domain we just got for pattern matching */
582 init_domain_components(csp->http);
588 /* We can't work without destination. Go spread the news.*/
590 req = list_to_text(headers);
592 /* XXX: Use correct size */
593 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
594 csp->ip_addr_str, csp->http->cmd);
595 log_error(LOG_LEVEL_ERROR,
596 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
597 csp->ip_addr_str, csp->http->cmd, req);
600 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
601 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
602 destroy_list(headers);
607 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
608 * to get the destination IP address, use it as host directly
609 * or do a reverse DNS lookup first.
614 /*********************************************************************
616 * Function : get_server_headers
618 * Description : Parses server headers in iob and fills them
619 * into csp->headers so that they can later be
623 * 1 : csp = Current client state (buffers, headers, etc...)
625 * Returns : JB_ERR_OK if everything went fine, or
626 * JB_ERR_PARSE if the headers were incomplete.
628 *********************************************************************/
629 static jb_err get_server_headers(struct client_state *csp)
631 int continue_hack_in_da_house = 0;
634 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
639 * continue hack in da house. Ignore the ending of
640 * this head and continue enlisting header lines.
641 * The reason is described below.
643 enlist(csp->headers, "");
644 continue_hack_in_da_house = 0;
647 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
650 * It's a bodyless continue response, don't
651 * stop header parsing after reaching its end.
653 * As a result Privoxy will concatenate the
654 * next response's head and parse and deliver
655 * the headers as if they belonged to one request.
657 * The client will separate them because of the
658 * empty line between them.
660 * XXX: What we're doing here is clearly against
661 * the intended purpose of the continue header,
662 * and under some conditions (HTTP/1.0 client request)
663 * it's a standard violation.
665 * Anyway, "sort of against the spec" is preferable
666 * to "always getting confused by Continue responses"
667 * (Privoxy's behaviour before this hack was added)
669 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
670 continue_hack_in_da_house = 1;
672 else if (*header == '\0')
675 * If the header is empty, but the Continue hack
676 * isn't active, we can assume that we reached the
677 * end of the buffer before we hit the end of the
680 * Inform the caller an let it decide how to handle it.
685 if (JB_ERR_MEMORY == enlist(csp->headers, header))
688 * XXX: Should we quit the request and return a
689 * out of memory error page instead?
691 log_error(LOG_LEVEL_ERROR,
692 "Out of memory while enlisting server headers. %s lost.",
702 /*********************************************************************
704 * Function : crunch_reason
706 * Description : Translates the crunch reason code into a string.
709 * 1 : rsp = a http_response
711 * Returns : A string with the crunch reason or an error description.
713 *********************************************************************/
714 static const char *crunch_reason(const struct http_response *rsp)
716 char * reason = NULL;
721 return "Internal error while searching for crunch reason";
724 switch (rsp->crunch_reason)
727 reason = "Unsupported HTTP feature";
733 reason = "Untrusted";
736 reason = "Redirected";
742 reason = "DNS failure";
744 case FORWARDING_FAILED:
745 reason = "Forwarding failed";
748 reason = "Connection failure";
751 reason = "Out of memory (may mask other reasons)";
753 case CONNECTION_TIMEOUT:
754 reason = "Connection timeout";
757 reason = "No server data received";
760 reason = "No reason recorded";
768 /*********************************************************************
770 * Function : log_applied_actions
772 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
776 * 1 : actions = Current action spec to log
780 *********************************************************************/
781 static void log_applied_actions(const struct current_action_spec *actions)
784 * The conversion to text requires lots of memory allocations so
785 * we only do the conversion if the user is actually interested.
787 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
789 char *actions_as_text = actions_to_line_of_text(actions);
790 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
791 freez(actions_as_text);
796 /*********************************************************************
798 * Function : send_crunch_response
800 * Description : Delivers already prepared response for
801 * intercepted requests, logs the interception
802 * and frees the response.
805 * 1 : csp = Current client state (buffers, headers, etc...)
806 * 2 : rsp = Fully prepared response. Will be freed on exit.
810 *********************************************************************/
811 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
813 const struct http_request *http = csp->http;
817 assert(rsp->head != NULL);
821 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
825 * Extract the status code from the actual head
826 * that will be send to the client. It is the only
827 * way to get it right for all requests, including
828 * the fixed ones for out-of-memory problems.
830 * A head starts like this: 'HTTP/1.1 200...'
834 status_code[0] = rsp->head[9];
835 status_code[1] = rsp->head[10];
836 status_code[2] = rsp->head[11];
837 status_code[3] = '\0';
839 /* Log that the request was crunched and why. */
840 log_applied_actions(csp->action);
841 #ifdef FEATURE_HTTPS_INSPECTION
842 if (client_use_ssl(csp))
844 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
845 http->hostport, http->path);
846 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %llu",
847 csp->ip_addr_str, http->gpc, http->hostport, http->path,
848 http->version, status_code, rsp->content_length);
853 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
854 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
855 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
857 /* Write the answer to the client */
858 #ifdef FEATURE_HTTPS_INSPECTION
859 if (client_use_ssl(csp))
861 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
862 (const unsigned char *)rsp->head, rsp->head_length,
863 get_write_delay(csp)) < 0)
864 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
865 (const unsigned char *)rsp->body, rsp->content_length,
866 get_write_delay(csp)) < 0))
868 /* There is nothing we can do about it. */
869 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
870 "for https://%s%s through client socket %d using TLS/SSL",
871 http->hostport, http->url, csp->cfd);
877 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
878 get_write_delay(csp))
879 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
880 get_write_delay(csp)))
882 /* There is nothing we can do about it. */
883 log_error(LOG_LEVEL_CONNECT,
884 "Couldn't deliver the error message for %s through client socket %d: %E",
885 http->url, csp->cfd);
889 /* Clean up and return */
890 if (cgi_error_memory() != rsp)
892 free_http_response(rsp);
898 /*********************************************************************
900 * Function : crunch_response_triggered
902 * Description : Checks if the request has to be crunched,
903 * and delivers the crunch response if necessary.
906 * 1 : csp = Current client state (buffers, headers, etc...)
907 * 2 : crunchers = list of cruncher functions to run
909 * Returns : TRUE if the request was answered with a crunch response
912 *********************************************************************/
913 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
915 struct http_response *rsp = NULL;
916 const struct cruncher *c;
919 * If CGI request crunching is disabled,
920 * check the CGI dispatcher out of order to
921 * prevent unintentional blocks or redirects.
923 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
924 && (NULL != (rsp = dispatch_cgi(csp))))
926 /* Deliver, log and free the interception response. */
927 send_crunch_response(csp, rsp);
928 csp->flags |= CSP_FLAG_CRUNCHED;
932 for (c = crunchers; c->cruncher != NULL; c++)
935 * Check the cruncher if either Privoxy is toggled
936 * on and the request isn't forced, or if the cruncher
937 * applies to forced requests as well.
939 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
940 !(csp->flags & CSP_FLAG_FORCED)) ||
941 (c->flags & CF_IGNORE_FORCE))
943 rsp = c->cruncher(csp);
946 /* Deliver, log and free the interception response. */
947 send_crunch_response(csp, rsp);
948 csp->flags |= CSP_FLAG_CRUNCHED;
949 #ifdef FEATURE_STATISTICS
950 if (c->flags & CF_COUNT_AS_REJECT)
952 csp->flags |= CSP_FLAG_REJECTED;
954 #endif /* def FEATURE_STATISTICS */
965 /*********************************************************************
967 * Function : build_request_line
969 * Description : Builds the HTTP request line.
971 * If a HTTP forwarder is used it expects the whole URL,
972 * web servers only get the path.
975 * 1 : csp = Current client state (buffers, headers, etc...)
976 * 2 : fwd = The forwarding spec used for the request
977 * XXX: Should use http->fwd instead.
978 * 3 : request_line = The old request line which will be replaced.
980 * Returns : Nothing. Terminates in case of memory problems.
982 *********************************************************************/
983 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
985 struct http_request *http = csp->http;
988 * Downgrade http version from 1.1 to 1.0
989 * if +downgrade action applies.
991 if ((csp->action->flags & ACTION_DOWNGRADE)
992 && (!strcmpic(http->version, "HTTP/1.1")))
994 freez(http->version);
995 http->version = strdup_or_die("HTTP/1.0");
999 * Rebuild the request line.
1001 freez(*request_line);
1002 *request_line = strdup(http->gpc);
1003 string_append(request_line, " ");
1005 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1007 string_append(request_line, http->url);
1011 string_append(request_line, http->path);
1013 string_append(request_line, " ");
1014 string_append(request_line, http->version);
1016 if (*request_line == NULL)
1018 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1020 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1024 /*********************************************************************
1026 * Function : change_request_destination
1028 * Description : Parse a (rewritten) request line and regenerate
1029 * the http request data.
1032 * 1 : csp = Current client state (buffers, headers, etc...)
1034 * Returns : Forwards the parse_http_request() return code.
1035 * Terminates in case of memory problems.
1037 *********************************************************************/
1038 static jb_err change_request_destination(struct client_state *csp)
1040 struct http_request *http = csp->http;
1043 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1044 csp->headers->first->str);
1045 free_http_request(http);
1046 err = parse_http_request(csp->headers->first->str, http);
1047 if (JB_ERR_OK != err)
1049 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1050 jb_err_to_string(err));
1057 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1058 /*********************************************************************
1060 * Function : server_response_is_complete
1062 * Description : Determines whether we should stop reading
1063 * from the server socket.
1066 * 1 : csp = Current client state (buffers, headers, etc...)
1067 * 2 : content_length = Length of content received so far.
1069 * Returns : TRUE if the response is complete,
1072 *********************************************************************/
1073 static int server_response_is_complete(struct client_state *csp,
1074 unsigned long long content_length)
1076 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1078 if (!strcmpic(csp->http->gpc, "HEAD"))
1081 * "HEAD" implies no body, we are thus expecting
1082 * no content. XXX: incomplete "list" of methods?
1084 csp->expected_content_length = 0;
1085 content_length_known = TRUE;
1086 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1089 if (csp->http->status == 204 || csp->http->status == 304)
1092 * Expect no body. XXX: incomplete "list" of status codes?
1094 csp->expected_content_length = 0;
1095 content_length_known = TRUE;
1096 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1099 return (content_length_known && ((0 == csp->expected_content_length)
1100 || (csp->expected_content_length <= content_length)));
1104 #ifdef FEATURE_CONNECTION_SHARING
1105 /*********************************************************************
1107 * Function : wait_for_alive_connections
1109 * Description : Waits for alive connections to timeout.
1115 *********************************************************************/
1116 static void wait_for_alive_connections(void)
1118 int connections_alive = close_unusable_connections();
1120 while (0 < connections_alive)
1122 log_error(LOG_LEVEL_CONNECT,
1123 "Waiting for %d connections to timeout.",
1126 connections_alive = close_unusable_connections();
1129 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1132 #endif /* def FEATURE_CONNECTION_SHARING */
1135 /*********************************************************************
1137 * Function : save_connection_destination
1139 * Description : Remembers a connection for reuse later on.
1142 * 1 : sfd = Open socket to remember.
1143 * 2 : http = The destination for the connection.
1144 * 3 : fwd = The forwarder settings used.
1145 * 4 : server_connection = storage.
1149 *********************************************************************/
1150 void save_connection_destination(jb_socket sfd,
1151 const struct http_request *http,
1152 const struct forward_spec *fwd,
1153 struct reusable_connection *server_connection)
1155 assert(sfd != JB_INVALID_SOCKET);
1156 assert(NULL != http->host);
1158 server_connection->sfd = sfd;
1159 server_connection->host = strdup_or_die(http->host);
1160 server_connection->port = http->port;
1162 assert(NULL != fwd);
1163 assert(server_connection->gateway_host == NULL);
1164 assert(server_connection->gateway_port == 0);
1165 assert(server_connection->forwarder_type == 0);
1166 assert(server_connection->forward_host == NULL);
1167 assert(server_connection->forward_port == 0);
1169 server_connection->forwarder_type = fwd->type;
1170 if (NULL != fwd->gateway_host)
1172 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1176 server_connection->gateway_host = NULL;
1178 server_connection->gateway_port = fwd->gateway_port;
1180 if (NULL != fwd->forward_host)
1182 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1186 server_connection->forward_host = NULL;
1188 server_connection->forward_port = fwd->forward_port;
1190 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1193 /*********************************************************************
1195 * Function : verify_request_length
1197 * Description : Checks if we already got the whole client requests
1198 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1201 * Data that doesn't belong to the current request is
1202 * either thrown away to let the client retry on a clean
1203 * socket, or stashed to be dealt with after the current
1204 * request is served.
1207 * 1 : csp = Current client state (buffers, headers, etc...)
1211 *********************************************************************/
1212 static void verify_request_length(struct client_state *csp)
1214 unsigned long long buffered_request_bytes =
1215 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1217 if ((csp->expected_client_content_length != 0)
1218 && (buffered_request_bytes != 0))
1220 if (csp->expected_client_content_length >= buffered_request_bytes)
1222 csp->expected_client_content_length -= buffered_request_bytes;
1223 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1224 "to account for the %llu ones we already got.",
1225 csp->expected_client_content_length, buffered_request_bytes);
1229 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1230 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1231 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1232 "Marking the server socket tainted after throwing %llu bytes away.",
1233 buffered_request_bytes - csp->expected_client_content_length);
1234 csp->expected_client_content_length = 0;
1235 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1238 if (csp->expected_client_content_length == 0)
1240 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1244 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1245 && ((csp->client_iob->cur < csp->client_iob->eod)
1246 || (csp->expected_client_content_length != 0)))
1248 if (strcmpic(csp->http->gpc, "GET")
1249 && strcmpic(csp->http->gpc, "HEAD")
1250 && strcmpic(csp->http->gpc, "TRACE")
1251 && strcmpic(csp->http->gpc, "OPTIONS")
1252 && strcmpic(csp->http->gpc, "DELETE"))
1254 /* XXX: this is an incomplete hack */
1255 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1256 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1260 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1262 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1264 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1265 log_error(LOG_LEVEL_CONNECT,
1266 "Possible pipeline attempt detected. The connection will not "
1267 "be kept alive and we will only serve the first request.");
1268 /* Nuke the pipelined requests from orbit, just to be sure. */
1269 clear_iob(csp->client_iob);
1274 * Keep the pipelined data around for now, we'll deal with
1275 * it once we're done serving the current request.
1277 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1278 assert(csp->client_iob->eod >= csp->client_iob->cur);
1279 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1280 "%d bytes of pipelined data received.",
1281 (int)(csp->client_iob->eod - csp->client_iob->cur));
1287 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1288 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1293 /*********************************************************************
1295 * Function : mark_server_socket_tainted
1297 * Description : Makes sure we don't reuse a server socket
1298 * (if we didn't read everything the server sent
1299 * us reusing the socket would lead to garbage).
1302 * 1 : csp = Current client state (buffers, headers, etc...)
1306 *********************************************************************/
1307 static void mark_server_socket_tainted(struct client_state *csp)
1310 * For consistency we always mark the server socket
1311 * tainted, however, to reduce the log noise we only
1312 * emit a log message if the server socket could have
1313 * actually been reused.
1315 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1316 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1318 log_error(LOG_LEVEL_CONNECT,
1319 "Marking the server socket %d tainted.",
1320 csp->server_connection.sfd);
1322 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1325 /*********************************************************************
1327 * Function : get_request_line
1329 * Description : Read the client request line.
1332 * 1 : csp = Current client state (buffers, headers, etc...)
1334 * Returns : Pointer to request line or NULL in case of errors.
1336 *********************************************************************/
1337 static char *get_request_line(struct client_state *csp)
1339 char buf[BUFFER_SIZE];
1340 char *request_line = NULL;
1343 memset(buf, 0, sizeof(buf));
1345 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1348 * If there are multiple pipelined requests waiting,
1349 * the flag will be set again once the next request
1352 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1354 request_line = get_header(csp->client_iob);
1355 if ((NULL != request_line) && ('\0' != *request_line))
1357 return request_line;
1361 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1362 "received yet. Continuing reading from %d.", csp->cfd);
1370 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1372 !data_is_available(csp->cfd, csp->config->socket_timeout)
1375 if (socket_is_still_alive(csp->cfd))
1377 log_error(LOG_LEVEL_CONNECT,
1378 "No request line on socket %d received in time. Timeout: %d.",
1379 csp->cfd, csp->config->socket_timeout);
1380 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1381 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1382 get_write_delay(csp));
1386 log_error(LOG_LEVEL_CONNECT,
1387 "The client side of the connection on socket %d got "
1388 "closed without sending a complete request line.", csp->cfd);
1393 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1395 if (len <= 0) return NULL;
1398 * If there is no memory left for buffering the
1399 * request, there is nothing we can do but hang up
1401 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1406 request_line = get_header(csp->client_iob);
1408 } while ((NULL != request_line) && ('\0' == *request_line));
1410 return request_line;
1416 CHUNK_STATUS_MISSING_DATA,
1417 CHUNK_STATUS_BODY_COMPLETE,
1418 CHUNK_STATUS_PARSE_ERROR
1422 /*********************************************************************
1424 * Function : chunked_body_is_complete
1426 * Description : Figures out whether or not a chunked body is complete.
1428 * Currently it always starts at the beginning of the
1429 * buffer which is somewhat wasteful and prevents Privoxy
1430 * from starting to forward the correctly parsed chunks
1431 * as soon as theoretically possible.
1433 * Should be modified to work with a common buffer,
1434 * and allow the caller to skip already parsed chunks.
1436 * This would allow the function to be used for unbuffered
1437 * response bodies as well.
1440 * 1 : iob = Buffer with the body to check.
1441 * 2 : length = Length of complete body
1443 * Returns : Enum with the result of the check.
1445 *********************************************************************/
1446 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1448 unsigned int chunksize;
1454 * We need at least a single digit, followed by "\r\n",
1455 * followed by an unknown amount of data, followed by "\r\n".
1457 if (p + 5 > iob->eod)
1459 return CHUNK_STATUS_MISSING_DATA;
1461 if (sscanf(p, "%x", &chunksize) != 1)
1463 return CHUNK_STATUS_PARSE_ERROR;
1467 * We want at least a single digit, followed by "\r\n",
1468 * followed by the specified amount of data, followed by "\r\n".
1470 if (p + chunksize + 5 > iob->eod)
1472 return CHUNK_STATUS_MISSING_DATA;
1475 /* Skip chunk-size. */
1476 p = strstr(p, "\r\n");
1479 return CHUNK_STATUS_PARSE_ERROR;
1481 /* Move beyond the chunkdata. */
1484 /* There should be another "\r\n" to skip */
1485 if (memcmp(p, "\r\n", 2))
1487 return CHUNK_STATUS_PARSE_ERROR;
1490 } while (chunksize > 0U);
1492 *length = (size_t)(p - iob->cur);
1493 assert(*length <= (size_t)(iob->eod - iob->cur));
1494 assert(p <= iob->eod);
1496 return CHUNK_STATUS_BODY_COMPLETE;
1501 /*********************************************************************
1503 * Function : receive_chunked_client_request_body
1505 * Description : Read the chunk-encoded client request body.
1506 * Failures are dealt with.
1509 * 1 : csp = Current client state (buffers, headers, etc...)
1511 * Returns : JB_ERR_OK or JB_ERR_PARSE
1513 *********************************************************************/
1514 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1517 enum chunk_status status;
1519 while (CHUNK_STATUS_MISSING_DATA ==
1520 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1522 char buf[BUFFER_SIZE];
1525 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1527 log_error(LOG_LEVEL_ERROR,
1528 "Timeout while waiting for the client body.");
1531 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1534 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1537 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1542 if (status != CHUNK_STATUS_BODY_COMPLETE)
1544 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1545 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1546 log_error(LOG_LEVEL_CLF,
1547 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1548 return JB_ERR_PARSE;
1550 log_error(LOG_LEVEL_CONNECT,
1551 "Chunked client body completely read. Length: %d", body_length);
1552 csp->expected_client_content_length = body_length;
1560 /*********************************************************************
1562 * Function : fuzz_chunked_transfer_encoding
1564 * Description : Treat the fuzzed input as chunked transfer encoding
1565 * to check and dechunk.
1568 * 1 : csp = Used to store the data.
1569 * 2 : fuzz_input_file = File to read the input from.
1571 * Returns : Result of dechunking
1573 *********************************************************************/
1574 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1577 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1578 enum chunk_status status;
1580 status = chunked_body_is_complete(csp->iob, &length);
1581 if (CHUNK_STATUS_BODY_COMPLETE != status)
1583 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1586 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1591 /*********************************************************************
1593 * Function : fuzz_client_request
1595 * Description : Try to get a client request from the fuzzed input.
1598 * 1 : csp = Current client state (buffers, headers, etc...)
1599 * 2 : fuzz_input_file = File to read the input from.
1601 * Returns : Result of fuzzing.
1603 *********************************************************************/
1604 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1609 csp->ip_addr_str = "fuzzer";
1611 if (strcmp(fuzz_input_file, "-") != 0)
1613 log_error(LOG_LEVEL_FATAL,
1614 "Fuzzed client requests can currently only be read from stdin (-).");
1616 err = receive_client_request(csp);
1617 if (err != JB_ERR_OK)
1621 err = parse_client_request(csp);
1622 if (err != JB_ERR_OK)
1630 #endif /* def FUZZ */
1633 #ifdef FEATURE_FORCE_LOAD
1634 /*********************************************************************
1636 * Function : force_required
1638 * Description : Checks a request line to see if it contains
1639 * the FORCE_PREFIX. If it does, it is removed
1640 * unless enforcing requests has beend disabled.
1643 * 1 : request_line = HTTP request line
1645 * Returns : TRUE if force is required, FALSE otherwise.
1647 *********************************************************************/
1648 static int force_required(const struct client_state *csp, char *request_line)
1652 p = strstr(request_line, "http://");
1656 p += strlen("http://");
1660 /* Intercepted request usually don't specify the protocol. */
1664 /* Go to the beginning of the path */
1669 * If the path is missing the request line is invalid and we
1670 * are done here. The client-visible rejection happens later on.
1675 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1677 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1679 /* XXX: Should clean more carefully */
1680 strclean(request_line, FORCE_PREFIX);
1681 log_error(LOG_LEVEL_FORCE,
1682 "Enforcing request: \"%s\".", request_line);
1686 log_error(LOG_LEVEL_FORCE,
1687 "Ignored force prefix in request: \"%s\".", request_line);
1693 #endif /* def FEATURE_FORCE_LOAD */
1696 /*********************************************************************
1698 * Function : receive_client_request
1700 * Description : Read the client's request (more precisely the
1701 * client headers) and answer it if necessary.
1704 * 1 : csp = Current client state (buffers, headers, etc...)
1706 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1708 *********************************************************************/
1709 static jb_err receive_client_request(struct client_state *csp)
1711 char buf[BUFFER_SIZE];
1714 struct http_request *http;
1718 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1719 struct list header_list;
1720 struct list *headers = &header_list;
1722 /* We don't care if the arriving data is a valid HTTP request or not. */
1723 csp->requests_received_total++;
1727 memset(buf, 0, sizeof(buf));
1729 req = get_request_line(csp);
1732 mark_server_socket_tainted(csp);
1733 return JB_ERR_PARSE;
1735 assert(*req != '\0');
1737 if (client_protocol_is_unsupported(csp, req))
1739 return JB_ERR_PARSE;
1742 #ifdef FEATURE_FORCE_LOAD
1743 if (force_required(csp, req))
1745 csp->flags |= CSP_FLAG_FORCED;
1747 #endif /* def FEATURE_FORCE_LOAD */
1749 err = parse_http_request(req, http);
1751 if (JB_ERR_OK != err)
1753 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1754 get_write_delay(csp));
1755 /* XXX: Use correct size */
1756 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1757 log_error(LOG_LEVEL_ERROR,
1758 "Couldn't parse request line received from %s: %s",
1759 csp->ip_addr_str, jb_err_to_string(err));
1761 free_http_request(http);
1762 return JB_ERR_PARSE;
1765 /* grab the rest of the client's headers */
1769 p = get_header(csp->client_iob);
1773 /* There are no additional headers to read. */
1780 * We didn't receive a complete header
1781 * line yet, get the rest of it.
1783 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1785 log_error(LOG_LEVEL_ERROR,
1786 "Stopped grabbing the client headers.");
1787 destroy_list(headers);
1788 return JB_ERR_PARSE;
1791 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1794 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1795 destroy_list(headers);
1796 return JB_ERR_PARSE;
1799 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1802 * If there is no memory left for buffering the
1803 * request, there is nothing we can do but hang up
1805 destroy_list(headers);
1806 return JB_ERR_MEMORY;
1811 if (!strncmpic(p, "Transfer-Encoding:", 18))
1814 * XXX: should be called through sed()
1815 * but currently can't.
1817 client_transfer_encoding(csp, &p);
1820 * We were able to read a complete
1821 * header and can finally enlist it.
1828 if (http->host == NULL)
1831 * If we still don't know the request destination,
1832 * the request is invalid or the client uses
1833 * Privoxy without its knowledge.
1835 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1838 * Our attempts to get the request destination
1839 * elsewhere failed or Privoxy is configured
1840 * to only accept proxy requests.
1842 * An error response has already been send
1843 * and we're done here.
1845 return JB_ERR_PARSE;
1849 #ifdef FEATURE_CLIENT_TAGS
1850 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1851 set_client_address(csp, headers);
1852 get_tag_list_for_client(csp->client_tags, csp->client_address);
1856 * Determine the actions for this URL
1858 #ifdef FEATURE_TOGGLE
1859 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1861 /* Most compatible set of actions (i.e. none) */
1862 init_current_action(csp->action);
1865 #endif /* ndef FEATURE_TOGGLE */
1867 get_url_actions(csp, http);
1870 enlist(csp->headers, http->cmd);
1872 /* Append the previously read headers */
1873 err = list_append_list_unique(csp->headers, headers);
1874 destroy_list(headers);
1881 /*********************************************************************
1883 * Function : parse_client_request
1885 * Description : Parses the client's request and decides what to do
1888 * Note that since we're not using select() we could get
1889 * blocked here if a client connected, then didn't say
1893 * 1 : csp = Current client state (buffers, headers, etc...)
1895 * Returns : JB_ERR_OK or JB_ERR_PARSE
1897 *********************************************************************/
1898 static jb_err parse_client_request(struct client_state *csp)
1900 struct http_request *http = csp->http;
1903 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1904 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1905 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1906 && (csp->http->ssl == 0))
1908 /* Assume persistence until further notice */
1909 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1911 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1913 if (csp->http->ssl == 0)
1916 * This whole block belongs to chat() but currently
1917 * has to be executed before sed().
1919 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1921 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1923 return JB_ERR_PARSE;
1928 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1930 verify_request_length(csp);
1932 #ifndef FEATURE_HTTPS_INSPECTION
1935 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1939 err = sed(csp, FILTER_CLIENT_HEADERS);
1940 if (JB_ERR_OK != err)
1942 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1944 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1945 csp->ip_addr_str, csp->http->cmd);
1946 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1947 return JB_ERR_PARSE;
1949 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1951 /* Check request line for rewrites. */
1952 if ((NULL == csp->headers->first->str)
1953 || (strcmp(http->cmd, csp->headers->first->str) &&
1954 (JB_ERR_OK != change_request_destination(csp))))
1957 * A header filter broke the request line - bail out.
1959 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1960 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1961 /* XXX: Use correct size */
1962 log_error(LOG_LEVEL_CLF,
1963 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1964 log_error(LOG_LEVEL_ERROR,
1965 "Invalid request line after applying header filters.");
1966 free_http_request(http);
1968 return JB_ERR_PARSE;
1971 if (client_has_unsupported_expectations(csp))
1973 return JB_ERR_PARSE;
1981 /*********************************************************************
1983 * Function : send_http_request
1985 * Description : Sends the HTTP headers from the client request
1986 * and all the body data that has already been received.
1989 * 1 : csp = Current client state (buffers, headers, etc...)
1991 * Returns : 0 on success, anything else is an error.
1993 *********************************************************************/
1994 static int send_http_request(struct client_state *csp)
1999 hdr = list_to_text(csp->headers);
2002 /* FIXME Should handle error properly */
2003 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2005 list_remove_all(csp->headers);
2008 * Write the client's (modified) header to the server
2009 * (along with anything else that may be in the buffer)
2011 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2016 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2017 csp->http->hostport);
2019 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2020 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2023 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2024 csp->http->hostport);
2027 return write_failure;
2032 #ifdef FEATURE_HTTPS_INSPECTION
2033 /*********************************************************************
2035 * Function : receive_and_send_encrypted_post_data
2037 * Description : Reads remaining POST data from the client and sends
2041 * 1 : csp = Current client state (buffers, headers, etc...)
2043 * Returns : 0 on success, anything else is an error.
2045 *********************************************************************/
2046 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2048 int content_length_known = csp->expected_client_content_length != 0;
2050 while (is_ssl_pending(&(csp->ssl_client_attr))
2051 || (content_length_known && csp->expected_client_content_length != 0))
2053 unsigned char buf[BUFFER_SIZE];
2055 int max_bytes_to_read = sizeof(buf);
2057 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2059 max_bytes_to_read = (int)csp->expected_client_content_length;
2061 log_error(LOG_LEVEL_CONNECT,
2062 "Waiting for up to %d bytes of POST data from the client.",
2064 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2065 (unsigned)max_bytes_to_read);
2072 /* XXX: Does this actually happen? */
2075 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted POST data",
2077 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2082 if (csp->expected_client_content_length != 0)
2084 if (csp->expected_client_content_length >= len)
2086 csp->expected_client_content_length -= (unsigned)len;
2088 if (csp->expected_client_content_length == 0)
2090 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2096 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted POST data");
2103 /*********************************************************************
2105 * Function : send_https_request
2107 * Description : Sends the HTTP headers from the client request
2108 * and all the body data that has already been received.
2111 * 1 : csp = Current client state (buffers, headers, etc...)
2113 * Returns : 0 on success, anything else is an error.
2115 *********************************************************************/
2116 static int send_https_request(struct client_state *csp)
2122 hdr = list_to_text(csp->https_headers);
2125 /* FIXME Should handle error properly */
2126 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2128 list_remove_all(csp->https_headers);
2131 * Write the client's (modified) header to the server
2132 * (along with anything else that may be in the buffer)
2134 ret = ssl_send_data(&(csp->ssl_server_attr),
2135 (const unsigned char *)hdr, strlen(hdr));
2140 log_error(LOG_LEVEL_CONNECT,
2141 "Failed sending encrypted request headers to: %s: %E",
2142 csp->http->hostport);
2143 mark_server_socket_tainted(csp);
2147 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2148 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2149 csp->client_iob)) < 0))
2151 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2152 csp->http->hostport);
2157 if (csp->expected_client_content_length != 0)
2159 if (csp->expected_client_content_length < flushed)
2161 log_error(LOG_LEVEL_ERROR,
2162 "Flushed %d bytes of request body while only expecting %llu",
2163 flushed, csp->expected_client_content_length);
2164 csp->expected_client_content_length = 0;
2168 log_error(LOG_LEVEL_CONNECT,
2169 "Flushed %d bytes of request body while expecting %llu",
2170 flushed, csp->expected_client_content_length);
2171 csp->expected_client_content_length -= (unsigned)flushed;
2172 if (receive_and_send_encrypted_post_data(csp))
2180 log_error(LOG_LEVEL_CONNECT,
2181 "Flushed %d bytes of request body", flushed);
2185 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2192 /*********************************************************************
2194 * Function : receive_encrypted_request
2196 * Description : Receives an encrypted request.
2199 * 1 : csp = Current client state (buffers, headers, etc...)
2201 * Returns : JB_ERR_OK on success,
2202 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2204 *********************************************************************/
2205 static jb_err receive_encrypted_request(struct client_state *csp)
2207 char buf[BUFFER_SIZE];
2213 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2214 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2215 !data_is_available(csp->cfd, csp->config->socket_timeout))
2217 log_error(LOG_LEVEL_CONNECT,
2218 "Socket %d timed out while waiting for client headers", csp->cfd);
2219 return JB_ERR_PARSE;
2221 len = ssl_recv_data(&(csp->ssl_client_attr),
2222 (unsigned char *)buf, sizeof(buf));
2225 log_error(LOG_LEVEL_CONNECT,
2226 "Socket %d closed while waiting for client headers", csp->cfd);
2227 return JB_ERR_PARSE;
2231 return JB_ERR_PARSE;
2233 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2235 return JB_ERR_MEMORY;
2237 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2238 } while (p == NULL);
2240 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2246 /*********************************************************************
2248 * Function : process_encrypted_request
2250 * Description : Receives and parses an encrypted request.
2253 * 1 : csp = Current client state (buffers, headers, etc...)
2255 * Returns : JB_ERR_OK on success,
2256 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2258 *********************************************************************/
2259 static jb_err process_encrypted_request(struct client_state *csp)
2264 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2265 struct list header_list;
2266 struct list *headers = &header_list;
2268 assert(csp->ssl_with_client_is_opened);
2270 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2271 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2273 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2276 err = receive_encrypted_request(csp);
2277 if (err != JB_ERR_OK)
2279 if (csp->client_iob->cur == NULL)
2282 * We did not receive any data, most likely because the
2283 * client is done. Don't log this as a parse failure.
2285 return JB_ERR_PARSE;
2287 /* XXX: Also used for JB_ERR_MEMORY */
2288 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2289 jb_err_to_string(err));
2290 ssl_send_data_delayed(&(csp->ssl_client_attr),
2291 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2295 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2296 request_line = get_header(csp->client_iob);
2297 if (request_line == NULL)
2299 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2300 ssl_send_data_delayed(&(csp->ssl_client_attr),
2301 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2302 return JB_ERR_PARSE;
2304 assert(*request_line != '\0');
2306 if (client_protocol_is_unsupported(csp, request_line))
2309 * If the protocol is unsupported we're done here.
2310 * client_protocol_is_unsupported() took care of sending
2311 * the error response and logging the error message.
2313 return JB_ERR_PARSE;
2316 #ifdef FEATURE_FORCE_LOAD
2317 if (force_required(csp, request_line))
2319 csp->flags |= CSP_FLAG_FORCED;
2321 #endif /* def FEATURE_FORCE_LOAD */
2323 free_http_request(csp->http);
2325 err = parse_http_request(request_line, csp->http);
2326 /* XXX: Restore ssl setting. This is ugly */
2327 csp->http->client_ssl = 1;
2328 csp->http->server_ssl = 1;
2330 freez(request_line);
2331 if (JB_ERR_OK != err)
2333 ssl_send_data_delayed(&(csp->ssl_client_attr),
2334 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2335 /* XXX: Use correct size */
2336 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2337 log_error(LOG_LEVEL_ERROR,
2338 "Couldn't parse request line received from %s: %s",
2339 csp->ip_addr_str, jb_err_to_string(err));
2341 free_http_request(csp->http);
2342 return JB_ERR_PARSE;
2345 /* Parse the rest of the client's headers. */
2349 p = get_header(csp->client_iob);
2353 /* There are no additional headers to read. */
2360 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2363 * Our attempts to get the request destination
2366 log_error(LOG_LEVEL_ERROR,
2367 "Failed to get the encrypted request destination");
2368 ssl_send_data_delayed(&(csp->ssl_client_attr),
2369 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2370 return JB_ERR_PARSE;
2373 /* Split the domain we just got for pattern matching */
2374 init_domain_components(csp->http);
2376 #ifdef FEATURE_CLIENT_TAGS
2377 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2378 if (csp->client_address == NULL)
2380 set_client_address(csp, headers);
2381 get_tag_list_for_client(csp->client_tags, csp->client_address);
2385 #ifdef FEATURE_TOGGLE
2386 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2390 * Determine the actions for this request after
2391 * clearing the ones from the previous one.
2393 free_current_action(csp->action);
2394 get_url_actions(csp, csp->http);
2397 enlist(csp->https_headers, csp->http->cmd);
2399 /* Append the previously read headers */
2400 err = list_append_list_unique(csp->https_headers, headers);
2401 destroy_list(headers);
2402 if (JB_ERR_OK != err)
2404 /* XXX: Send error message */
2408 /* XXX: Work around crash */
2409 csp->error_message = NULL;
2411 /* XXX: Why do this here? */
2414 err = sed_https(csp);
2415 if (JB_ERR_OK != err)
2417 ssl_send_data_delayed(&(csp->ssl_client_attr),
2418 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2419 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2421 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2422 csp->ip_addr_str, csp->http->cmd);
2423 return JB_ERR_PARSE;
2426 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2427 log_applied_actions(csp->action);
2428 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2435 /*********************************************************************
2437 * Function : cgi_page_requested
2439 * Description : Checks if a request is for an internal CGI page.
2442 * 1 : host = The host requested by the client.
2444 * Returns : 1 if a CGI page has been requested, 0 otherwise
2446 *********************************************************************/
2447 static int cgi_page_requested(const char *host)
2449 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2450 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2451 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2452 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2462 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2463 /*********************************************************************
2465 * Function : continue_https_chat
2467 * Description : Behaves similar to chat() but only deals with
2468 * https-inspected requests that arrive on an already
2469 * established connection. The first request is always
2470 * served by chat() which is a lot more complex as it
2471 * has to deal with forwarding settings and connection
2474 * If a connection to the server has already been
2475 * opened it is reused unless the request is blocked.
2477 * If a connection to the server has not yet been
2478 * opened (because the previous request was crunched)
2479 * the connection is dropped so that the client retries
2482 * XXX: Forwarding settings are currently ignored.
2485 * 1 : csp = Current client state (buffers, headers, etc...)
2487 * Returns : Nothing.
2489 *********************************************************************/
2490 static void continue_https_chat(struct client_state *csp)
2492 if (JB_ERR_OK != process_encrypted_request(csp))
2497 csp->requests_received_total++;
2500 * We have an encrypted request. Check if one of the crunchers wants it.
2502 if (crunch_response_triggered(csp, crunchers_all))
2505 * Yes. The client got the crunch response and we're done here.
2509 if (csp->ssl_with_server_is_opened == 0)
2511 log_error(LOG_LEVEL_CONNECT,
2512 "Dropping the client connection on socket %d. "
2513 "The server connection has not been established yet.",
2515 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2518 if (send_https_request(csp))
2521 * Most likely the server connection timed out. We can't easily
2522 * create a new one so simply drop the client connection without a
2523 * error response to let the client retry.
2525 log_error(LOG_LEVEL_CONNECT,
2526 "Dropping client connection on socket %d. "
2527 "Forwarding the encrypted client request failed.",
2531 handle_established_connection(csp);
2532 freez(csp->receive_buffer);
2534 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2538 /*********************************************************************
2540 * Function : handle_established_connection
2542 * Description : Shuffle data between client and server once the
2543 * connection has been established.
2546 * 1 : csp = Current client state (buffers, headers, etc...)
2548 * Returns : Nothing.
2550 *********************************************************************/
2551 static void handle_established_connection(struct client_state *csp)
2557 struct pollfd poll_fds[2];
2561 struct timeval timeout;
2564 int ms_iis5_hack = 0;
2565 unsigned long long byte_count = 0;
2566 struct http_request *http;
2567 long len = 0; /* for buffer sizes (and negative error codes) */
2568 int buffer_and_filter_content = 0;
2569 unsigned int write_delay;
2570 #ifdef FEATURE_HTTPS_INSPECTION
2572 int use_ssl_tunnel = 0;
2573 csp->dont_verify_certificate = 0;
2575 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2577 /* Pass encrypted content without filtering. */
2582 /* Skeleton for HTTP response, if we should intercept the request */
2583 struct http_response *rsp;
2584 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2585 int watch_client_socket;
2588 csp->receive_buffer_size = csp->config->receive_buffer_size;
2589 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2590 if (csp->receive_buffer == NULL)
2592 log_error(LOG_LEVEL_ERROR,
2593 "Out of memory. Failed to allocate the receive buffer.");
2594 rsp = cgi_error_memory();
2595 send_crunch_response(csp, rsp);
2602 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2603 csp->cfd : csp->server_connection.sfd;
2606 /* pass data between the client and server
2607 * until one or the other shuts down the connection.
2612 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2613 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2615 write_delay = get_write_delay(csp);
2621 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2622 if (!watch_client_socket)
2624 maxfd = csp->server_connection.sfd;
2627 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2629 FD_SET(csp->cfd, &rfds);
2632 FD_SET(csp->server_connection.sfd, &rfds);
2633 #endif /* ndef HAVE_POLL */
2635 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2636 if ((csp->flags & CSP_FLAG_CHUNKED)
2637 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2638 && ((csp->iob->eod - csp->iob->cur) >= 5)
2639 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2642 * XXX: This check should be obsolete now,
2643 * but let's wait a while to be sure.
2645 log_error(LOG_LEVEL_CONNECT,
2646 "Looks like we got the last chunk together with "
2647 "the server headers but didn't detect it earlier. "
2648 "We better stop reading.");
2649 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2650 csp->expected_content_length = byte_count;
2651 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2653 if (server_body && server_response_is_complete(csp, byte_count))
2655 if (csp->expected_content_length == byte_count)
2657 log_error(LOG_LEVEL_CONNECT,
2658 "Done reading from server. Content length: %llu as expected. "
2659 "Bytes most recently read: %d.",
2664 log_error(LOG_LEVEL_CONNECT,
2665 "Done reading from server. Expected content length: %llu. "
2666 "Actual content length: %llu. Bytes most recently read: %d.",
2667 csp->expected_content_length, byte_count, len);
2671 * XXX: Should not jump around, handle_established_connection()
2672 * is complicated enough already.
2676 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2679 poll_fds[0].fd = csp->cfd;
2680 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2681 if (!watch_client_socket)
2684 * Ignore incoming data, but still watch out
2685 * for disconnects etc. These flags are always
2686 * implied anyway but explicitly setting them
2689 poll_fds[0].events = POLLERR|POLLHUP;
2694 poll_fds[0].events = POLLIN;
2696 poll_fds[1].fd = csp->server_connection.sfd;
2697 poll_fds[1].events = POLLIN;
2698 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2700 timeout.tv_sec = csp->config->socket_timeout;
2701 timeout.tv_usec = 0;
2702 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
2703 #endif /* def HAVE_POLL */
2705 /*server or client not responding in timeout */
2708 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2709 csp->config->socket_timeout, http->url);
2710 if ((byte_count == 0) && (http->ssl == 0))
2712 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2714 mark_server_socket_tainted(csp);
2715 #ifdef FEATURE_HTTPS_INSPECTION
2716 close_client_and_server_ssl_connections(csp);
2723 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2725 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2727 mark_server_socket_tainted(csp);
2728 #ifdef FEATURE_HTTPS_INSPECTION
2729 close_client_and_server_ssl_connections(csp);
2735 * This is the body of the browser's request,
2736 * just read and write it.
2738 * Receives data from browser and sends it to server
2740 * XXX: Make sure the client doesn't use pipelining
2741 * behind Privoxy's back.
2744 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2746 log_error(LOG_LEVEL_CONNECT,
2747 "The client socket %d has become unusable while "
2748 "the server socket %d is still open.",
2749 csp->cfd, csp->server_connection.sfd);
2750 mark_server_socket_tainted(csp);
2754 if (poll_fds[0].revents != 0)
2756 if (FD_ISSET(csp->cfd, &rfds))
2757 #endif /* def HAVE_POLL*/
2759 int max_bytes_to_read = (int)csp->receive_buffer_size;
2761 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2762 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2764 if (data_is_available(csp->cfd, 0))
2767 * If the next request is already waiting, we have
2768 * to stop select()ing the client socket. Otherwise
2769 * we would always return right away and get nothing
2772 watch_client_socket = 0;
2773 log_error(LOG_LEVEL_CONNECT,
2774 "Stop watching client socket %d. "
2775 "There's already another request waiting.",
2780 * If the client socket is set, but there's no data
2781 * available on the socket, the client went fishing
2782 * and continuing talking to the server makes no sense.
2784 log_error(LOG_LEVEL_CONNECT,
2785 "The client closed socket %d while "
2786 "the server socket %d is still open.",
2787 csp->cfd, csp->server_connection.sfd);
2788 mark_server_socket_tainted(csp);
2791 if (csp->expected_client_content_length != 0)
2793 if (csp->expected_client_content_length < csp->receive_buffer_size)
2795 max_bytes_to_read = (int)csp->expected_client_content_length;
2797 log_error(LOG_LEVEL_CONNECT,
2798 "Waiting for up to %d bytes from the client.",
2801 assert(max_bytes_to_read <= csp->receive_buffer_size);
2802 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2804 #ifdef FEATURE_HTTPS_INSPECTION
2805 if (client_use_ssl(csp))
2807 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
2811 #endif /* def FEATURE_HTTPS_INSPECTION */
2813 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2817 /* XXX: not sure if this is necessary. */
2818 mark_server_socket_tainted(csp);
2819 break; /* "game over, man" */
2822 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2823 if (csp->expected_client_content_length != 0)
2825 assert(len <= max_bytes_to_read);
2826 csp->expected_client_content_length -= (unsigned)len;
2827 log_error(LOG_LEVEL_CONNECT,
2828 "Expected client content length set to %llu "
2829 "after reading %d bytes.",
2830 csp->expected_client_content_length, len);
2831 if (csp->expected_client_content_length == 0)
2833 log_error(LOG_LEVEL_CONNECT,
2834 "Done reading from the client.");
2835 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2838 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2840 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2842 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2843 mark_server_socket_tainted(csp);
2851 * The server wants to talk. It could be the header or the body.
2852 * If `hdr' is null, then it's the header otherwise it's the body.
2853 * FIXME: Does `hdr' really mean `host'? No.
2856 if (poll_fds[1].revents != 0)
2858 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2859 #endif /* HAVE_POLL */
2861 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2863 * If we are buffering content, we don't want to eat up to
2864 * buffer-limit bytes if the client no longer cares about them.
2865 * If we aren't buffering, however, a dead client socket will be
2866 * noticed pretty much right away anyway, so we can reduce the
2867 * overhead by skipping the check.
2869 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2872 log_error(LOG_LEVEL_CONNECT,
2873 "The server still wants to talk, but the client may already have hung up on us.");
2875 log_error(LOG_LEVEL_CONNECT,
2876 "The server still wants to talk, but the client hung up on us.");
2877 mark_server_socket_tainted(csp);
2878 #ifdef FEATURE_HTTPS_INSPECTION
2879 close_client_and_server_ssl_connections(csp);
2882 #endif /* def _WIN32 */
2884 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2886 #ifdef FEATURE_HTTPS_INSPECTION
2888 * Reading data from standard or secured connection (HTTP/HTTPS)
2890 if (server_use_ssl(csp))
2892 len = ssl_recv_data(&(csp->ssl_server_attr),
2893 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2898 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2899 (int)csp->receive_buffer_size);
2904 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2906 if ((http->ssl && (csp->fwd == NULL))
2907 #ifdef FEATURE_HTTPS_INSPECTION
2913 * Just hang up. We already confirmed the client's CONNECT
2914 * request with status code 200 and unencrypted content is
2915 * no longer welcome.
2917 log_error(LOG_LEVEL_ERROR,
2918 "CONNECT already confirmed. Unable to tell the client about the problem.");
2921 else if (byte_count)
2924 * Just hang up. We already transmitted the original headers
2925 * and parts of the original content and therefore missed the
2926 * chance to send an error message (without risking data corruption).
2928 * XXX: we could retry with a fancy range request here.
2930 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2931 "Unable to tell the client about the problem.");
2932 mark_server_socket_tainted(csp);
2933 #ifdef FEATURE_HTTPS_INSPECTION
2934 close_client_and_server_ssl_connections(csp);
2939 * XXX: Consider handling the cases above the same.
2941 mark_server_socket_tainted(csp);
2945 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2946 if (csp->flags & CSP_FLAG_CHUNKED)
2948 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2950 /* XXX: this is a temporary hack */
2951 log_error(LOG_LEVEL_CONNECT,
2952 "Looks like we reached the end of the last chunk. "
2953 "We better stop reading.");
2954 csp->expected_content_length = byte_count + (unsigned long long)len;
2955 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2959 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2962 * This is guaranteed by allocating with zalloc_or_die()
2963 * and never (intentionally) writing to the last byte.
2965 * csp->receive_buffer_size is the size of the part of the
2966 * buffer we intentionally write to, but we actually
2967 * allocated csp->receive_buffer_size+1 bytes so the assertion
2968 * stays within the allocated range.
2970 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2973 * Add a trailing zero to let be able to use string operations.
2974 * XXX: do we still need this with filter_popups gone?
2976 assert(len <= csp->receive_buffer_size);
2977 csp->receive_buffer[len] = '\0';
2980 * Normally, this would indicate that we've read
2981 * as much as the server has sent us and we can
2982 * close the client connection. However, Microsoft
2983 * in its wisdom has released IIS/5 with a bug that
2984 * prevents it from sending the trailing \r\n in
2985 * a 302 redirect header (and possibly other headers).
2986 * To work around this if we've haven't parsed
2987 * a full header we'll append a trailing \r\n
2988 * and see if this now generates a valid one.
2990 * This hack shouldn't have any impacts. If we've
2991 * already transmitted the header or if this is a
2992 * SSL connection, then we won't bother with this
2993 * hack. So we only work on partially received
2994 * headers. If we append a \r\n and this still
2995 * doesn't generate a valid header, then we won't
2996 * transmit anything to the client.
3001 if (server_body || (http->ssl
3002 #ifdef FEATURE_HTTPS_INSPECTION
3008 * If we have been buffering up the document,
3009 * now is the time to apply content modification
3010 * and send the result to the client.
3012 if (buffer_and_filter_content)
3014 p = execute_content_filters(csp);
3016 * If content filtering fails, use the original
3017 * buffer and length.
3018 * (see p != NULL ? p : csp->iob->cur below)
3022 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3024 #ifdef FEATURE_COMPRESSION
3025 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3026 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3028 char *compressed_content = compress_buffer(p,
3029 (size_t *)&csp->content_length, csp->config->compression_level);
3030 if (compressed_content != NULL)
3033 p = compressed_content;
3034 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3039 if (JB_ERR_OK != update_server_headers(csp))
3041 log_error(LOG_LEVEL_FATAL,
3042 "Failed to update server headers. after filtering.");
3045 hdr = list_to_text(csp->headers);
3048 /* FIXME Should handle error properly */
3049 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3052 #ifdef FEATURE_HTTPS_INSPECTION
3054 * Sending data with standard or secured connection (HTTP/HTTPS)
3056 if (client_use_ssl(csp))
3058 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3059 (const unsigned char *)hdr, strlen(hdr),
3060 get_write_delay(csp)) < 0)
3061 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3062 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3063 csp->content_length, get_write_delay(csp)) < 0))
3065 log_error(LOG_LEVEL_ERROR, "write modified content to "
3066 "client over TLS/SSL failed");
3069 mark_server_socket_tainted(csp);
3070 close_client_and_server_ssl_connections(csp);
3075 #endif /* def FEATURE_HTTPS_INSPECTION */
3077 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3078 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3079 (size_t)csp->content_length, write_delay))
3081 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3084 mark_server_socket_tainted(csp);
3093 break; /* "game over, man" */
3097 * This is NOT the body, so
3098 * Let's pretend the server just sent us a blank line.
3100 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3101 len = (int)strlen(csp->receive_buffer);
3104 * Now, let the normal header parsing algorithm below do its
3105 * job. If it fails, we'll exit instead of continuing.
3112 * If we're in the body of the server document, just write it to
3113 * the client, unless we need to buffer the body for later
3114 * content-filtering.
3116 if (server_body || (http->ssl
3117 #ifdef FEATURE_HTTPS_INSPECTION
3122 if (buffer_and_filter_content)
3125 * If there is no memory left for buffering the content, or the buffer limit
3126 * has been reached, switch to non-filtering mode, i.e. make & write the
3127 * header, flush the iob and buf, and get out of the way.
3129 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3134 log_error(LOG_LEVEL_INFO,
3135 "Flushing header and buffers. Stepping back from filtering.");
3137 hdr = list_to_text(csp->headers);
3141 * Memory is too tight to even generate the header.
3142 * Send our static "Out-of-memory" page.
3144 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3145 rsp = cgi_error_memory();
3146 send_crunch_response(csp, rsp);
3147 mark_server_socket_tainted(csp);
3148 #ifdef FEATURE_HTTPS_INSPECTION
3149 close_client_and_server_ssl_connections(csp);
3153 hdrlen = strlen(hdr);
3155 #ifdef FEATURE_HTTPS_INSPECTION
3157 * Sending data with standard or secured connection (HTTP/HTTPS)
3159 if (client_use_ssl(csp))
3161 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3162 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3163 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3165 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3166 (const unsigned char *)csp->receive_buffer, (size_t)len,
3167 get_write_delay(csp)) < 0))
3169 log_error(LOG_LEVEL_CONNECT,
3170 "Flush header and buffers to client failed");
3172 mark_server_socket_tainted(csp);
3173 close_client_and_server_ssl_connections(csp);
3178 #endif /* def FEATURE_HTTPS_INSPECTION */
3180 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3181 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3182 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3185 log_error(LOG_LEVEL_CONNECT,
3186 "Flush header and buffers to client failed: %E");
3188 mark_server_socket_tainted(csp);
3194 * Reset the byte_count to the amount of bytes
3195 * we just flushed. len will be added a few lines below,
3196 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3198 byte_count = (unsigned long long)flushed;
3200 buffer_and_filter_content = 0;
3206 #ifdef FEATURE_HTTPS_INSPECTION
3208 * Sending data with standard or secured connection (HTTP/HTTPS)
3210 if (client_use_ssl(csp))
3212 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3213 (const unsigned char *)csp->receive_buffer, (size_t)len,
3214 get_write_delay(csp));
3217 log_error(LOG_LEVEL_ERROR,
3218 "Sending data to client failed");
3219 mark_server_socket_tainted(csp);
3220 close_client_and_server_ssl_connections(csp);
3225 #endif /* def FEATURE_HTTPS_INSPECTION */
3227 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3228 (size_t)len, write_delay))
3230 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3231 mark_server_socket_tainted(csp);
3236 byte_count += (unsigned long long)len;
3242 * We're still looking for the end of the server's header.
3243 * Buffer up the data we just read. If that fails, there's
3244 * little we can do but send our static out-of-memory page.
3246 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3248 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3249 rsp = cgi_error_memory();
3250 send_crunch_response(csp, rsp);
3251 mark_server_socket_tainted(csp);
3252 #ifdef FEATURE_HTTPS_INSPECTION
3253 close_client_and_server_ssl_connections(csp);
3258 /* Convert iob into something sed() can digest */
3259 if (JB_ERR_PARSE == get_server_headers(csp))
3264 * Well, we tried our MS IIS/5 hack and it didn't work.
3265 * The header is incomplete and there isn't anything
3266 * we can do about it.
3268 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3269 "Applying the MS IIS5 hack didn't help.");
3270 log_error(LOG_LEVEL_CLF,
3271 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3272 #ifdef FEATURE_HTTPS_INSPECTION
3274 * Sending data with standard or secured connection (HTTP/HTTPS)
3276 if (client_use_ssl(csp))
3278 ssl_send_data_delayed(&(csp->ssl_client_attr),
3279 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3280 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3283 #endif /* def FEATURE_HTTPS_INSPECTION */
3285 write_socket_delayed(csp->cfd,
3286 INVALID_SERVER_HEADERS_RESPONSE,
3287 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3289 mark_server_socket_tainted(csp);
3290 #ifdef FEATURE_HTTPS_INSPECTION
3291 close_client_and_server_ssl_connections(csp);
3298 * Since we have to wait for more from the server before
3299 * we can parse the headers we just continue here.
3301 log_error(LOG_LEVEL_CONNECT,
3302 "Continuing buffering server headers from socket %d. "
3303 "Bytes most recently read: %d.", csp->cfd, len);
3310 * Account for the content bytes we
3311 * might have gotten with the headers.
3313 assert(csp->iob->eod >= csp->iob->cur);
3314 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3317 /* Did we actually get anything? */
3318 if (NULL == csp->headers->first)
3320 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3322 log_error(LOG_LEVEL_ERROR,
3323 "No server or forwarder response received on socket %d. "
3324 "Closing client socket %d without sending data.",
3325 csp->server_connection.sfd, csp->cfd);
3326 log_error(LOG_LEVEL_CLF,
3327 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3331 log_error(LOG_LEVEL_ERROR,
3332 "No server or forwarder response received on socket %d.",
3333 csp->server_connection.sfd);
3334 send_crunch_response(csp, error_response(csp, "no-server-data"));
3336 free_http_request(http);
3337 mark_server_socket_tainted(csp);
3338 #ifdef FEATURE_HTTPS_INSPECTION
3339 close_client_and_server_ssl_connections(csp);
3344 if (!csp->headers->first->str)
3346 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3348 assert(csp->headers->first->str);
3350 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3351 strncmpic(csp->headers->first->str, "ICY", 3))
3354 * It doesn't look like a HTTP (or Shoutcast) response:
3355 * tell the client and log the problem.
3357 if (strlen(csp->headers->first->str) > 30)
3359 csp->headers->first->str[30] = '\0';
3361 log_error(LOG_LEVEL_ERROR,
3362 "Invalid server or forwarder response. Starts with: %s",
3363 csp->headers->first->str);
3364 log_error(LOG_LEVEL_CLF,
3365 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3366 #ifdef FEATURE_HTTPS_INSPECTION
3368 * Sending data with standard or secured connection (HTTP/HTTPS)
3370 if (client_use_ssl(csp))
3372 ssl_send_data_delayed(&(csp->ssl_client_attr),
3373 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3374 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3375 get_write_delay(csp));
3378 #endif /* def FEATURE_HTTPS_INSPECTION */
3380 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3381 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3383 free_http_request(http);
3384 mark_server_socket_tainted(csp);
3385 #ifdef FEATURE_HTTPS_INSPECTION
3386 close_client_and_server_ssl_connections(csp);
3392 * We have now received the entire server header,
3393 * filter it and send the result to the client
3395 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3397 log_error(LOG_LEVEL_CLF,
3398 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3399 #ifdef FEATURE_HTTPS_INSPECTION
3401 * Sending data with standard or secured connection (HTTP/HTTPS)
3403 if (client_use_ssl(csp))
3405 ssl_send_data_delayed(&(csp->ssl_client_attr),
3406 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3407 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3408 get_write_delay(csp));
3413 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3414 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3416 free_http_request(http);
3417 mark_server_socket_tainted(csp);
3418 #ifdef FEATURE_HTTPS_INSPECTION
3419 close_client_and_server_ssl_connections(csp);
3423 hdr = list_to_text(csp->headers);
3426 /* FIXME Should handle error properly */
3427 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3430 if ((csp->flags & CSP_FLAG_CHUNKED)
3431 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3432 && ((csp->iob->eod - csp->iob->cur) >= 5)
3433 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3435 log_error(LOG_LEVEL_CONNECT,
3436 "Looks like we got the last chunk together with "
3437 "the server headers. We better stop reading.");
3438 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3439 csp->expected_content_length = byte_count;
3440 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3443 csp->server_connection.response_received = time(NULL);
3445 if (crunch_response_triggered(csp, crunchers_light))
3448 * One of the tags created by a server-header
3449 * tagger triggered a crunch. We already
3450 * delivered the crunch response to the client
3451 * and are done here after cleaning up.
3454 mark_server_socket_tainted(csp);
3455 #ifdef FEATURE_HTTPS_INSPECTION
3456 close_client_and_server_ssl_connections(csp);
3461 /* Buffer and pcrs filter this if appropriate. */
3462 buffer_and_filter_content = content_requires_filtering(csp);
3464 if (!buffer_and_filter_content)
3467 * Write the server's (modified) header to
3468 * the client (along with anything else that
3469 * may be in the buffer). Use standard or secured
3472 #ifdef FEATURE_HTTPS_INSPECTION
3473 if (client_use_ssl(csp))
3475 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3476 (const unsigned char *)hdr, strlen(hdr),
3477 get_write_delay(csp)) < 0)
3478 || (len = ssl_flush_socket(&(csp->ssl_client_attr),
3481 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3484 * The write failed, so don't bother mentioning it
3485 * to the client... it probably can't hear us anyway.
3488 mark_server_socket_tainted(csp);
3489 #ifdef FEATURE_HTTPS_INSPECTION
3490 close_client_and_server_ssl_connections(csp);
3496 #endif /* def FEATURE_HTTPS_INSPECTION */
3498 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3499 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3501 log_error(LOG_LEVEL_ERROR,
3502 "write header to client failed");
3504 * The write failed, so don't bother mentioning it
3505 * to the client... it probably can't hear us anyway.
3508 mark_server_socket_tainted(csp);
3514 /* we're finished with the server's header */
3520 * If this was a MS IIS/5 hack then it means the server
3521 * has already closed the connection. Nothing more to read.
3526 log_error(LOG_LEVEL_ERROR,
3527 "Closed server connection detected. "
3528 "Applying the MS IIS5 hack didn't help.");
3529 log_error(LOG_LEVEL_CLF,
3530 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3531 #ifdef FEATURE_HTTPS_INSPECTION
3533 * Sending data with standard or secured connection (HTTP/HTTPS)
3535 if (client_use_ssl(csp))
3537 ssl_send_data_delayed(&(csp->ssl_client_attr),
3538 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3539 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3540 get_write_delay(csp));
3543 #endif /* def FEATURE_HTTPS_INSPECTION */
3545 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3546 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3548 mark_server_socket_tainted(csp);
3549 #ifdef FEATURE_HTTPS_INSPECTION
3550 close_client_and_server_ssl_connections(csp);
3557 mark_server_socket_tainted(csp);
3558 #ifdef FEATURE_HTTPS_INSPECTION
3559 close_client_and_server_ssl_connections(csp);
3561 return; /* huh? we should never get here */
3564 if (csp->content_length == 0)
3567 * If Privoxy didn't recalculate the Content-Length,
3568 * byte_count is still correct.
3570 csp->content_length = byte_count;
3573 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3574 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3575 && (csp->expected_content_length != byte_count))
3577 log_error(LOG_LEVEL_CONNECT,
3578 "Received %llu bytes while expecting %llu.",
3579 byte_count, csp->expected_content_length);
3580 mark_server_socket_tainted(csp);
3584 #ifdef FEATURE_HTTPS_INSPECTION
3585 if (client_use_ssl(csp))
3587 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
3588 csp->ip_addr_str, http->gpc, http->hostport, http->path,
3589 http->version, csp->content_length);
3594 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3595 csp->ip_addr_str, http->ocmd, csp->content_length);
3597 csp->server_connection.timestamp = time(NULL);
3601 /*********************************************************************
3605 * Description : Once a connection from the client has been accepted,
3606 * this function is called (via serve()) to handle the
3607 * main business of the communication. This function
3608 * returns after dealing with a single request. It can
3609 * be called multiple times with the same client socket
3610 * if the client is keeping the connection alive.
3612 * The decision whether or not a client connection will
3613 * be kept alive is up to the caller which also must
3614 * close the client socket when done.
3616 * FIXME: chat is nearly thousand lines long.
3620 * 1 : csp = Current client state (buffers, headers, etc...)
3622 * Returns : Nothing.
3624 *********************************************************************/
3625 static void chat(struct client_state *csp)
3627 const struct forward_spec *fwd;
3628 struct http_request *http;
3629 /* Skeleton for HTTP response, if we should intercept the request */
3630 struct http_response *rsp;
3631 #ifdef FEATURE_HTTPS_INSPECTION
3632 int use_ssl_tunnel = 0;
3637 if (receive_client_request(csp) != JB_ERR_OK)
3641 if (parse_client_request(csp) != JB_ERR_OK)
3646 /* decide how to route the HTTP request */
3647 fwd = forward_url(csp, http);
3650 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
3651 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3655 #ifdef FEATURE_HTTPS_INSPECTION
3657 * Setting flags to use old solution with SSL tunnel and to disable
3658 * certificate verification.
3660 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
3661 && !cgi_page_requested(csp->http->host))
3666 if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3668 csp->dont_verify_certificate = 1;
3673 * build the http request to send to the server
3674 * we have to do one of the following:
3676 * create = use the original HTTP request to create a new
3677 * HTTP request that has either the path component
3678 * without the http://domainspec (w/path) or the
3679 * full orininal URL (w/url)
3680 * Note that the path and/or the HTTP version may
3681 * have been altered by now.
3683 * SSL proxy = Open a socket to the host:port of the server
3684 * and create TLS/SSL connection with server and
3685 * with client. Then behave like mediator between
3686 * client and server over TLS/SSL.
3688 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3689 * with request to a parent proxy. Note that we'll be sending
3690 * forwarding the CFAIL message ourselves if connecting to the parent
3691 * fails, but we won't send a CSUCCEED message if it works,
3692 * since that would result in a double message (ours and the
3693 * parent's). After sending the request to the parent, we
3694 * must parse answer and send it to client. If connection
3695 * with server is established, we do TLS/SSL proxy. Otherwise
3696 * we send parent response to client and close connections.
3698 * here's the matrix:
3701 * +--------+--------+
3703 * 0 | create | SSL |
3704 * | w/path | proxy |
3705 * Forwarding +--------+--------+
3707 * 1 | create | proxy |
3708 * | w/url |+forward|
3709 * +--------+--------+
3713 #ifdef FEATURE_HTTPS_INSPECTION
3715 * Presetting SSL client and server flags
3717 if (http->ssl && !use_ssl_tunnel)
3719 http->client_ssl = 1;
3720 http->server_ssl = 1;
3724 http->client_ssl = 0;
3725 http->server_ssl = 0;
3729 #ifdef FEATURE_HTTPS_INSPECTION
3731 * Log the request unless we're https inspecting
3732 * in which case we don't have the path yet and
3733 * will log the request later.
3735 if (!client_use_ssl(csp))
3738 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
3741 if (http->ssl && connect_port_is_forbidden(csp))
3743 const char *acceptable_connect_ports =
3744 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3745 assert(NULL != acceptable_connect_ports);
3746 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3747 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3748 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3749 csp->action->flags |= ACTION_BLOCK;
3751 #ifdef FEATURE_HTTPS_INSPECTION
3752 http->client_ssl = 0;
3753 http->server_ssl = 0;
3758 freez(csp->headers->first->str);
3759 build_request_line(csp, fwd, &csp->headers->first->str);
3762 * We have a request. Check if one of the crunchers wants it
3763 * unless the client wants to use TLS/SSL in which case we
3764 * haven't setup the TLS context yet and will send the crunch
3768 #ifdef FEATURE_HTTPS_INSPECTION
3769 !client_use_ssl(csp) &&
3771 crunch_response_triggered(csp, crunchers_all))
3774 * Yes. The client got the crunch response and we're done here.
3779 log_applied_actions(csp->action);
3780 if (fwd->forward_host)
3782 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3783 fwd->forward_host, fwd->forward_port, http->hostport);
3787 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3790 /* here we connect to the server, gateway, or the forwarder */
3792 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3793 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3794 && socket_is_still_alive(csp->server_connection.sfd)
3795 && connection_destination_matches(&csp->server_connection, http, fwd))
3797 log_error(LOG_LEVEL_CONNECT,
3798 "Reusing server socket %d connected to %s. Total requests: %u.",
3799 csp->server_connection.sfd, csp->server_connection.host,
3800 csp->server_connection.requests_sent_total);
3804 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3806 #ifdef FEATURE_CONNECTION_SHARING
3807 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
3808 #ifdef FEATURE_HTTPS_INSPECTION
3809 && !server_use_ssl(csp)
3813 remember_connection(&csp->server_connection);
3816 #endif /* def FEATURE_CONNECTION_SHARING */
3818 log_error(LOG_LEVEL_CONNECT,
3819 "Closing server socket %d connected to %s. Total requests: %u.",
3820 csp->server_connection.sfd, csp->server_connection.host,
3821 csp->server_connection.requests_sent_total);
3822 close_socket(csp->server_connection.sfd);
3824 mark_connection_closed(&csp->server_connection);
3826 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3827 #ifdef FEATURE_HTTPS_INSPECTION
3828 if (http->ssl && !use_ssl_tunnel)
3832 * Creating a SSL proxy.
3834 * By sending the CSUCCEED message we're lying to the client as
3835 * the connection hasn't actually been established yet. We don't
3836 * establish the connection until we have seen and parsed the
3837 * encrypted client headers.
3839 if (write_socket_delayed(csp->cfd, CSUCCEED,
3840 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3842 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3846 ret = create_client_ssl_connection(csp);
3849 log_error(LOG_LEVEL_ERROR,
3850 "Failed to open a secure connection with the client");
3853 if (JB_ERR_OK != process_encrypted_request(csp))
3855 close_client_ssl_connection(csp);
3859 * We have an encrypted request. Check if one of the crunchers now
3860 * wants it (for example because the previously invisible path was
3861 * required to match).
3863 if (crunch_response_triggered(csp, crunchers_all))
3866 * Yes. The client got the crunch response and we're done here.
3873 * Connecting to destination server
3875 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3877 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3879 if (fwd->type != SOCKS_NONE)
3882 rsp = error_response(csp, "forwarding-failed");
3884 else if (errno == EINVAL)
3886 rsp = error_response(csp, "no-such-domain");
3890 rsp = error_response(csp, "connect-failed");
3893 /* Write the answer to the client */
3896 send_crunch_response(csp, rsp);
3900 * Temporary workaround to prevent already-read client
3901 * bodies from being parsed as new requests. For now we
3902 * err on the safe side and throw all the following
3903 * requests under the bus, even if no client body has been
3904 * buffered. A compliant client will repeat the dropped
3905 * requests on an untainted connection.
3907 * The proper fix is to discard the no longer needed
3908 * client body in the buffer (if there is one) and to
3909 * continue parsing the bytes that follow.
3911 #ifdef FEATURE_HTTPS_INSPECTION
3912 close_client_ssl_connection(csp);
3914 drain_and_close_socket(csp->cfd);
3915 csp->cfd = JB_INVALID_SOCKET;
3920 #ifdef FEATURE_HTTPS_INSPECTION
3922 * Creating TLS/SSL connections with destination server or parent
3923 * proxy. If forwarding is enabled, we must send client request to
3924 * parent proxy and receive, parse and resend parent proxy answer.
3926 if (http->ssl && !use_ssl_tunnel)
3928 if (fwd->forward_host != NULL)
3930 char server_response[BUFFER_SIZE];
3933 char *hdr = list_to_text(csp->headers);
3934 memset(server_response, 0, sizeof(server_response));
3938 log_error(LOG_LEVEL_FATAL,
3939 "Out of memory parsing client header");
3941 list_remove_all(csp->headers);
3944 * Sending client's CONNECT request to the parent proxy
3946 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
3952 log_error(LOG_LEVEL_CONNECT,
3953 "Sending request headers to: %s failed", http->hostport);
3954 mark_server_socket_tainted(csp);
3955 close_client_ssl_connection(csp);
3959 /* Waiting for parent proxy server response */
3960 len = read_socket(csp->server_connection.sfd, server_response,
3961 sizeof(server_response)-1);
3965 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
3966 "server on socket %d.", csp->server_connection.sfd);
3968 rsp = error_response(csp, "no-server-data");
3971 send_crunch_response(csp, rsp);
3973 mark_server_socket_tainted(csp);
3974 close_client_ssl_connection(csp);
3979 * Test if the connection to the destination server was
3980 * established successfully by the parent proxy.
3982 if (!tunnel_established_successfully(server_response, (unsigned int)len))
3984 log_error(LOG_LEVEL_ERROR,
3985 "The forwarder %s failed to establish a connection with %s",
3986 fwd->forward_host, http->host);
3987 rsp = error_response(csp, "connect-failed");
3990 send_crunch_response(csp, rsp);
3992 mark_server_socket_tainted(csp);
3993 close_client_ssl_connection(csp);
3996 } /* -END- if (fwd->forward_host != NULL) */
3999 * We can now create the TLS/SSL connection with the destination server.
4001 int ret = create_server_ssl_connection(csp);
4004 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4005 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4008 * If the server certificate is invalid, we must inform
4009 * the client and then close connection to the client.
4011 ssl_send_certificate_error(csp);
4012 close_client_and_server_ssl_connections(csp);
4015 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4016 || csp->server_cert_verification_result == SSL_CERT_VALID)
4019 * The TLS/SSL connection wasn't created but an invalid
4020 * certificate wasn't detected. Report it as connection
4023 rsp = error_response(csp, "connect-failed");
4026 send_crunch_response(csp, rsp);
4028 close_client_and_server_ssl_connections(csp);
4032 }/* -END- if (http->ssl) */
4033 #endif /* def FEATURE_HTTPS_INSPECTION */
4035 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4036 save_connection_destination(csp->server_connection.sfd,
4037 http, fwd, &csp->server_connection);
4038 csp->server_connection.keep_alive_timeout =
4039 (unsigned)csp->config->keep_alive_timeout;
4041 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4043 csp->server_connection.requests_sent_total++;
4045 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4047 /* Client headers have been sent optimistically */
4048 assert(csp->headers->last == NULL);
4050 else if (http->ssl == 0 || (fwd->forward_host
4051 #ifdef FEATURE_HTTPS_INSPECTION
4056 if (send_http_request(csp))
4058 rsp = error_response(csp, "connect-failed");
4061 send_crunch_response(csp, rsp);
4069 * Using old solution with SSL tunnel or new solution with SSL proxy
4071 list_remove_all(csp->headers);
4072 #ifdef FEATURE_HTTPS_INSPECTION
4077 * We're running an SSL tunnel and we're not forwarding,
4078 * so just ditch the client headers, send the "connect succeeded"
4079 * message to the client, flush the rest, and get out of the way.
4081 if (write_socket_delayed(csp->cfd, CSUCCEED,
4082 strlen(CSUCCEED), get_write_delay(csp)))
4087 #ifdef FEATURE_HTTPS_INSPECTION
4091 * If server certificate is invalid, we must inform client and then
4092 * close connection with client.
4094 if (csp->server_cert_verification_result != SSL_CERT_VALID)
4096 ssl_send_certificate_error(csp);
4097 close_client_and_server_ssl_connections(csp);
4100 if (send_https_request(csp))
4102 rsp = error_response(csp, "connect-failed");
4105 send_crunch_response(csp, rsp);
4107 close_client_and_server_ssl_connections(csp);
4111 #endif /* def FEATURE_HTTPS_INSPECTION */
4112 clear_iob(csp->client_iob);
4113 }/* -END- else ... if (http->ssl == 1) */
4115 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4117 /* XXX: should the time start earlier for optimistically sent data? */
4118 csp->server_connection.request_sent = time(NULL);
4120 handle_established_connection(csp);
4121 freez(csp->receive_buffer);
4126 /*********************************************************************
4128 * Function : fuzz_server_response
4130 * Description : Treat the input as a whole server response.
4133 * 1 : csp = Current client state (buffers, headers, etc...)
4134 * 2 : fuzz_input_file = File to read the input from.
4138 *********************************************************************/
4139 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4141 static struct forward_spec fwd; /* Zero'd due to being static */
4144 if (strcmp(fuzz_input_file, "-") == 0)
4146 /* XXX: Doesn't work yet. */
4147 csp->server_connection.sfd = 0;
4151 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4152 if (csp->server_connection.sfd == -1)
4154 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4159 csp->content_type |= CT_GIF;
4160 csp->action->flags |= ACTION_DEANIMATE;
4161 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4163 csp->http->path = strdup_or_die("/");
4164 csp->http->host = strdup_or_die("fuzz.example.org");
4165 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4166 /* Prevent client socket monitoring */
4167 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4168 csp->flags |= CSP_FLAG_CHUNKED;
4170 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4171 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4173 csp->content_type |= CT_DECLARED|CT_GIF;
4175 csp->config->socket_timeout = 0;
4177 cgi_init_error_messages();
4179 handle_established_connection(csp);
4180 freez(csp->receive_buffer);
4187 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4188 /*********************************************************************
4190 * Function : prepare_csp_for_next_request
4192 * Description : Put the csp in a mostly vergin state.
4195 * 1 : csp = Current client state (buffers, headers, etc...)
4199 *********************************************************************/
4200 static void prepare_csp_for_next_request(struct client_state *csp)
4202 csp->content_type = 0;
4203 csp->content_length = 0;
4204 csp->expected_content_length = 0;
4205 csp->expected_client_content_length = 0;
4206 list_remove_all(csp->headers);
4207 clear_iob(csp->iob);
4208 freez(csp->error_message);
4209 free_http_request(csp->http);
4210 destroy_list(csp->headers);
4211 #ifdef FEATURE_HTTPS_INSPECTION
4212 destroy_list(csp->https_headers);
4214 destroy_list(csp->tags);
4215 #ifdef FEATURE_CLIENT_TAGS
4216 destroy_list(csp->client_tags);
4217 freez(csp->client_address);
4219 free_current_action(csp->action);
4220 if (NULL != csp->fwd)
4222 unload_forward_spec(csp->fwd);
4225 /* XXX: Store per-connection flags someplace else. */
4226 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4227 #ifdef FEATURE_TOGGLE
4228 if (global_toggle_state)
4229 #endif /* def FEATURE_TOGGLE */
4231 csp->flags |= CSP_FLAG_TOGGLED_ON;
4234 if (csp->client_iob->eod > csp->client_iob->cur)
4236 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4237 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4239 assert(bytes_to_shift > 0);
4240 assert(data_length > 0);
4242 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
4243 data_length, bytes_to_shift);
4244 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4245 csp->client_iob->cur = csp->client_iob->buf;
4246 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4247 csp->client_iob->eod = csp->client_iob->buf + data_length;
4248 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4250 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4255 * We mainly care about resetting client_iob->cur so we don't
4256 * waste buffer space at the beginning and don't mess up the
4257 * request restoration done by cgi_show_request().
4259 * Freeing the buffer itself isn't technically necessary,
4260 * but makes debugging more convenient.
4262 clear_iob(csp->client_iob);
4265 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4268 /*********************************************************************
4272 * Description : This is little more than chat. We only "serve" to
4273 * to close (or remember) any socket that chat may have
4277 * 1 : csp = Current client state (buffers, headers, etc...)
4281 *********************************************************************/
4282 static void serve(struct client_state *csp)
4284 int config_file_change_detected = 0; /* Only used for debugging */
4285 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4286 #ifdef FEATURE_CONNECTION_SHARING
4287 static int monitor_thread_running = 0;
4288 #endif /* def FEATURE_CONNECTION_SHARING */
4289 int continue_chatting = 0;
4291 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4292 csp->ip_addr_str, csp->cfd);
4296 unsigned int latency;
4298 #ifdef FEATURE_HTTPS_INSPECTION
4299 if (continue_chatting && client_use_ssl(csp))
4301 continue_https_chat(csp);
4310 * If the request has been crunched,
4311 * the calculated latency is zero.
4313 latency = (unsigned)(csp->server_connection.response_received -
4314 csp->server_connection.request_sent) / 2;
4316 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4317 && (csp->flags & CSP_FLAG_CRUNCHED)
4318 && (csp->expected_client_content_length != 0))
4320 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4321 log_error(LOG_LEVEL_CONNECT,
4322 "Tainting client socket %d due to unread data.", csp->cfd);
4325 continue_chatting = (csp->config->feature_flags
4326 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4327 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4328 && (csp->cfd != JB_INVALID_SOCKET)
4329 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4330 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4331 || (csp->flags & CSP_FLAG_CHUNKED));
4333 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4334 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4336 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4338 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4340 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4341 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4342 || !socket_is_still_alive(csp->server_connection.sfd)
4343 || !(latency < csp->server_connection.keep_alive_timeout))
4345 log_error(LOG_LEVEL_CONNECT,
4346 "Closing server socket %d connected to %s. "
4347 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4348 csp->server_connection.sfd, csp->server_connection.host,
4349 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4350 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4351 socket_is_still_alive(csp->server_connection.sfd),
4352 csp->server_connection.keep_alive_timeout);
4353 #ifdef FEATURE_CONNECTION_SHARING
4354 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4356 forget_connection(csp->server_connection.sfd);
4358 #endif /* def FEATURE_CONNECTION_SHARING */
4359 #ifdef FEATURE_HTTPS_INSPECTION
4360 close_server_ssl_connection(csp);
4362 close_socket(csp->server_connection.sfd);
4363 mark_connection_closed(&csp->server_connection);
4367 if (continue_chatting && any_loaded_file_changed(csp))
4369 continue_chatting = 0;
4370 config_file_change_detected = 1;
4372 #ifdef FEATURE_HTTPS_INSPECTION
4373 if (continue_chatting && client_use_ssl(csp) &&
4374 csp->ssl_with_client_is_opened == 0)
4376 continue_chatting = 0;
4377 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4378 "The TLS session has been terminated.", csp->cfd);
4382 if (continue_chatting)
4384 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4385 && socket_is_still_alive(csp->cfd))
4387 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4388 "pipelined on socket %d and the socket is still alive.",
4389 csp->requests_received_total+1, csp->cfd);
4390 prepare_csp_for_next_request(csp);
4394 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4396 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4398 log_error(LOG_LEVEL_CONNECT,
4399 "Waiting for the next client request on socket %d. "
4400 "Keeping the server socket %d to %s open.",
4401 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4405 log_error(LOG_LEVEL_CONNECT,
4406 "Waiting for the next client request on socket %d. "
4407 "No server socket to keep open.", csp->cfd);
4411 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4412 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4413 && socket_is_still_alive(csp->cfd))
4415 log_error(LOG_LEVEL_CONNECT,
4416 "Data arrived in time on client socket %d. Requests so far: %u",
4417 csp->cfd, csp->requests_received_total);
4418 prepare_csp_for_next_request(csp);
4422 #ifdef FEATURE_CONNECTION_SHARING
4423 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4424 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4425 && (socket_is_still_alive(csp->server_connection.sfd))
4426 #ifdef FEATURE_HTTPS_INSPECTION
4427 && !server_use_ssl(csp)
4431 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4433 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4438 remember_connection(&csp->server_connection);
4439 csp->server_connection.sfd = JB_INVALID_SOCKET;
4440 drain_and_close_socket(csp->cfd);
4441 csp->cfd = JB_INVALID_SOCKET;
4442 privoxy_mutex_lock(&connection_reuse_mutex);
4443 if (!monitor_thread_running)
4445 monitor_thread_running = 1;
4446 privoxy_mutex_unlock(&connection_reuse_mutex);
4447 wait_for_alive_connections();
4448 privoxy_mutex_lock(&connection_reuse_mutex);
4449 monitor_thread_running = 0;
4451 privoxy_mutex_unlock(&connection_reuse_mutex);
4453 #endif /* def FEATURE_CONNECTION_SHARING */
4457 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4459 log_error(LOG_LEVEL_CONNECT,
4460 "Closing server socket %d connected to %s. Keep-alive: %u. "
4461 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4462 "Configuration file change detected: %u",
4463 csp->server_connection.sfd, csp->server_connection.host,
4464 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4465 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4466 socket_is_still_alive(csp->server_connection.sfd),
4467 csp->server_connection.keep_alive_timeout,
4468 config_file_change_detected);
4470 } while (continue_chatting);
4474 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4476 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4478 #ifdef FEATURE_CONNECTION_SHARING
4479 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4481 forget_connection(csp->server_connection.sfd);
4483 #endif /* def FEATURE_CONNECTION_SHARING */
4485 #ifdef FEATURE_HTTPS_INSPECTION
4486 close_server_ssl_connection(csp);
4487 #endif /* def FEATURE_HTTPS_INSPECTION */
4489 close_socket(csp->server_connection.sfd);
4492 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4493 mark_connection_closed(&csp->server_connection);
4496 if (csp->cfd != JB_INVALID_SOCKET)
4498 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4499 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4500 "Configuration file change detected: %u. Requests received: %u.",
4501 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4502 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4503 config_file_change_detected, csp->requests_received_total);
4504 #ifdef FEATURE_HTTPS_INSPECTION
4505 close_client_ssl_connection(csp);
4507 drain_and_close_socket(csp->cfd);
4510 free_csp_resources(csp);
4512 csp->flags &= ~CSP_FLAG_ACTIVE;
4518 /*********************************************************************
4520 * Function : server_thread
4522 * Description : We only exist to call `serve' in a threaded environment.
4525 * 1 : data = Current client state (buffers, headers, etc...)
4527 * Returns : Always 0.
4529 *********************************************************************/
4530 static int32 server_thread(void *data)
4532 serve((struct client_state *) data);
4539 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4540 /*********************************************************************
4544 * Description : Print usage info & exit.
4546 * Parameters : Pointer to argv[0] for identifying ourselves
4550 *********************************************************************/
4551 static void usage(const char *name)
4553 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4554 "Usage: %s [--config-test] "
4557 #endif /* defined(unix) */
4560 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4561 #endif /* defined(unix) */
4562 "[--version] [configfile]\n",
4566 show_fuzz_usage(name);
4569 printf("Aborting\n");
4574 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4577 #ifdef MUTEX_LOCKS_AVAILABLE
4578 /*********************************************************************
4580 * Function : privoxy_mutex_lock
4582 * Description : Locks a mutex.
4585 * 1 : mutex = The mutex to lock.
4587 * Returns : Void. May exit in case of errors.
4589 *********************************************************************/
4590 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4592 #ifdef FEATURE_PTHREAD
4593 int err = pthread_mutex_lock(mutex);
4596 if (mutex != &log_mutex)
4598 log_error(LOG_LEVEL_FATAL,
4599 "Mutex locking failed: %s.\n", strerror(err));
4604 EnterCriticalSection(mutex);
4605 #endif /* def FEATURE_PTHREAD */
4609 /*********************************************************************
4611 * Function : privoxy_mutex_unlock
4613 * Description : Unlocks a mutex.
4616 * 1 : mutex = The mutex to unlock.
4618 * Returns : Void. May exit in case of errors.
4620 *********************************************************************/
4621 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4623 #ifdef FEATURE_PTHREAD
4624 int err = pthread_mutex_unlock(mutex);
4627 if (mutex != &log_mutex)
4629 log_error(LOG_LEVEL_FATAL,
4630 "Mutex unlocking failed: %s.\n", strerror(err));
4635 LeaveCriticalSection(mutex);
4636 #endif /* def FEATURE_PTHREAD */
4640 /*********************************************************************
4642 * Function : privoxy_mutex_init
4644 * Description : Prepares a mutex.
4647 * 1 : mutex = The mutex to initialize.
4649 * Returns : Void. May exit in case of errors.
4651 *********************************************************************/
4652 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4654 #ifdef FEATURE_PTHREAD
4655 int err = pthread_mutex_init(mutex, 0);
4658 printf("Fatal error. Mutex initialization failed: %s.\n",
4663 InitializeCriticalSection(mutex);
4664 #endif /* def FEATURE_PTHREAD */
4666 #endif /* def MUTEX_LOCKS_AVAILABLE */
4668 /*********************************************************************
4670 * Function : initialize_mutexes
4672 * Description : Prepares mutexes if mutex support is available.
4676 * Returns : Void, exits in case of errors.
4678 *********************************************************************/
4679 static void initialize_mutexes(void)
4681 #ifdef MUTEX_LOCKS_AVAILABLE
4683 * Prepare global mutex semaphores
4686 #ifdef FEATURE_HTTPS_INSPECTION
4687 privoxy_mutex_init(&certificate_mutex);
4688 privoxy_mutex_init(&ssl_init_mutex);
4691 privoxy_mutex_init(&log_mutex);
4692 privoxy_mutex_init(&log_init_mutex);
4693 privoxy_mutex_init(&connection_reuse_mutex);
4694 #ifdef FEATURE_EXTERNAL_FILTERS
4695 privoxy_mutex_init(&external_filter_mutex);
4697 #ifdef FEATURE_CLIENT_TAGS
4698 privoxy_mutex_init(&client_tags_mutex);
4700 #ifdef FEATURE_EXTENDED_STATISTICS
4701 privoxy_mutex_init(&filter_statistics_mutex);
4702 privoxy_mutex_init(&block_statistics_mutex);
4706 * XXX: The assumptions below are a bit naive
4707 * and can cause locks that aren't necessary.
4709 * For example older FreeBSD versions (< 6.x?)
4710 * have no gethostbyname_r, but gethostbyname is
4713 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4714 privoxy_mutex_init(&resolver_mutex);
4715 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4717 * XXX: should we use a single mutex for
4718 * localtime() and gmtime() as well?
4720 #ifndef HAVE_GMTIME_R
4721 privoxy_mutex_init(&gmtime_mutex);
4722 #endif /* ndef HAVE_GMTIME_R */
4724 #ifndef HAVE_LOCALTIME_R
4725 privoxy_mutex_init(&localtime_mutex);
4726 #endif /* ndef HAVE_GMTIME_R */
4728 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4729 privoxy_mutex_init(&rand_mutex);
4730 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4732 #endif /* def MUTEX_LOCKS_AVAILABLE */
4735 /*********************************************************************
4739 * Description : Load the config file and start the listen loop.
4740 * This function is a lot more *sane* with the `load_config'
4741 * and `listen_loop' functions; although it stills does
4742 * a *little* too much for my taste.
4745 * 1 : argc = Number of parameters (including $0).
4746 * 2 : argv = Array of (char *)'s to the parameters.
4748 * Returns : 1 if : can't open config file, unrecognized directive,
4749 * stats requested in multi-thread mode, can't open the
4750 * log file, can't open the jar file, listen port is invalid,
4751 * any load fails, and can't bind port.
4753 * Else main never returns, the process must be signaled
4754 * to terminate execution. Or, on Windows, use the
4755 * "File", "Exit" menu option.
4757 *********************************************************************/
4759 int real_main(int argc, char **argv)
4761 int main(int argc, char **argv)
4765 int do_config_test = 0;
4766 #ifndef HAVE_ARC4RANDOM
4767 unsigned int random_seed;
4770 struct passwd *pw = NULL;
4771 struct group *grp = NULL;
4773 char *pre_chroot_nslookup_to_load_resolver = NULL;
4776 char *fuzz_input_type = NULL;
4777 char *fuzz_input_file = NULL;
4784 #if !defined(_WIN32)
4791 /* Prepare mutexes if supported and necessary. */
4792 initialize_mutexes();
4794 /* Enable logging until further notice. */
4798 * Parse the command line arguments
4800 * XXX: simply printing usage information in case of
4801 * invalid arguments isn't particularly user friendly.
4803 while (++argc_pos < argc)
4806 /* Check to see if the service must be installed or uninstalled */
4807 if (strncmp(argv[argc_pos], "--install", 9) == 0)
4809 const char *pName = argv[argc_pos] + 9;
4812 exit((install_service(pName)) ? 0 : 1);
4814 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4816 const char *pName = argv[argc_pos] + 11;
4819 exit((uninstall_service(pName)) ? 0 : 1);
4821 else if (strcmp(argv[argc_pos], "--service") == 0)
4823 bRunAsService = TRUE;
4824 w32_set_service_cwd();
4825 atexit(w32_service_exit_notify);
4828 #endif /* defined(_WIN32) */
4831 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4833 if (strcmp(argv[argc_pos], "--help") == 0)
4838 else if (strcmp(argv[argc_pos], "--version") == 0)
4840 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4846 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4848 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4852 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4854 if (++argc_pos == argc) usage(argv[0]);
4855 pidfile = strdup_or_die(argv[argc_pos]);
4858 else if (strcmp(argv[argc_pos], "--user") == 0)
4863 if (++argc_pos == argc) usage(argv[argc_pos]);
4865 user_arg = strdup_or_die(argv[argc_pos]);
4866 group_name = strchr(user_arg, '.');
4867 if (NULL != group_name)
4869 /* Nul-terminate the user name */
4872 /* Skip the former delimiter to actually reach the group name */
4875 grp = getgrnam(group_name);
4878 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4881 pw = getpwnam(user_arg);
4884 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4890 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4892 if (++argc_pos == argc) usage(argv[0]);
4893 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4896 else if (strcmp(argv[argc_pos], "--chroot") == 0)
4900 #endif /* defined(unix) */
4902 else if (strcmp(argv[argc_pos], "--config-test") == 0)
4907 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4910 if (argc < argc_pos + 2) usage(argv[0]);
4911 fuzz_input_type = argv[argc_pos];
4913 fuzz_input_file = argv[argc_pos];
4915 else if (strcmp(argv[argc_pos], "--stfu") == 0)
4917 set_debug_level(LOG_LEVEL_STFU);
4920 else if (argc_pos + 1 != argc)
4923 * This is neither the last command line
4924 * option, nor was it recognized before,
4925 * therefore it must be invalid.
4931 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4933 configfile = argv[argc_pos];
4936 } /* -END- while (more arguments) */
4938 show_version(Argv[0]);
4941 if (*configfile != '/')
4943 char cwd[BUFFER_SIZE];
4945 size_t abs_file_size;
4947 /* make config-filename absolute here */
4948 if (NULL == getcwd(cwd, sizeof(cwd)))
4950 perror("failed to get current working directory");
4954 basedir = strdup_or_die(cwd);
4956 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4957 abs_file = malloc_or_die(abs_file_size);
4958 strlcpy(abs_file, basedir, abs_file_size);
4959 strlcat(abs_file, "/", abs_file_size);
4960 strlcat(abs_file, configfile, abs_file_size);
4961 configfile = abs_file;
4963 #endif /* defined unix */
4967 clients->next = NULL;
4969 /* XXX: factor out initialising after the next stable release. */
4974 #ifndef HAVE_ARC4RANDOM
4975 random_seed = (unsigned int)time(NULL);
4977 srandom(random_seed);
4980 #endif /* ifdef HAVE_RANDOM */
4981 #endif /* ifndef HAVE_ARC4RANDOM */
4984 * Unix signal handling
4986 * Catch the abort, interrupt and terminate signals for a graceful exit
4987 * Catch the hangup signal so the errlog can be reopened.
4989 * Ignore the broken pipe signal as connection failures
4990 * are handled when and where they occur without relying
4993 #if !defined(_WIN32)
4996 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
4998 for (idx = 0; idx < SZ(catched_signals); idx++)
5000 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5001 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5003 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5004 #endif /* ifdef sun */
5006 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5010 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5012 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5016 #else /* ifdef _WIN32 */
5017 # ifdef _WIN_CONSOLE
5019 * We *are* in a windows console app.
5020 * Print a verbose messages about FAQ's and such
5022 printf("%s", win32_blurb);
5023 # endif /* def _WIN_CONSOLE */
5024 #endif /* def _WIN32 */
5027 if (fuzz_input_type != NULL)
5029 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5031 log_error(LOG_LEVEL_FATAL,
5032 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5033 "Various data structures are static which is unsafe when using threads.");
5038 exit(NULL == load_config());
5041 /* Initialize the CGI subsystem */
5042 cgi_init_error_messages();
5045 * If running on unix and without the --no-daemon
5046 * option, become a daemon. I.e. fork, detach
5047 * from tty and get process group leadership
5056 if (pid < 0) /* error */
5061 else if (pid != 0) /* parent */
5066 * must check for errors
5067 * child died due to missing files aso
5070 wpid = waitpid(pid, &status, WNOHANG);
5082 * stderr (fd 2) will be closed later on,
5083 * when the config file has been parsed.
5089 * Reserve fd 0 and 1 to prevent abort() and friends
5090 * from sending stuff to the clients or servers.
5092 fd = open("/dev/null", O_RDONLY);
5095 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5099 if (dup2(fd, 0) == -1)
5101 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5105 fd = open("/dev/null", O_WRONLY);
5108 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5112 if (dup2(fd, 1) == -1)
5114 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5119 #ifdef FEATURE_EXTERNAL_FILTERS
5120 for (fd = 0; fd < 3; fd++)
5122 mark_socket_for_close_on_execute(fd);
5128 } /* -END- if (daemon_mode) */
5131 * As soon as we have written the PID file, we can switch
5132 * to the user and group ID indicated by the --user option
5134 if (pidfile != NULL)
5136 write_pid_file(pidfile);
5140 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5142 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5146 if (setgroups(1, &grp->gr_gid))
5148 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5151 else if (initgroups(pw->pw_name, pw->pw_gid))
5153 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5159 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5161 /* Read the time zone file from /etc before doing chroot. */
5163 if (NULL != pre_chroot_nslookup_to_load_resolver
5164 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5166 /* Initialize resolver library. */
5167 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5169 if (chroot(pw->pw_dir) < 0)
5171 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5175 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5178 if (setuid(pw->pw_uid))
5180 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5184 char putenv_dummy[64];
5186 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5187 if (putenv(putenv_dummy) != 0)
5189 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5192 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5193 if (putenv(putenv_dummy) != 0)
5195 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5201 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5204 #endif /* defined unix */
5207 /* This will be FALSE unless the command line specified --service
5211 /* Yup, so now we must attempt to establish a connection
5212 * with the service dispatcher. This will only work if this
5213 * process was launched by the service control manager to
5214 * actually run as a service. If this isn't the case, i've
5215 * known it take around 30 seconds or so for the call to return.
5218 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5219 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5221 /* Service has run, and at this point is now being stopped, so just return */
5226 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5228 /* An error occurred. Usually it's because --service was wrongly specified
5229 * and we were unable to connect to the Service Control Dispatcher because
5230 * it wasn't expecting us and is therefore not listening.
5232 * For now, just continue below to call the listen_loop function.
5235 #endif /* def _WIN32 */
5245 /*********************************************************************
5247 * Function : bind_port_helper
5249 * Description : Bind the listen port. Handles logging, and aborts
5253 * 1 : haddr = Host address to bind to. Use NULL to bind to
5255 * 2 : hport = Specifies port to bind to.
5256 * 3 : backlog = Listen backlog.
5258 * Returns : Port that was opened.
5260 *********************************************************************/
5261 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5266 result = bind_port(haddr, hport, backlog, &bfd);
5270 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5274 log_error(LOG_LEVEL_FATAL,
5275 "can't bind to %s:%d: There may be another Privoxy "
5276 "or some other proxy running on port %d",
5277 bind_address, hport, hport);
5280 log_error(LOG_LEVEL_FATAL,
5281 "can't bind to %s:%d: The hostname is not resolvable",
5282 bind_address, hport);
5285 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5286 bind_address, hport);
5289 /* shouldn't get here */
5290 return JB_INVALID_SOCKET;
5295 if (bfd >= FD_SETSIZE)
5297 log_error(LOG_LEVEL_FATAL,
5298 "Bind socket number too high to use select(): %d >= %d",
5306 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5311 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5319 /*********************************************************************
5321 * Function : bind_ports_helper
5323 * Description : Bind the listen ports. Handles logging, and aborts
5327 * 1 : config = Privoxy configuration. Specifies ports
5329 * 2 : sockets = Preallocated array of opened sockets
5330 * corresponding to specification in config.
5331 * All non-opened sockets will be set to
5332 * JB_INVALID_SOCKET.
5334 * Returns : Nothing. Inspect sockets argument.
5336 *********************************************************************/
5337 static void bind_ports_helper(struct configuration_spec * config,
5338 jb_socket sockets[])
5342 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5344 if (config->hport[i])
5346 sockets[i] = bind_port_helper(config->haddr[i],
5347 config->hport[i], config->listen_backlog);
5348 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5349 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5351 struct accept_filter_arg af_options;
5352 bzero(&af_options, sizeof(af_options));
5353 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5354 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5355 sizeof(af_options)))
5357 log_error(LOG_LEVEL_ERROR,
5358 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5365 sockets[i] = JB_INVALID_SOCKET;
5368 config->need_bind = 0;
5372 /*********************************************************************
5374 * Function : close_ports_helper
5376 * Description : Close listenings ports.
5379 * 1 : sockets = Array of opened and non-opened sockets to
5380 * close. All sockets will be set to
5381 * JB_INVALID_SOCKET.
5383 * Returns : Nothing.
5385 *********************************************************************/
5386 static void close_ports_helper(jb_socket sockets[])
5390 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5392 if (JB_INVALID_SOCKET != sockets[i])
5394 close_socket(sockets[i]);
5396 sockets[i] = JB_INVALID_SOCKET;
5402 /* Without this simple workaround we get this compiler warning from _beginthread
5403 * warning C4028: formal parameter 1 different from declaration
5405 void w32_service_listen_loop(void *p)
5409 #endif /* def _WIN32 */
5412 /*********************************************************************
5414 * Function : listen_loop
5416 * Description : bind the listen port and enter a "FOREVER" listening loop.
5422 *********************************************************************/
5423 static void listen_loop(void)
5425 struct client_states *csp_list = NULL;
5426 struct client_state *csp = NULL;
5427 jb_socket bfds[MAX_LISTENING_SOCKETS];
5428 struct configuration_spec *config;
5429 unsigned int active_threads = 0;
5430 #if defined(FEATURE_PTHREAD)
5431 pthread_attr_t attrs;
5433 pthread_attr_init(&attrs);
5434 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5437 config = load_config();
5439 #ifdef FEATURE_CONNECTION_SHARING
5441 * XXX: Should be relocated once it no
5442 * longer needs to emit log messages.
5444 initialize_reusable_connections();
5445 #endif /* def FEATURE_CONNECTION_SHARING */
5447 bind_ports_helper(config, bfds);
5449 #ifdef FEATURE_GRACEFUL_TERMINATION
5450 while (!g_terminate)
5455 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
5456 while (waitpid(-1, NULL, WNOHANG) > 0)
5458 /* zombie children */
5460 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5463 * Free data that was used by died threads
5465 active_threads = sweep();
5469 * Re-open the errlog after HUP signal
5471 if (received_hup_signal)
5473 if (NULL != config->logfile)
5475 init_error_log(Argv[0], config->logfile);
5477 received_hup_signal = 0;
5481 csp_list = zalloc_or_die(sizeof(*csp_list));
5482 csp = &csp_list->csp;
5484 log_error(LOG_LEVEL_CONNECT,
5485 "Waiting for the next client connection. Currently active threads: %d",
5489 * This config may be outdated, but for accept_connection()
5490 * it's fresh enough.
5492 csp->config = config;
5494 if (!accept_connection(csp, bfds))
5496 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5501 csp->flags |= CSP_FLAG_ACTIVE;
5502 csp->server_connection.sfd = JB_INVALID_SOCKET;
5504 csp->config = config = load_config();
5506 if (config->need_bind)
5509 * Since we were listening to the "old port", we will not see
5510 * a "listen" param change until the next request. So, at
5511 * least 1 more request must be made for us to find the new
5512 * setting. I am simply closing the old socket and binding the
5515 * Which-ever is correct, we will serve 1 more page via the
5516 * old settings. This should probably be a "show-status"
5517 * request. This should not be a so common of an operation
5518 * that this will hurt people's feelings.
5521 close_ports_helper(bfds);
5523 bind_ports_helper(config, bfds);
5526 #ifdef FEATURE_TOGGLE
5527 if (global_toggle_state)
5528 #endif /* def FEATURE_TOGGLE */
5530 csp->flags |= CSP_FLAG_TOGGLED_ON;
5533 if (run_loader(csp))
5535 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5536 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5540 if (block_acl(NULL,csp))
5542 log_error(LOG_LEVEL_CONNECT,
5543 "Connection from %s on %s (socket %d) dropped due to ACL",
5544 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5545 close_socket(csp->cfd);
5546 freez(csp->ip_addr_str);
5547 freez(csp->listen_addr_str);
5551 #endif /* def FEATURE_ACL */
5553 if ((0 != config->max_client_connections)
5554 && (active_threads >= config->max_client_connections))
5556 log_error(LOG_LEVEL_CONNECT,
5557 "Rejecting connection from %s. Maximum number of connections reached.",
5559 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5560 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5561 close_socket(csp->cfd);
5562 freez(csp->ip_addr_str);
5563 freez(csp->listen_addr_str);
5568 /* add it to the list of clients */
5569 csp_list->next = clients->next;
5570 clients->next = csp_list;
5572 if (config->multi_threaded)
5576 /* this is a switch () statement in the C preprocessor - ugh */
5577 #undef SELECTED_ONE_OPTION
5579 /* Use Pthreads in preference to native code */
5580 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5581 #define SELECTED_ONE_OPTION
5583 pthread_t the_thread;
5586 ret = pthread_create(&the_thread, &attrs,
5587 (void * (*)(void *))serve, csp);
5588 child_id = ret ? -1 : 0;
5592 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5593 #define SELECTED_ONE_OPTION
5594 child_id = _beginthread(
5595 (void (*)(void *))serve,
5600 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5601 #define SELECTED_ONE_OPTION
5603 thread_id tid = spawn_thread
5604 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5606 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5608 child_id = (int) tid;
5617 #if !defined(SELECTED_ONE_OPTION)
5620 /* This block is only needed when using fork().
5621 * When using threads, the server thread was
5622 * created and run by the call to _beginthread().
5624 if (child_id == 0) /* child */
5627 #ifdef FEATURE_TOGGLE
5628 int inherited_toggle_state = global_toggle_state;
5629 #endif /* def FEATURE_TOGGLE */
5634 * If we've been toggled or we've blocked the request, tell Mom
5637 #ifdef FEATURE_TOGGLE
5638 if (inherited_toggle_state != global_toggle_state)
5640 rc |= RC_FLAG_TOGGLED;
5642 #endif /* def FEATURE_TOGGLE */
5644 #ifdef FEATURE_STATISTICS
5645 if (csp->flags & CSP_FLAG_REJECTED)
5647 rc |= RC_FLAG_BLOCKED;
5649 #endif /* ndef FEATURE_STATISTICS */
5653 else if (child_id > 0) /* parent */
5655 /* in a fork()'d environment, the parent's
5656 * copy of the client socket and the CSP
5660 #if !defined(_WIN32) && !defined(__CYGWIN__)
5662 wait(&child_status);
5665 * Evaluate child's return code: If the child has
5666 * - been toggled, toggle ourselves
5667 * - blocked its request, bump up the stats counter
5670 #ifdef FEATURE_TOGGLE
5671 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5673 global_toggle_state = !global_toggle_state;
5675 #endif /* def FEATURE_TOGGLE */
5677 #ifdef FEATURE_STATISTICS
5679 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5683 #endif /* def FEATURE_STATISTICS */
5685 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5686 close_socket(csp->cfd);
5687 csp->flags &= ~CSP_FLAG_ACTIVE;
5691 #undef SELECTED_ONE_OPTION
5692 /* end of cpp switch () */
5697 * Spawning the child failed, assume it's because
5698 * there are too many children running already.
5699 * XXX: If you assume ...
5701 log_error(LOG_LEVEL_ERROR,
5702 "Unable to take any additional connections: %E. Active threads: %d",
5704 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5705 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5706 close_socket(csp->cfd);
5707 csp->flags &= ~CSP_FLAG_ACTIVE;
5716 #if defined(FEATURE_PTHREAD)
5717 pthread_attr_destroy(&attrs);
5720 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5722 #ifdef FEATURE_HTTPS_INSPECTION
5723 /* Clean up. Aim: free all memory (no leaks) */
5727 #ifdef FEATURE_GRACEFUL_TERMINATION
5729 log_error(LOG_LEVEL_INFO, "Graceful termination requested");
5731 unload_current_config_file();
5732 unload_current_actions_file();
5733 unload_current_re_filterfile();
5734 #ifdef FEATURE_TRUST
5735 unload_current_trust_file();
5738 if (config->multi_threaded)
5745 } while ((clients->next != NULL) && (--i > 0));
5749 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5759 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5760 /* Cleanup - remove taskbar icon etc. */
5765 #endif /* FEATURE_GRACEFUL_TERMINATION */