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 %lu",
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 %lu",
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;
1179 if (NULL != fwd->auth_username)
1181 server_connection->auth_username = strdup_or_die(fwd->auth_username);
1185 server_connection->auth_username = NULL;
1187 if (NULL != fwd->auth_password)
1189 server_connection->auth_password = strdup_or_die(fwd->auth_password);
1193 server_connection->auth_password = NULL;
1196 if (NULL != fwd->forward_host)
1198 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1202 server_connection->forward_host = NULL;
1204 server_connection->forward_port = fwd->forward_port;
1206 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1209 /*********************************************************************
1211 * Function : verify_request_length
1213 * Description : Checks if we already got the whole client requests
1214 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1217 * Data that doesn't belong to the current request is
1218 * either thrown away to let the client retry on a clean
1219 * socket, or stashed to be dealt with after the current
1220 * request is served.
1223 * 1 : csp = Current client state (buffers, headers, etc...)
1227 *********************************************************************/
1228 static void verify_request_length(struct client_state *csp)
1230 unsigned long long buffered_request_bytes =
1231 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1233 if ((csp->expected_client_content_length != 0)
1234 && (buffered_request_bytes != 0))
1236 if (csp->expected_client_content_length >= buffered_request_bytes)
1238 csp->expected_client_content_length -= buffered_request_bytes;
1239 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1240 "to account for the %llu ones we already got.",
1241 csp->expected_client_content_length, buffered_request_bytes);
1245 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1246 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1247 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1248 "Marking the server socket tainted after throwing %llu bytes away.",
1249 buffered_request_bytes - csp->expected_client_content_length);
1250 csp->expected_client_content_length = 0;
1251 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1254 if (csp->expected_client_content_length == 0)
1256 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1260 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1261 && ((csp->client_iob->cur < csp->client_iob->eod)
1262 || (csp->expected_client_content_length != 0)))
1264 if (strcmpic(csp->http->gpc, "GET")
1265 && strcmpic(csp->http->gpc, "HEAD")
1266 && strcmpic(csp->http->gpc, "TRACE")
1267 && strcmpic(csp->http->gpc, "OPTIONS")
1268 && strcmpic(csp->http->gpc, "DELETE"))
1270 /* XXX: this is an incomplete hack */
1271 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1272 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1276 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1278 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1280 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1281 log_error(LOG_LEVEL_CONNECT,
1282 "Possible pipeline attempt detected. The connection will not "
1283 "be kept alive and we will only serve the first request.");
1284 /* Nuke the pipelined requests from orbit, just to be sure. */
1285 clear_iob(csp->client_iob);
1290 * Keep the pipelined data around for now, we'll deal with
1291 * it once we're done serving the current request.
1293 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1294 assert(csp->client_iob->eod >= csp->client_iob->cur);
1295 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1296 "%d bytes of pipelined data received.",
1297 (int)(csp->client_iob->eod - csp->client_iob->cur));
1303 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1304 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1309 /*********************************************************************
1311 * Function : mark_server_socket_tainted
1313 * Description : Makes sure we don't reuse a server socket
1314 * (if we didn't read everything the server sent
1315 * us reusing the socket would lead to garbage).
1318 * 1 : csp = Current client state (buffers, headers, etc...)
1322 *********************************************************************/
1323 static void mark_server_socket_tainted(struct client_state *csp)
1326 * For consistency we always mark the server socket
1327 * tainted, however, to reduce the log noise we only
1328 * emit a log message if the server socket could have
1329 * actually been reused.
1331 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1332 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1334 log_error(LOG_LEVEL_CONNECT,
1335 "Marking the server socket %d tainted.",
1336 csp->server_connection.sfd);
1338 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1341 /*********************************************************************
1343 * Function : get_request_line
1345 * Description : Read the client request line.
1348 * 1 : csp = Current client state (buffers, headers, etc...)
1350 * Returns : Pointer to request line or NULL in case of errors.
1352 *********************************************************************/
1353 static char *get_request_line(struct client_state *csp)
1355 char buf[BUFFER_SIZE];
1356 char *request_line = NULL;
1359 memset(buf, 0, sizeof(buf));
1361 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1364 * If there are multiple pipelined requests waiting,
1365 * the flag will be set again once the next request
1368 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1370 request_line = get_header(csp->client_iob);
1371 if ((NULL != request_line) && ('\0' != *request_line))
1373 return request_line;
1377 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1378 "received yet. Continuing reading from %d.", csp->cfd);
1386 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1388 !data_is_available(csp->cfd, csp->config->socket_timeout)
1391 if (socket_is_still_alive(csp->cfd))
1393 log_error(LOG_LEVEL_CONNECT,
1394 "No request line on socket %d received in time. Timeout: %d.",
1395 csp->cfd, csp->config->socket_timeout);
1396 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1397 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1398 get_write_delay(csp));
1402 log_error(LOG_LEVEL_CONNECT,
1403 "The client side of the connection on socket %d got "
1404 "closed without sending a complete request line.", csp->cfd);
1409 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1411 if (len <= 0) return NULL;
1414 * If there is no memory left for buffering the
1415 * request, there is nothing we can do but hang up
1417 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1422 request_line = get_header(csp->client_iob);
1424 } while ((NULL != request_line) && ('\0' == *request_line));
1426 return request_line;
1432 CHUNK_STATUS_MISSING_DATA,
1433 CHUNK_STATUS_BODY_COMPLETE,
1434 CHUNK_STATUS_PARSE_ERROR
1438 /*********************************************************************
1440 * Function : chunked_body_is_complete
1442 * Description : Figures out whether or not a chunked body is complete.
1444 * Currently it always starts at the beginning of the
1445 * buffer which is somewhat wasteful and prevents Privoxy
1446 * from starting to forward the correctly parsed chunks
1447 * as soon as theoretically possible.
1449 * Should be modified to work with a common buffer,
1450 * and allow the caller to skip already parsed chunks.
1452 * This would allow the function to be used for unbuffered
1453 * response bodies as well.
1456 * 1 : iob = Buffer with the body to check.
1457 * 2 : length = Length of complete body
1459 * Returns : Enum with the result of the check.
1461 *********************************************************************/
1462 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1464 unsigned int chunksize;
1470 * We need at least a single digit, followed by "\r\n",
1471 * followed by an unknown amount of data, followed by "\r\n".
1473 if (p + 5 > iob->eod)
1475 return CHUNK_STATUS_MISSING_DATA;
1477 if (sscanf(p, "%x", &chunksize) != 1)
1479 return CHUNK_STATUS_PARSE_ERROR;
1483 * We want at least a single digit, followed by "\r\n",
1484 * followed by the specified amount of data, followed by "\r\n".
1486 if (p + chunksize + 5 > iob->eod)
1488 return CHUNK_STATUS_MISSING_DATA;
1491 /* Skip chunk-size. */
1492 p = strstr(p, "\r\n");
1495 return CHUNK_STATUS_PARSE_ERROR;
1497 /* Move beyond the chunkdata. */
1500 /* There should be another "\r\n" to skip */
1501 if (memcmp(p, "\r\n", 2))
1503 return CHUNK_STATUS_PARSE_ERROR;
1506 } while (chunksize > 0U);
1508 *length = (size_t)(p - iob->cur);
1509 assert(*length <= (size_t)(iob->eod - iob->cur));
1510 assert(p <= iob->eod);
1512 return CHUNK_STATUS_BODY_COMPLETE;
1517 /*********************************************************************
1519 * Function : receive_chunked_client_request_body
1521 * Description : Read the chunk-encoded client request body.
1522 * Failures are dealt with.
1525 * 1 : csp = Current client state (buffers, headers, etc...)
1527 * Returns : JB_ERR_OK or JB_ERR_PARSE
1529 *********************************************************************/
1530 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1533 enum chunk_status status;
1535 while (CHUNK_STATUS_MISSING_DATA ==
1536 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1538 char buf[BUFFER_SIZE];
1541 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1543 log_error(LOG_LEVEL_ERROR,
1544 "Timeout while waiting for the client body.");
1547 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1550 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1553 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1558 if (status != CHUNK_STATUS_BODY_COMPLETE)
1560 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1561 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1562 log_error(LOG_LEVEL_CLF,
1563 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1564 return JB_ERR_PARSE;
1566 log_error(LOG_LEVEL_CONNECT,
1567 "Chunked client body completely read. Length: %lu", body_length);
1568 csp->expected_client_content_length = body_length;
1576 /*********************************************************************
1578 * Function : fuzz_chunked_transfer_encoding
1580 * Description : Treat the fuzzed input as chunked transfer encoding
1581 * to check and dechunk.
1584 * 1 : csp = Used to store the data.
1585 * 2 : fuzz_input_file = File to read the input from.
1587 * Returns : Result of dechunking
1589 *********************************************************************/
1590 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1593 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1594 enum chunk_status status;
1596 status = chunked_body_is_complete(csp->iob, &length);
1597 if (CHUNK_STATUS_BODY_COMPLETE != status)
1599 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1602 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1607 /*********************************************************************
1609 * Function : fuzz_client_request
1611 * Description : Try to get a client request from the fuzzed input.
1614 * 1 : csp = Current client state (buffers, headers, etc...)
1615 * 2 : fuzz_input_file = File to read the input from.
1617 * Returns : Result of fuzzing.
1619 *********************************************************************/
1620 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1625 csp->ip_addr_str = "fuzzer";
1627 if (strcmp(fuzz_input_file, "-") != 0)
1629 log_error(LOG_LEVEL_FATAL,
1630 "Fuzzed client requests can currently only be read from stdin (-).");
1632 err = receive_client_request(csp);
1633 if (err != JB_ERR_OK)
1637 err = parse_client_request(csp);
1638 if (err != JB_ERR_OK)
1646 #endif /* def FUZZ */
1649 #ifdef FEATURE_FORCE_LOAD
1650 /*********************************************************************
1652 * Function : force_required
1654 * Description : Checks a request line to see if it contains
1655 * the FORCE_PREFIX. If it does, it is removed
1656 * unless enforcing requests has beend disabled.
1659 * 1 : request_line = HTTP request line
1661 * Returns : TRUE if force is required, FALSE otherwise.
1663 *********************************************************************/
1664 static int force_required(const struct client_state *csp, char *request_line)
1668 p = strstr(request_line, "http://");
1672 p += strlen("http://");
1676 /* Intercepted request usually don't specify the protocol. */
1680 /* Go to the beginning of the path */
1685 * If the path is missing the request line is invalid and we
1686 * are done here. The client-visible rejection happens later on.
1691 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1693 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1695 /* XXX: Should clean more carefully */
1696 strclean(request_line, FORCE_PREFIX);
1697 log_error(LOG_LEVEL_FORCE,
1698 "Enforcing request: \"%s\".", request_line);
1702 log_error(LOG_LEVEL_FORCE,
1703 "Ignored force prefix in request: \"%s\".", request_line);
1709 #endif /* def FEATURE_FORCE_LOAD */
1712 /*********************************************************************
1714 * Function : receive_client_request
1716 * Description : Read the client's request (more precisely the
1717 * client headers) and answer it if necessary.
1720 * 1 : csp = Current client state (buffers, headers, etc...)
1722 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1724 *********************************************************************/
1725 static jb_err receive_client_request(struct client_state *csp)
1727 char buf[BUFFER_SIZE];
1730 struct http_request *http;
1734 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1735 struct list header_list;
1736 struct list *headers = &header_list;
1738 /* We don't care if the arriving data is a valid HTTP request or not. */
1739 csp->requests_received_total++;
1743 memset(buf, 0, sizeof(buf));
1745 req = get_request_line(csp);
1748 mark_server_socket_tainted(csp);
1749 return JB_ERR_PARSE;
1751 assert(*req != '\0');
1753 if (client_protocol_is_unsupported(csp, req))
1755 return JB_ERR_PARSE;
1758 #ifdef FEATURE_FORCE_LOAD
1759 if (force_required(csp, req))
1761 csp->flags |= CSP_FLAG_FORCED;
1763 #endif /* def FEATURE_FORCE_LOAD */
1765 err = parse_http_request(req, http);
1767 if (JB_ERR_OK != err)
1769 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1770 get_write_delay(csp));
1771 /* XXX: Use correct size */
1772 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1773 log_error(LOG_LEVEL_ERROR,
1774 "Couldn't parse request line received from %s: %s",
1775 csp->ip_addr_str, jb_err_to_string(err));
1777 free_http_request(http);
1778 return JB_ERR_PARSE;
1781 /* grab the rest of the client's headers */
1785 p = get_header(csp->client_iob);
1789 /* There are no additional headers to read. */
1796 * We didn't receive a complete header
1797 * line yet, get the rest of it.
1799 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1801 log_error(LOG_LEVEL_ERROR,
1802 "Stopped grabbing the client headers.");
1803 destroy_list(headers);
1804 return JB_ERR_PARSE;
1807 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1810 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1811 destroy_list(headers);
1812 return JB_ERR_PARSE;
1815 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1818 * If there is no memory left for buffering the
1819 * request, there is nothing we can do but hang up
1821 destroy_list(headers);
1822 return JB_ERR_MEMORY;
1827 if (!strncmpic(p, "Transfer-Encoding:", 18))
1830 * XXX: should be called through sed()
1831 * but currently can't.
1833 client_transfer_encoding(csp, &p);
1836 * We were able to read a complete
1837 * header and can finally enlist it.
1844 if (http->host == NULL)
1847 * If we still don't know the request destination,
1848 * the request is invalid or the client uses
1849 * Privoxy without its knowledge.
1851 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1854 * Our attempts to get the request destination
1855 * elsewhere failed or Privoxy is configured
1856 * to only accept proxy requests.
1858 * An error response has already been send
1859 * and we're done here.
1861 return JB_ERR_PARSE;
1865 #ifdef FEATURE_CLIENT_TAGS
1866 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1867 set_client_address(csp, headers);
1868 get_tag_list_for_client(csp->client_tags, csp->client_address);
1872 * Determine the actions for this URL
1874 #ifdef FEATURE_TOGGLE
1875 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1877 /* Most compatible set of actions (i.e. none) */
1878 init_current_action(csp->action);
1881 #endif /* ndef FEATURE_TOGGLE */
1883 get_url_actions(csp, http);
1886 enlist(csp->headers, http->cmd);
1888 /* Append the previously read headers */
1889 err = list_append_list_unique(csp->headers, headers);
1890 destroy_list(headers);
1897 /*********************************************************************
1899 * Function : parse_client_request
1901 * Description : Parses the client's request and decides what to do
1904 * Note that since we're not using select() we could get
1905 * blocked here if a client connected, then didn't say
1909 * 1 : csp = Current client state (buffers, headers, etc...)
1911 * Returns : JB_ERR_OK or JB_ERR_PARSE
1913 *********************************************************************/
1914 static jb_err parse_client_request(struct client_state *csp)
1916 struct http_request *http = csp->http;
1919 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1920 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1921 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1922 && (csp->http->ssl == 0))
1924 /* Assume persistence until further notice */
1925 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1927 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1929 if (csp->http->ssl == 0)
1932 * This whole block belongs to chat() but currently
1933 * has to be executed before sed().
1935 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1937 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1939 return JB_ERR_PARSE;
1944 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1946 verify_request_length(csp);
1948 #ifndef FEATURE_HTTPS_INSPECTION
1951 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1955 err = sed(csp, FILTER_CLIENT_HEADERS);
1956 if (JB_ERR_OK != err)
1958 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1960 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1961 csp->ip_addr_str, csp->http->cmd);
1962 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1963 return JB_ERR_PARSE;
1965 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1967 /* Check request line for rewrites. */
1968 if ((NULL == csp->headers->first->str)
1969 || (strcmp(http->cmd, csp->headers->first->str) &&
1970 (JB_ERR_OK != change_request_destination(csp))))
1973 * A header filter broke the request line - bail out.
1975 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1976 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1977 /* XXX: Use correct size */
1978 log_error(LOG_LEVEL_CLF,
1979 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1980 log_error(LOG_LEVEL_ERROR,
1981 "Invalid request line after applying header filters.");
1982 free_http_request(http);
1984 return JB_ERR_PARSE;
1987 if (client_has_unsupported_expectations(csp))
1989 return JB_ERR_PARSE;
1997 /*********************************************************************
1999 * Function : send_http_request
2001 * Description : Sends the HTTP headers from the client request
2002 * and all the body data that has already been received.
2005 * 1 : csp = Current client state (buffers, headers, etc...)
2007 * Returns : 0 on success, anything else is an error.
2009 *********************************************************************/
2010 static int send_http_request(struct client_state *csp)
2015 hdr = list_to_text(csp->headers);
2018 /* FIXME Should handle error properly */
2019 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2021 list_remove_all(csp->headers);
2024 * Write the client's (modified) header to the server
2025 * (along with anything else that may be in the buffer)
2027 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2032 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2033 csp->http->hostport);
2035 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2036 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2039 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2040 csp->http->hostport);
2043 return write_failure;
2048 #ifdef FEATURE_HTTPS_INSPECTION
2049 /*********************************************************************
2051 * Function : receive_and_send_encrypted_post_data
2053 * Description : Reads remaining POST data from the client and sends
2057 * 1 : csp = Current client state (buffers, headers, etc...)
2059 * Returns : 0 on success, anything else is an error.
2061 *********************************************************************/
2062 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2064 int content_length_known = csp->expected_client_content_length != 0;
2066 while (is_ssl_pending(&(csp->ssl_client_attr))
2067 || (content_length_known && csp->expected_client_content_length != 0))
2069 unsigned char buf[BUFFER_SIZE];
2071 int max_bytes_to_read = sizeof(buf);
2073 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2075 max_bytes_to_read = (int)csp->expected_client_content_length;
2077 log_error(LOG_LEVEL_CONNECT,
2078 "Waiting for up to %d bytes of POST data from the client.",
2080 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2081 (unsigned)max_bytes_to_read);
2088 /* XXX: Does this actually happen? */
2091 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted POST data",
2093 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2098 if (csp->expected_client_content_length != 0)
2100 if (csp->expected_client_content_length >= len)
2102 csp->expected_client_content_length -= (unsigned)len;
2104 if (csp->expected_client_content_length == 0)
2106 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2112 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted POST data");
2119 /*********************************************************************
2121 * Function : send_https_request
2123 * Description : Sends the HTTP headers from the client request
2124 * and all the body data that has already been received.
2127 * 1 : csp = Current client state (buffers, headers, etc...)
2129 * Returns : 0 on success, anything else is an error.
2131 *********************************************************************/
2132 static int send_https_request(struct client_state *csp)
2138 hdr = list_to_text(csp->https_headers);
2141 /* FIXME Should handle error properly */
2142 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2144 list_remove_all(csp->https_headers);
2147 * Write the client's (modified) header to the server
2148 * (along with anything else that may be in the buffer)
2150 ret = ssl_send_data(&(csp->ssl_server_attr),
2151 (const unsigned char *)hdr, strlen(hdr));
2156 log_error(LOG_LEVEL_CONNECT,
2157 "Failed sending encrypted request headers to: %s: %E",
2158 csp->http->hostport);
2159 mark_server_socket_tainted(csp);
2163 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2164 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2165 csp->client_iob)) < 0))
2167 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2168 csp->http->hostport);
2171 if (flushed != 0 || csp->expected_client_content_length != 0)
2173 if (csp->expected_client_content_length != 0)
2175 if (csp->expected_client_content_length < flushed)
2177 log_error(LOG_LEVEL_ERROR,
2178 "Flushed %ld bytes of request body while only expecting %llu",
2179 flushed, csp->expected_client_content_length);
2180 csp->expected_client_content_length = 0;
2184 log_error(LOG_LEVEL_CONNECT,
2185 "Flushed %ld bytes of request body while expecting %llu",
2186 flushed, csp->expected_client_content_length);
2187 csp->expected_client_content_length -= (unsigned)flushed;
2188 if (receive_and_send_encrypted_post_data(csp))
2196 log_error(LOG_LEVEL_CONNECT,
2197 "Flushed %ld bytes of request body", flushed);
2201 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2208 /*********************************************************************
2210 * Function : receive_encrypted_request
2212 * Description : Receives an encrypted request.
2215 * 1 : csp = Current client state (buffers, headers, etc...)
2217 * Returns : JB_ERR_OK on success,
2218 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2220 *********************************************************************/
2221 static jb_err receive_encrypted_request(struct client_state *csp)
2223 char buf[BUFFER_SIZE];
2229 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2230 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2231 !data_is_available(csp->cfd, csp->config->socket_timeout))
2233 log_error(LOG_LEVEL_CONNECT,
2234 "Socket %d timed out while waiting for client headers", csp->cfd);
2235 return JB_ERR_PARSE;
2237 len = ssl_recv_data(&(csp->ssl_client_attr),
2238 (unsigned char *)buf, sizeof(buf));
2241 log_error(LOG_LEVEL_CONNECT,
2242 "Socket %d closed while waiting for client headers", csp->cfd);
2243 return JB_ERR_PARSE;
2247 return JB_ERR_PARSE;
2249 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2251 return JB_ERR_MEMORY;
2253 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2254 } while (p == NULL);
2256 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2262 /*********************************************************************
2264 * Function : process_encrypted_request
2266 * Description : Receives and parses an encrypted request.
2269 * 1 : csp = Current client state (buffers, headers, etc...)
2271 * Returns : JB_ERR_OK on success,
2272 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2274 *********************************************************************/
2275 static jb_err process_encrypted_request(struct client_state *csp)
2280 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2281 struct list header_list;
2282 struct list *headers = &header_list;
2284 assert(csp->ssl_with_client_is_opened);
2286 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2287 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2289 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2292 err = receive_encrypted_request(csp);
2293 if (err != JB_ERR_OK)
2295 if (csp->client_iob->cur == NULL ||
2296 csp->client_iob->cur == csp->client_iob->eod)
2299 * We did not receive any data, most likely because the
2300 * client is done. Don't log this as a parse failure.
2302 return JB_ERR_PARSE;
2304 /* XXX: Also used for JB_ERR_MEMORY */
2305 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2306 jb_err_to_string(err));
2307 ssl_send_data_delayed(&(csp->ssl_client_attr),
2308 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2312 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2313 request_line = get_header(csp->client_iob);
2314 if (request_line == NULL)
2316 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2317 ssl_send_data_delayed(&(csp->ssl_client_attr),
2318 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2319 return JB_ERR_PARSE;
2321 assert(*request_line != '\0');
2323 if (client_protocol_is_unsupported(csp, request_line))
2326 * If the protocol is unsupported we're done here.
2327 * client_protocol_is_unsupported() took care of sending
2328 * the error response and logging the error message.
2330 return JB_ERR_PARSE;
2333 #ifdef FEATURE_FORCE_LOAD
2334 if (force_required(csp, request_line))
2336 csp->flags |= CSP_FLAG_FORCED;
2338 #endif /* def FEATURE_FORCE_LOAD */
2340 free_http_request(csp->http);
2342 err = parse_http_request(request_line, csp->http);
2343 /* XXX: Restore ssl setting. This is ugly */
2344 csp->http->client_ssl = 1;
2345 csp->http->server_ssl = 1;
2347 freez(request_line);
2348 if (JB_ERR_OK != err)
2350 ssl_send_data_delayed(&(csp->ssl_client_attr),
2351 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2352 /* XXX: Use correct size */
2353 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2354 log_error(LOG_LEVEL_ERROR,
2355 "Couldn't parse request line received from %s: %s",
2356 csp->ip_addr_str, jb_err_to_string(err));
2358 free_http_request(csp->http);
2359 return JB_ERR_PARSE;
2362 /* Parse the rest of the client's headers. */
2366 p = get_header(csp->client_iob);
2370 /* There are no additional headers to read. */
2377 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2380 * Our attempts to get the request destination
2383 log_error(LOG_LEVEL_ERROR,
2384 "Failed to get the encrypted request destination");
2385 ssl_send_data_delayed(&(csp->ssl_client_attr),
2386 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2387 return JB_ERR_PARSE;
2390 /* Split the domain we just got for pattern matching */
2391 init_domain_components(csp->http);
2393 #ifdef FEATURE_CLIENT_TAGS
2394 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2395 if (csp->client_address == NULL)
2397 set_client_address(csp, headers);
2398 get_tag_list_for_client(csp->client_tags, csp->client_address);
2402 #ifdef FEATURE_TOGGLE
2403 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2407 * Determine the actions for this request after
2408 * clearing the ones from the previous one.
2410 free_current_action(csp->action);
2411 get_url_actions(csp, csp->http);
2414 enlist(csp->https_headers, csp->http->cmd);
2416 /* Append the previously read headers */
2417 err = list_append_list_unique(csp->https_headers, headers);
2418 destroy_list(headers);
2419 if (JB_ERR_OK != err)
2421 /* XXX: Send error message */
2425 /* XXX: Work around crash */
2426 csp->error_message = NULL;
2428 /* XXX: Why do this here? */
2431 err = sed_https(csp);
2432 if (JB_ERR_OK != err)
2434 ssl_send_data_delayed(&(csp->ssl_client_attr),
2435 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2436 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2438 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2439 csp->ip_addr_str, csp->http->cmd);
2440 return JB_ERR_PARSE;
2443 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2444 log_applied_actions(csp->action);
2445 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2452 /*********************************************************************
2454 * Function : cgi_page_requested
2456 * Description : Checks if a request is for an internal CGI page.
2459 * 1 : host = The host requested by the client.
2461 * Returns : 1 if a CGI page has been requested, 0 otherwise
2463 *********************************************************************/
2464 static int cgi_page_requested(const char *host)
2466 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2467 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2468 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2469 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2479 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2480 /*********************************************************************
2482 * Function : continue_https_chat
2484 * Description : Behaves similar to chat() but only deals with
2485 * https-inspected requests that arrive on an already
2486 * established connection. The first request is always
2487 * served by chat() which is a lot more complex as it
2488 * has to deal with forwarding settings and connection
2491 * If a connection to the server has already been
2492 * opened it is reused unless the request is blocked
2493 * or the forwarder changed.
2495 * If a connection to the server has not yet been
2496 * opened (because the previous request was crunched),
2497 * or the forwarder changed, the connection is dropped
2498 * so that the client retries on a fresh one.
2501 * 1 : csp = Current client state (buffers, headers, etc...)
2503 * Returns : Nothing.
2505 *********************************************************************/
2506 static void continue_https_chat(struct client_state *csp)
2508 const struct forward_spec *fwd;
2510 if (JB_ERR_OK != process_encrypted_request(csp))
2515 csp->requests_received_total++;
2518 * We have an encrypted request. Check if one of the crunchers wants it.
2520 if (crunch_response_triggered(csp, crunchers_all))
2523 * Yes. The client got the crunch response and we're done here.
2527 if (csp->ssl_with_server_is_opened == 0)
2529 log_error(LOG_LEVEL_CONNECT,
2530 "Dropping the client connection on socket %d. "
2531 "The server connection has not been established yet.",
2533 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2536 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2538 fwd = forward_url(csp, csp->http);
2539 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2541 log_error(LOG_LEVEL_CONNECT,
2542 "Dropping the client connection on socket %d with "
2543 "server socket %d connected to %s. The forwarder has changed.",
2544 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2545 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2549 log_error(LOG_LEVEL_CONNECT,
2550 "Reusing server socket %d connected to %s. Requests already sent: %u.",
2551 csp->server_connection.sfd, csp->server_connection.host,
2552 csp->server_connection.requests_sent_total);
2554 if (send_https_request(csp))
2557 * Most likely the server connection timed out. We can't easily
2558 * create a new one so simply drop the client connection without a
2559 * error response to let the client retry.
2561 log_error(LOG_LEVEL_CONNECT,
2562 "Dropping client connection on socket %d. "
2563 "Forwarding the encrypted client request failed.",
2567 csp->server_connection.requests_sent_total++;
2568 handle_established_connection(csp);
2569 freez(csp->receive_buffer);
2571 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2575 /*********************************************************************
2577 * Function : handle_established_connection
2579 * Description : Shuffle data between client and server once the
2580 * connection has been established.
2583 * 1 : csp = Current client state (buffers, headers, etc...)
2585 * Returns : Nothing.
2587 *********************************************************************/
2588 static void handle_established_connection(struct client_state *csp)
2594 struct pollfd poll_fds[2];
2598 struct timeval timeout;
2601 int ms_iis5_hack = 0;
2602 unsigned long long byte_count = 0;
2603 struct http_request *http;
2604 long len = 0; /* for buffer sizes (and negative error codes) */
2605 int buffer_and_filter_content = 0;
2606 unsigned int write_delay;
2607 #ifdef FEATURE_HTTPS_INSPECTION
2609 int use_ssl_tunnel = 0;
2610 csp->dont_verify_certificate = 0;
2612 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2614 /* Pass encrypted content without filtering. */
2619 /* Skeleton for HTTP response, if we should intercept the request */
2620 struct http_response *rsp;
2621 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2622 int watch_client_socket;
2625 csp->receive_buffer_size = csp->config->receive_buffer_size;
2626 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2627 if (csp->receive_buffer == NULL)
2629 log_error(LOG_LEVEL_ERROR,
2630 "Out of memory. Failed to allocate the receive buffer.");
2631 rsp = cgi_error_memory();
2632 send_crunch_response(csp, rsp);
2639 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2640 csp->cfd : csp->server_connection.sfd;
2643 /* pass data between the client and server
2644 * until one or the other shuts down the connection.
2649 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2650 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2652 write_delay = get_write_delay(csp);
2658 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2659 if (!watch_client_socket)
2661 maxfd = csp->server_connection.sfd;
2664 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2666 FD_SET(csp->cfd, &rfds);
2669 FD_SET(csp->server_connection.sfd, &rfds);
2670 #endif /* ndef HAVE_POLL */
2672 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2673 if ((csp->flags & CSP_FLAG_CHUNKED)
2674 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2675 && ((csp->iob->eod - csp->iob->cur) >= 5)
2676 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2679 * XXX: This check should be obsolete now,
2680 * but let's wait a while to be sure.
2682 log_error(LOG_LEVEL_CONNECT,
2683 "Looks like we got the last chunk together with "
2684 "the server headers but didn't detect it earlier. "
2685 "We better stop reading.");
2686 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2687 csp->expected_content_length = byte_count;
2688 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2690 if (server_body && server_response_is_complete(csp, byte_count))
2692 if (csp->expected_content_length == byte_count)
2694 log_error(LOG_LEVEL_CONNECT,
2695 "Done reading from server. Content length: %llu as expected. "
2696 "Bytes most recently read: %ld.",
2701 log_error(LOG_LEVEL_CONNECT,
2702 "Done reading from server. Expected content length: %llu. "
2703 "Actual content length: %llu. Bytes most recently read: %ld.",
2704 csp->expected_content_length, byte_count, len);
2708 * XXX: Should not jump around, handle_established_connection()
2709 * is complicated enough already.
2713 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2716 poll_fds[0].fd = csp->cfd;
2717 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2718 if (!watch_client_socket)
2721 * Ignore incoming data, but still watch out
2722 * for disconnects etc. These flags are always
2723 * implied anyway but explicitly setting them
2726 poll_fds[0].events = POLLERR|POLLHUP;
2731 poll_fds[0].events = POLLIN;
2733 poll_fds[1].fd = csp->server_connection.sfd;
2734 poll_fds[1].events = POLLIN;
2735 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2737 timeout.tv_sec = csp->config->socket_timeout;
2738 timeout.tv_usec = 0;
2739 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
2740 #endif /* def HAVE_POLL */
2742 /*server or client not responding in timeout */
2745 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2746 csp->config->socket_timeout, http->url);
2747 if ((byte_count == 0) && (http->ssl == 0))
2749 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2751 mark_server_socket_tainted(csp);
2752 #ifdef FEATURE_HTTPS_INSPECTION
2753 close_client_and_server_ssl_connections(csp);
2760 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2762 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2764 mark_server_socket_tainted(csp);
2765 #ifdef FEATURE_HTTPS_INSPECTION
2766 close_client_and_server_ssl_connections(csp);
2772 * This is the body of the browser's request,
2773 * just read and write it.
2775 * Receives data from browser and sends it to server
2777 * XXX: Make sure the client doesn't use pipelining
2778 * behind Privoxy's back.
2781 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2783 log_error(LOG_LEVEL_CONNECT,
2784 "The client socket %d has become unusable while "
2785 "the server socket %d is still open.",
2786 csp->cfd, csp->server_connection.sfd);
2787 mark_server_socket_tainted(csp);
2791 if (poll_fds[0].revents != 0)
2793 if (FD_ISSET(csp->cfd, &rfds))
2794 #endif /* def HAVE_POLL*/
2796 int max_bytes_to_read = (int)csp->receive_buffer_size;
2798 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2799 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2801 if (data_is_available(csp->cfd, 0))
2804 * If the next request is already waiting, we have
2805 * to stop select()ing the client socket. Otherwise
2806 * we would always return right away and get nothing
2809 watch_client_socket = 0;
2810 log_error(LOG_LEVEL_CONNECT,
2811 "Stop watching client socket %d. "
2812 "There's already another request waiting.",
2817 * If the client socket is set, but there's no data
2818 * available on the socket, the client went fishing
2819 * and continuing talking to the server makes no sense.
2821 log_error(LOG_LEVEL_CONNECT,
2822 "The client closed socket %d while "
2823 "the server socket %d is still open.",
2824 csp->cfd, csp->server_connection.sfd);
2825 mark_server_socket_tainted(csp);
2828 if (csp->expected_client_content_length != 0)
2830 if (csp->expected_client_content_length < csp->receive_buffer_size)
2832 max_bytes_to_read = (int)csp->expected_client_content_length;
2834 log_error(LOG_LEVEL_CONNECT,
2835 "Waiting for up to %d bytes from the client.",
2838 assert(max_bytes_to_read <= csp->receive_buffer_size);
2839 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2841 #ifdef FEATURE_HTTPS_INSPECTION
2842 if (client_use_ssl(csp))
2844 if (csp->http->status == 101)
2846 len = ssl_recv_data(&(csp->ssl_client_attr),
2847 (unsigned char *)csp->receive_buffer,
2848 (size_t)max_bytes_to_read);
2851 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
2852 "on client socket %d for an upgraded connection",
2858 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
2859 "on client socket %d for an upgraded connection",
2863 byte_count += (unsigned long long)len;
2864 len = ssl_send_data(&(csp->ssl_server_attr),
2865 (unsigned char *)csp->receive_buffer, (size_t)len);
2868 log_error(LOG_LEVEL_ERROR, "Failed to send data "
2869 "on server socket %d for an upgraded connection",
2870 csp->server_connection.sfd);
2875 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
2879 #endif /* def FEATURE_HTTPS_INSPECTION */
2881 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2885 /* XXX: not sure if this is necessary. */
2886 mark_server_socket_tainted(csp);
2887 break; /* "game over, man" */
2890 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2891 if (csp->expected_client_content_length != 0)
2893 assert(len <= max_bytes_to_read);
2894 csp->expected_client_content_length -= (unsigned)len;
2895 log_error(LOG_LEVEL_CONNECT,
2896 "Expected client content length set to %llu "
2897 "after reading %ld bytes.",
2898 csp->expected_client_content_length, len);
2899 if (csp->expected_client_content_length == 0)
2901 log_error(LOG_LEVEL_CONNECT,
2902 "Done reading from the client.");
2903 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2906 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2908 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2910 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2911 mark_server_socket_tainted(csp);
2919 * The server wants to talk. It could be the header or the body.
2920 * If `hdr' is null, then it's the header otherwise it's the body.
2921 * FIXME: Does `hdr' really mean `host'? No.
2924 if (poll_fds[1].revents != 0)
2926 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2927 #endif /* HAVE_POLL */
2929 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2931 * If we are buffering content, we don't want to eat up to
2932 * buffer-limit bytes if the client no longer cares about them.
2933 * If we aren't buffering, however, a dead client socket will be
2934 * noticed pretty much right away anyway, so we can reduce the
2935 * overhead by skipping the check.
2937 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2940 log_error(LOG_LEVEL_CONNECT,
2941 "The server still wants to talk, but the client may already have hung up on us.");
2943 log_error(LOG_LEVEL_CONNECT,
2944 "The server still wants to talk, but the client hung up on us.");
2945 mark_server_socket_tainted(csp);
2946 #ifdef FEATURE_HTTPS_INSPECTION
2947 close_client_and_server_ssl_connections(csp);
2950 #endif /* def _WIN32 */
2952 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2954 #ifdef FEATURE_HTTPS_INSPECTION
2956 * Reading data from standard or secured connection (HTTP/HTTPS)
2958 if (server_use_ssl(csp))
2960 len = ssl_recv_data(&(csp->ssl_server_attr),
2961 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2966 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2967 (int)csp->receive_buffer_size);
2972 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2974 if ((http->ssl && (csp->fwd == NULL))
2975 #ifdef FEATURE_HTTPS_INSPECTION
2981 * Just hang up. We already confirmed the client's CONNECT
2982 * request with status code 200 and unencrypted content is
2983 * no longer welcome.
2985 log_error(LOG_LEVEL_ERROR,
2986 "CONNECT already confirmed. Unable to tell the client about the problem.");
2989 else if (byte_count)
2992 * Just hang up. We already transmitted the original headers
2993 * and parts of the original content and therefore missed the
2994 * chance to send an error message (without risking data corruption).
2996 * XXX: we could retry with a fancy range request here.
2998 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2999 "Unable to tell the client about the problem.");
3000 mark_server_socket_tainted(csp);
3001 #ifdef FEATURE_HTTPS_INSPECTION
3002 close_client_and_server_ssl_connections(csp);
3007 * XXX: Consider handling the cases above the same.
3009 mark_server_socket_tainted(csp);
3013 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3014 if (csp->flags & CSP_FLAG_CHUNKED)
3016 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3018 /* XXX: this is a temporary hack */
3019 log_error(LOG_LEVEL_CONNECT,
3020 "Looks like we reached the end of the last chunk. "
3021 "We better stop reading.");
3022 csp->expected_content_length = byte_count + (unsigned long long)len;
3023 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3027 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3030 * This is guaranteed by allocating with zalloc_or_die()
3031 * and never (intentionally) writing to the last byte.
3033 * csp->receive_buffer_size is the size of the part of the
3034 * buffer we intentionally write to, but we actually
3035 * allocated csp->receive_buffer_size+1 bytes so the assertion
3036 * stays within the allocated range.
3038 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3041 * Add a trailing zero to let be able to use string operations.
3042 * XXX: do we still need this with filter_popups gone?
3044 assert(len <= csp->receive_buffer_size);
3045 csp->receive_buffer[len] = '\0';
3048 * Normally, this would indicate that we've read
3049 * as much as the server has sent us and we can
3050 * close the client connection. However, Microsoft
3051 * in its wisdom has released IIS/5 with a bug that
3052 * prevents it from sending the trailing \r\n in
3053 * a 302 redirect header (and possibly other headers).
3054 * To work around this if we've haven't parsed
3055 * a full header we'll append a trailing \r\n
3056 * and see if this now generates a valid one.
3058 * This hack shouldn't have any impacts. If we've
3059 * already transmitted the header or if this is a
3060 * SSL connection, then we won't bother with this
3061 * hack. So we only work on partially received
3062 * headers. If we append a \r\n and this still
3063 * doesn't generate a valid header, then we won't
3064 * transmit anything to the client.
3069 if (server_body || (http->ssl
3070 #ifdef FEATURE_HTTPS_INSPECTION
3076 * If we have been buffering up the document,
3077 * now is the time to apply content modification
3078 * and send the result to the client.
3080 if (buffer_and_filter_content)
3082 p = execute_content_filters(csp);
3084 * If content filtering fails, use the original
3085 * buffer and length.
3086 * (see p != NULL ? p : csp->iob->cur below)
3090 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3092 #ifdef FEATURE_COMPRESSION
3093 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3094 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3096 char *compressed_content = compress_buffer(p,
3097 (size_t *)&csp->content_length, csp->config->compression_level);
3098 if (compressed_content != NULL)
3101 p = compressed_content;
3102 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3107 if (JB_ERR_OK != update_server_headers(csp))
3109 log_error(LOG_LEVEL_FATAL,
3110 "Failed to update server headers. after filtering.");
3113 hdr = list_to_text(csp->headers);
3116 /* FIXME Should handle error properly */
3117 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3120 #ifdef FEATURE_HTTPS_INSPECTION
3122 * Sending data with standard or secured connection (HTTP/HTTPS)
3124 if (client_use_ssl(csp))
3126 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3127 (const unsigned char *)hdr, strlen(hdr),
3128 get_write_delay(csp)) < 0)
3129 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3130 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3131 csp->content_length, get_write_delay(csp)) < 0))
3133 log_error(LOG_LEVEL_ERROR, "write modified content to "
3134 "client over TLS/SSL failed");
3137 mark_server_socket_tainted(csp);
3138 close_client_and_server_ssl_connections(csp);
3143 #endif /* def FEATURE_HTTPS_INSPECTION */
3145 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3146 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3147 (size_t)csp->content_length, write_delay))
3149 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3152 mark_server_socket_tainted(csp);
3161 break; /* "game over, man" */
3165 * This is NOT the body, so
3166 * Let's pretend the server just sent us a blank line.
3168 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3169 len = (int)strlen(csp->receive_buffer);
3172 * Now, let the normal header parsing algorithm below do its
3173 * job. If it fails, we'll exit instead of continuing.
3180 * If we're in the body of the server document, just write it to
3181 * the client, unless we need to buffer the body for later
3182 * content-filtering.
3184 if (server_body || (http->ssl
3185 #ifdef FEATURE_HTTPS_INSPECTION
3190 if (buffer_and_filter_content)
3193 * If there is no memory left for buffering the content, or the buffer limit
3194 * has been reached, switch to non-filtering mode, i.e. make & write the
3195 * header, flush the iob and buf, and get out of the way.
3197 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3202 log_error(LOG_LEVEL_INFO,
3203 "Flushing header and buffers. Stepping back from filtering.");
3205 hdr = list_to_text(csp->headers);
3209 * Memory is too tight to even generate the header.
3210 * Send our static "Out-of-memory" page.
3212 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3213 rsp = cgi_error_memory();
3214 send_crunch_response(csp, rsp);
3215 mark_server_socket_tainted(csp);
3216 #ifdef FEATURE_HTTPS_INSPECTION
3217 close_client_and_server_ssl_connections(csp);
3221 hdrlen = strlen(hdr);
3223 #ifdef FEATURE_HTTPS_INSPECTION
3225 * Sending data with standard or secured connection (HTTP/HTTPS)
3227 if (client_use_ssl(csp))
3229 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3230 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3231 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3233 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3234 (const unsigned char *)csp->receive_buffer, (size_t)len,
3235 get_write_delay(csp)) < 0))
3237 log_error(LOG_LEVEL_CONNECT,
3238 "Flush header and buffers to client failed");
3240 mark_server_socket_tainted(csp);
3241 close_client_and_server_ssl_connections(csp);
3246 #endif /* def FEATURE_HTTPS_INSPECTION */
3248 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3249 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3250 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3253 log_error(LOG_LEVEL_CONNECT,
3254 "Flush header and buffers to client failed: %E");
3256 mark_server_socket_tainted(csp);
3262 * Reset the byte_count to the amount of bytes
3263 * we just flushed. len will be added a few lines below,
3264 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3266 byte_count = (unsigned long long)flushed;
3268 buffer_and_filter_content = 0;
3274 #ifdef FEATURE_HTTPS_INSPECTION
3276 * Sending data with standard or secured connection (HTTP/HTTPS)
3278 if (client_use_ssl(csp))
3280 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3281 (const unsigned char *)csp->receive_buffer, (size_t)len,
3282 get_write_delay(csp));
3285 log_error(LOG_LEVEL_ERROR,
3286 "Sending data to client failed");
3287 mark_server_socket_tainted(csp);
3288 close_client_and_server_ssl_connections(csp);
3293 #endif /* def FEATURE_HTTPS_INSPECTION */
3295 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3296 (size_t)len, write_delay))
3298 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3299 mark_server_socket_tainted(csp);
3304 byte_count += (unsigned long long)len;
3310 * We're still looking for the end of the server's header.
3311 * Buffer up the data we just read. If that fails, there's
3312 * little we can do but send our static out-of-memory page.
3314 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3316 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3317 rsp = cgi_error_memory();
3318 send_crunch_response(csp, rsp);
3319 mark_server_socket_tainted(csp);
3320 #ifdef FEATURE_HTTPS_INSPECTION
3321 close_client_and_server_ssl_connections(csp);
3326 /* Convert iob into something sed() can digest */
3327 if (JB_ERR_PARSE == get_server_headers(csp))
3332 * Well, we tried our MS IIS/5 hack and it didn't work.
3333 * The header is incomplete and there isn't anything
3334 * we can do about it.
3336 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3337 "Applying the MS IIS5 hack didn't help.");
3338 log_error(LOG_LEVEL_CLF,
3339 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3340 #ifdef FEATURE_HTTPS_INSPECTION
3342 * Sending data with standard or secured connection (HTTP/HTTPS)
3344 if (client_use_ssl(csp))
3346 ssl_send_data_delayed(&(csp->ssl_client_attr),
3347 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3348 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3351 #endif /* def FEATURE_HTTPS_INSPECTION */
3353 write_socket_delayed(csp->cfd,
3354 INVALID_SERVER_HEADERS_RESPONSE,
3355 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3357 mark_server_socket_tainted(csp);
3358 #ifdef FEATURE_HTTPS_INSPECTION
3359 close_client_and_server_ssl_connections(csp);
3366 * Since we have to wait for more from the server before
3367 * we can parse the headers we just continue here.
3369 log_error(LOG_LEVEL_CONNECT,
3370 "Continuing buffering server headers from socket %d. "
3371 "Bytes most recently read: %ld.", csp->cfd, len);
3378 * Account for the content bytes we
3379 * might have gotten with the headers.
3381 assert(csp->iob->eod >= csp->iob->cur);
3382 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3385 /* Did we actually get anything? */
3386 if (NULL == csp->headers->first)
3388 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3390 log_error(LOG_LEVEL_ERROR,
3391 "No server or forwarder response received on socket %d. "
3392 "Closing client socket %d without sending data.",
3393 csp->server_connection.sfd, csp->cfd);
3394 log_error(LOG_LEVEL_CLF,
3395 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3399 log_error(LOG_LEVEL_ERROR,
3400 "No server or forwarder response received on socket %d.",
3401 csp->server_connection.sfd);
3402 send_crunch_response(csp, error_response(csp, "no-server-data"));
3404 free_http_request(http);
3405 mark_server_socket_tainted(csp);
3406 #ifdef FEATURE_HTTPS_INSPECTION
3407 close_client_and_server_ssl_connections(csp);
3412 if (!csp->headers->first->str)
3414 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3416 assert(csp->headers->first->str);
3418 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3419 strncmpic(csp->headers->first->str, "ICY", 3))
3422 * It doesn't look like a HTTP (or Shoutcast) response:
3423 * tell the client and log the problem.
3425 if (strlen(csp->headers->first->str) > 30)
3427 csp->headers->first->str[30] = '\0';
3429 log_error(LOG_LEVEL_ERROR,
3430 "Invalid server or forwarder response. Starts with: %s",
3431 csp->headers->first->str);
3432 log_error(LOG_LEVEL_CLF,
3433 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3434 #ifdef FEATURE_HTTPS_INSPECTION
3436 * Sending data with standard or secured connection (HTTP/HTTPS)
3438 if (client_use_ssl(csp))
3440 ssl_send_data_delayed(&(csp->ssl_client_attr),
3441 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3442 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3443 get_write_delay(csp));
3446 #endif /* def FEATURE_HTTPS_INSPECTION */
3448 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3449 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3451 free_http_request(http);
3452 mark_server_socket_tainted(csp);
3453 #ifdef FEATURE_HTTPS_INSPECTION
3454 close_client_and_server_ssl_connections(csp);
3460 * We have now received the entire server header,
3461 * filter it and send the result to the client
3463 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3465 log_error(LOG_LEVEL_CLF,
3466 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3467 #ifdef FEATURE_HTTPS_INSPECTION
3469 * Sending data with standard or secured connection (HTTP/HTTPS)
3471 if (client_use_ssl(csp))
3473 ssl_send_data_delayed(&(csp->ssl_client_attr),
3474 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3475 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3476 get_write_delay(csp));
3481 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3482 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3484 free_http_request(http);
3485 mark_server_socket_tainted(csp);
3486 #ifdef FEATURE_HTTPS_INSPECTION
3487 close_client_and_server_ssl_connections(csp);
3491 hdr = list_to_text(csp->headers);
3494 /* FIXME Should handle error properly */
3495 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3498 if ((csp->flags & CSP_FLAG_CHUNKED)
3499 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3500 && ((csp->iob->eod - csp->iob->cur) >= 5)
3501 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3503 log_error(LOG_LEVEL_CONNECT,
3504 "Looks like we got the last chunk together with "
3505 "the server headers. We better stop reading.");
3506 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3507 csp->expected_content_length = byte_count;
3508 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3511 csp->server_connection.response_received = time(NULL);
3513 if (crunch_response_triggered(csp, crunchers_light))
3516 * One of the tags created by a server-header
3517 * tagger triggered a crunch. We already
3518 * delivered the crunch response to the client
3519 * and are done here after cleaning up.
3522 mark_server_socket_tainted(csp);
3523 #ifdef FEATURE_HTTPS_INSPECTION
3524 close_client_and_server_ssl_connections(csp);
3529 /* Buffer and pcrs filter this if appropriate. */
3530 buffer_and_filter_content = content_requires_filtering(csp);
3532 if (!buffer_and_filter_content)
3535 * Write the server's (modified) header to
3536 * the client (along with anything else that
3537 * may be in the buffer). Use standard or secured
3540 #ifdef FEATURE_HTTPS_INSPECTION
3541 if (client_use_ssl(csp))
3543 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3544 (const unsigned char *)hdr, strlen(hdr),
3545 get_write_delay(csp)) < 0)
3546 || (len = ssl_flush_socket(&(csp->ssl_client_attr),
3549 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3552 * The write failed, so don't bother mentioning it
3553 * to the client... it probably can't hear us anyway.
3556 mark_server_socket_tainted(csp);
3557 #ifdef FEATURE_HTTPS_INSPECTION
3558 close_client_and_server_ssl_connections(csp);
3564 #endif /* def FEATURE_HTTPS_INSPECTION */
3566 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3567 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3569 log_error(LOG_LEVEL_ERROR,
3570 "write header to client failed");
3572 * The write failed, so don't bother mentioning it
3573 * to the client... it probably can't hear us anyway.
3576 mark_server_socket_tainted(csp);
3582 /* we're finished with the server's header */
3588 * If this was a MS IIS/5 hack then it means the server
3589 * has already closed the connection. Nothing more to read.
3594 log_error(LOG_LEVEL_ERROR,
3595 "Closed server connection detected. "
3596 "Applying the MS IIS5 hack didn't help.");
3597 log_error(LOG_LEVEL_CLF,
3598 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3599 #ifdef FEATURE_HTTPS_INSPECTION
3601 * Sending data with standard or secured connection (HTTP/HTTPS)
3603 if (client_use_ssl(csp))
3605 ssl_send_data_delayed(&(csp->ssl_client_attr),
3606 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3607 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3608 get_write_delay(csp));
3611 #endif /* def FEATURE_HTTPS_INSPECTION */
3613 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3614 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3616 mark_server_socket_tainted(csp);
3617 #ifdef FEATURE_HTTPS_INSPECTION
3618 close_client_and_server_ssl_connections(csp);
3625 mark_server_socket_tainted(csp);
3626 #ifdef FEATURE_HTTPS_INSPECTION
3627 close_client_and_server_ssl_connections(csp);
3629 return; /* huh? we should never get here */
3632 if (csp->content_length == 0)
3635 * If Privoxy didn't recalculate the Content-Length,
3636 * byte_count is still correct.
3638 csp->content_length = byte_count;
3641 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3642 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3643 && (csp->expected_content_length != byte_count))
3645 log_error(LOG_LEVEL_CONNECT,
3646 "Received %llu bytes while expecting %llu.",
3647 byte_count, csp->expected_content_length);
3648 mark_server_socket_tainted(csp);
3652 #ifdef FEATURE_HTTPS_INSPECTION
3653 if (client_use_ssl(csp))
3655 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
3656 csp->ip_addr_str, http->gpc, http->hostport, http->path,
3657 http->version, csp->content_length);
3662 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3663 csp->ip_addr_str, http->ocmd, csp->content_length);
3665 csp->server_connection.timestamp = time(NULL);
3669 /*********************************************************************
3673 * Description : Once a connection from the client has been accepted,
3674 * this function is called (via serve()) to handle the
3675 * main business of the communication. This function
3676 * returns after dealing with a single request. It can
3677 * be called multiple times with the same client socket
3678 * if the client is keeping the connection alive.
3680 * The decision whether or not a client connection will
3681 * be kept alive is up to the caller which also must
3682 * close the client socket when done.
3684 * FIXME: chat is nearly thousand lines long.
3688 * 1 : csp = Current client state (buffers, headers, etc...)
3690 * Returns : Nothing.
3692 *********************************************************************/
3693 static void chat(struct client_state *csp)
3695 const struct forward_spec *fwd;
3696 struct http_request *http;
3697 /* Skeleton for HTTP response, if we should intercept the request */
3698 struct http_response *rsp;
3699 #ifdef FEATURE_HTTPS_INSPECTION
3700 int use_ssl_tunnel = 0;
3705 if (receive_client_request(csp) != JB_ERR_OK)
3709 if (parse_client_request(csp) != JB_ERR_OK)
3714 /* decide how to route the HTTP request */
3715 fwd = forward_url(csp, http);
3717 #ifdef FEATURE_HTTPS_INSPECTION
3719 * Setting flags to use old solution with SSL tunnel and to disable
3720 * certificate verification.
3722 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
3723 && !cgi_page_requested(csp->http->host))
3728 if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3730 csp->dont_verify_certificate = 1;
3735 * build the http request to send to the server
3736 * we have to do one of the following:
3738 * create = use the original HTTP request to create a new
3739 * HTTP request that has either the path component
3740 * without the http://domainspec (w/path) or the
3741 * full orininal URL (w/url)
3742 * Note that the path and/or the HTTP version may
3743 * have been altered by now.
3745 * SSL proxy = Open a socket to the host:port of the server
3746 * and create TLS/SSL connection with server and
3747 * with client. Then behave like mediator between
3748 * client and server over TLS/SSL.
3750 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3751 * with request to a parent proxy. Note that we'll be sending
3752 * forwarding the CFAIL message ourselves if connecting to the parent
3753 * fails, but we won't send a CSUCCEED message if it works,
3754 * since that would result in a double message (ours and the
3755 * parent's). After sending the request to the parent, we
3756 * must parse answer and send it to client. If connection
3757 * with server is established, we do TLS/SSL proxy. Otherwise
3758 * we send parent response to client and close connections.
3760 * here's the matrix:
3763 * +--------+--------+
3765 * 0 | create | SSL |
3766 * | w/path | proxy |
3767 * Forwarding +--------+--------+
3769 * 1 | create | proxy |
3770 * | w/url |+forward|
3771 * +--------+--------+
3775 #ifdef FEATURE_HTTPS_INSPECTION
3777 * Presetting SSL client and server flags
3779 if (http->ssl && !use_ssl_tunnel)
3781 http->client_ssl = 1;
3782 http->server_ssl = 1;
3786 http->client_ssl = 0;
3787 http->server_ssl = 0;
3791 #ifdef FEATURE_HTTPS_INSPECTION
3793 * Log the request unless we're https inspecting
3794 * in which case we don't have the path yet and
3795 * will log the request later.
3797 if (!client_use_ssl(csp))
3800 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
3803 if (http->ssl && connect_port_is_forbidden(csp))
3805 const char *acceptable_connect_ports =
3806 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3807 assert(NULL != acceptable_connect_ports);
3808 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3809 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3810 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3811 csp->action->flags |= ACTION_BLOCK;
3813 #ifdef FEATURE_HTTPS_INSPECTION
3814 http->client_ssl = 0;
3815 http->server_ssl = 0;
3820 freez(csp->headers->first->str);
3821 build_request_line(csp, fwd, &csp->headers->first->str);
3824 * We have a request. Check if one of the crunchers wants it
3825 * unless the client wants to use TLS/SSL in which case we
3826 * haven't setup the TLS context yet and will send the crunch
3830 #ifdef FEATURE_HTTPS_INSPECTION
3831 !client_use_ssl(csp) &&
3833 crunch_response_triggered(csp, crunchers_all))
3836 * Yes. The client got the crunch response and we're done here.
3841 log_applied_actions(csp->action);
3842 if (fwd->forward_host)
3844 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3845 fwd->forward_host, fwd->forward_port, http->hostport);
3849 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3852 /* here we connect to the server, gateway, or the forwarder */
3854 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3855 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3856 && socket_is_still_alive(csp->server_connection.sfd)
3857 && connection_destination_matches(&csp->server_connection, http, fwd))
3859 log_error(LOG_LEVEL_CONNECT,
3860 "Reusing server socket %d connected to %s. Total requests: %u.",
3861 csp->server_connection.sfd, csp->server_connection.host,
3862 csp->server_connection.requests_sent_total);
3866 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3868 #ifdef FEATURE_CONNECTION_SHARING
3869 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
3870 #ifdef FEATURE_HTTPS_INSPECTION
3871 && !server_use_ssl(csp)
3875 remember_connection(&csp->server_connection);
3878 #endif /* def FEATURE_CONNECTION_SHARING */
3880 log_error(LOG_LEVEL_CONNECT,
3881 "Closing server socket %d connected to %s. Total requests: %u.",
3882 csp->server_connection.sfd, csp->server_connection.host,
3883 csp->server_connection.requests_sent_total);
3884 close_socket(csp->server_connection.sfd);
3886 mark_connection_closed(&csp->server_connection);
3888 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3889 #ifdef FEATURE_HTTPS_INSPECTION
3890 if (http->ssl && !use_ssl_tunnel)
3894 * Creating a SSL proxy.
3896 * By sending the CSUCCEED message we're lying to the client as
3897 * the connection hasn't actually been established yet. We don't
3898 * establish the connection until we have seen and parsed the
3899 * encrypted client headers.
3901 if (write_socket_delayed(csp->cfd, CSUCCEED,
3902 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3904 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3908 ret = create_client_ssl_connection(csp);
3911 log_error(LOG_LEVEL_ERROR,
3912 "Failed to open a secure connection with the client");
3915 if (JB_ERR_OK != process_encrypted_request(csp))
3917 close_client_ssl_connection(csp);
3921 * We have an encrypted request. Check if one of the crunchers now
3922 * wants it (for example because the previously invisible path was
3923 * required to match).
3925 if (crunch_response_triggered(csp, crunchers_all))
3928 * Yes. The client got the crunch response and we're done here.
3935 * Connecting to destination server
3937 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3939 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3941 if (fwd->type != SOCKS_NONE)
3944 rsp = error_response(csp, "forwarding-failed");
3946 else if (errno == EINVAL)
3948 rsp = error_response(csp, "no-such-domain");
3952 rsp = error_response(csp, "connect-failed");
3955 /* Write the answer to the client */
3958 send_crunch_response(csp, rsp);
3962 * Temporary workaround to prevent already-read client
3963 * bodies from being parsed as new requests. For now we
3964 * err on the safe side and throw all the following
3965 * requests under the bus, even if no client body has been
3966 * buffered. A compliant client will repeat the dropped
3967 * requests on an untainted connection.
3969 * The proper fix is to discard the no longer needed
3970 * client body in the buffer (if there is one) and to
3971 * continue parsing the bytes that follow.
3973 #ifdef FEATURE_HTTPS_INSPECTION
3974 close_client_ssl_connection(csp);
3976 drain_and_close_socket(csp->cfd);
3977 csp->cfd = JB_INVALID_SOCKET;
3982 #ifdef FEATURE_HTTPS_INSPECTION
3984 * Creating TLS/SSL connections with destination server or parent
3985 * proxy. If forwarding is enabled, we must send client request to
3986 * parent proxy and receive, parse and resend parent proxy answer.
3988 if (http->ssl && !use_ssl_tunnel)
3990 if (fwd->forward_host != NULL)
3992 char server_response[BUFFER_SIZE];
3995 char *hdr = list_to_text(csp->headers);
3996 memset(server_response, 0, sizeof(server_response));
4000 log_error(LOG_LEVEL_FATAL,
4001 "Out of memory parsing client header");
4003 list_remove_all(csp->headers);
4006 * Sending client's CONNECT request to the parent proxy
4008 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4014 log_error(LOG_LEVEL_CONNECT,
4015 "Sending request headers to: %s failed", http->hostport);
4016 mark_server_socket_tainted(csp);
4017 close_client_ssl_connection(csp);
4021 /* Waiting for parent proxy server response */
4022 len = read_socket(csp->server_connection.sfd, server_response,
4023 sizeof(server_response)-1);
4027 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4028 "server on socket %d.", csp->server_connection.sfd);
4030 rsp = error_response(csp, "no-server-data");
4033 send_crunch_response(csp, rsp);
4035 mark_server_socket_tainted(csp);
4036 close_client_ssl_connection(csp);
4041 * Test if the connection to the destination server was
4042 * established successfully by the parent proxy.
4044 if (!tunnel_established_successfully(server_response, (unsigned int)len))
4046 log_error(LOG_LEVEL_ERROR,
4047 "The forwarder %s failed to establish a connection with %s",
4048 fwd->forward_host, http->host);
4049 rsp = error_response(csp, "connect-failed");
4052 send_crunch_response(csp, rsp);
4054 mark_server_socket_tainted(csp);
4055 close_client_ssl_connection(csp);
4058 } /* -END- if (fwd->forward_host != NULL) */
4061 * We can now create the TLS/SSL connection with the destination server.
4063 int ret = create_server_ssl_connection(csp);
4066 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4067 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4070 * If the server certificate is invalid, we must inform
4071 * the client and then close connection to the client.
4073 ssl_send_certificate_error(csp);
4074 close_client_and_server_ssl_connections(csp);
4077 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4078 || csp->server_cert_verification_result == SSL_CERT_VALID)
4081 * The TLS/SSL connection wasn't created but an invalid
4082 * certificate wasn't detected. Report it as connection
4085 rsp = error_response(csp, "connect-failed");
4088 send_crunch_response(csp, rsp);
4090 close_client_and_server_ssl_connections(csp);
4094 }/* -END- if (http->ssl) */
4095 #endif /* def FEATURE_HTTPS_INSPECTION */
4097 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4098 save_connection_destination(csp->server_connection.sfd,
4099 http, fwd, &csp->server_connection);
4100 csp->server_connection.keep_alive_timeout =
4101 (unsigned)csp->config->keep_alive_timeout;
4103 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4105 csp->server_connection.requests_sent_total++;
4107 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4109 /* Client headers have been sent optimistically */
4110 assert(csp->headers->last == NULL);
4112 else if (http->ssl == 0 || (fwd->forward_host
4113 #ifdef FEATURE_HTTPS_INSPECTION
4118 if (send_http_request(csp))
4120 rsp = error_response(csp, "connect-failed");
4123 send_crunch_response(csp, rsp);
4131 * Using old solution with SSL tunnel or new solution with SSL proxy
4133 list_remove_all(csp->headers);
4134 #ifdef FEATURE_HTTPS_INSPECTION
4139 * We're running an SSL tunnel and we're not forwarding,
4140 * so just ditch the client headers, send the "connect succeeded"
4141 * message to the client, flush the rest, and get out of the way.
4143 if (write_socket_delayed(csp->cfd, CSUCCEED,
4144 strlen(CSUCCEED), get_write_delay(csp)))
4149 #ifdef FEATURE_HTTPS_INSPECTION
4153 * If server certificate has been verified and is invalid,
4154 * we must inform the client and then close the connection
4155 * with client and server.
4157 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4158 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4160 ssl_send_certificate_error(csp);
4161 close_client_and_server_ssl_connections(csp);
4164 if (send_https_request(csp))
4166 rsp = error_response(csp, "connect-failed");
4169 send_crunch_response(csp, rsp);
4171 close_client_and_server_ssl_connections(csp);
4175 #endif /* def FEATURE_HTTPS_INSPECTION */
4176 clear_iob(csp->client_iob);
4177 }/* -END- else ... if (http->ssl == 1) */
4179 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4181 /* XXX: should the time start earlier for optimistically sent data? */
4182 csp->server_connection.request_sent = time(NULL);
4184 handle_established_connection(csp);
4185 freez(csp->receive_buffer);
4190 /*********************************************************************
4192 * Function : fuzz_server_response
4194 * Description : Treat the input as a whole server response.
4197 * 1 : csp = Current client state (buffers, headers, etc...)
4198 * 2 : fuzz_input_file = File to read the input from.
4202 *********************************************************************/
4203 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4205 static struct forward_spec fwd; /* Zero'd due to being static */
4208 if (strcmp(fuzz_input_file, "-") == 0)
4210 /* XXX: Doesn't work yet. */
4211 csp->server_connection.sfd = 0;
4215 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4216 if (csp->server_connection.sfd == -1)
4218 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4223 csp->content_type |= CT_GIF;
4224 csp->action->flags |= ACTION_DEANIMATE;
4225 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4227 csp->http->path = strdup_or_die("/");
4228 csp->http->host = strdup_or_die("fuzz.example.org");
4229 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4230 /* Prevent client socket monitoring */
4231 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4232 csp->flags |= CSP_FLAG_CHUNKED;
4234 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4235 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4237 csp->content_type |= CT_DECLARED|CT_GIF;
4239 csp->config->socket_timeout = 0;
4241 cgi_init_error_messages();
4243 handle_established_connection(csp);
4244 freez(csp->receive_buffer);
4251 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4252 /*********************************************************************
4254 * Function : prepare_csp_for_next_request
4256 * Description : Put the csp in a mostly vergin state.
4259 * 1 : csp = Current client state (buffers, headers, etc...)
4263 *********************************************************************/
4264 static void prepare_csp_for_next_request(struct client_state *csp)
4266 csp->content_type = 0;
4267 csp->content_length = 0;
4268 csp->expected_content_length = 0;
4269 csp->expected_client_content_length = 0;
4270 list_remove_all(csp->headers);
4271 clear_iob(csp->iob);
4272 freez(csp->error_message);
4273 free_http_request(csp->http);
4274 destroy_list(csp->headers);
4275 #ifdef FEATURE_HTTPS_INSPECTION
4276 destroy_list(csp->https_headers);
4278 destroy_list(csp->tags);
4279 #ifdef FEATURE_CLIENT_TAGS
4280 destroy_list(csp->client_tags);
4281 freez(csp->client_address);
4283 free_current_action(csp->action);
4284 if (NULL != csp->fwd)
4286 unload_forward_spec(csp->fwd);
4289 /* XXX: Store per-connection flags someplace else. */
4290 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4291 #ifdef FEATURE_TOGGLE
4292 if (global_toggle_state)
4293 #endif /* def FEATURE_TOGGLE */
4295 csp->flags |= CSP_FLAG_TOGGLED_ON;
4298 if (csp->client_iob->eod > csp->client_iob->cur)
4300 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4301 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4303 assert(bytes_to_shift > 0);
4304 assert(data_length > 0);
4306 log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4307 data_length, bytes_to_shift);
4308 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4309 csp->client_iob->cur = csp->client_iob->buf;
4310 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4311 csp->client_iob->eod = csp->client_iob->buf + data_length;
4312 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4314 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4319 * We mainly care about resetting client_iob->cur so we don't
4320 * waste buffer space at the beginning and don't mess up the
4321 * request restoration done by cgi_show_request().
4323 * Freeing the buffer itself isn't technically necessary,
4324 * but makes debugging more convenient.
4326 clear_iob(csp->client_iob);
4329 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4332 /*********************************************************************
4336 * Description : This is little more than chat. We only "serve" to
4337 * to close (or remember) any socket that chat may have
4341 * 1 : csp = Current client state (buffers, headers, etc...)
4345 *********************************************************************/
4346 static void serve(struct client_state *csp)
4348 int config_file_change_detected = 0; /* Only used for debugging */
4349 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4350 #ifdef FEATURE_CONNECTION_SHARING
4351 static int monitor_thread_running = 0;
4352 #endif /* def FEATURE_CONNECTION_SHARING */
4353 int continue_chatting = 0;
4355 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4356 csp->ip_addr_str, csp->cfd);
4360 unsigned int latency;
4362 #ifdef FEATURE_HTTPS_INSPECTION
4363 if (continue_chatting && client_use_ssl(csp))
4365 continue_https_chat(csp);
4374 * If the request has been crunched,
4375 * the calculated latency is zero.
4377 latency = (unsigned)(csp->server_connection.response_received -
4378 csp->server_connection.request_sent) / 2;
4380 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4381 && (csp->flags & CSP_FLAG_CRUNCHED)
4382 && (csp->expected_client_content_length != 0))
4384 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4385 log_error(LOG_LEVEL_CONNECT,
4386 "Tainting client socket %d due to unread data.", csp->cfd);
4389 continue_chatting = (csp->config->feature_flags
4390 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4391 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4392 && (csp->cfd != JB_INVALID_SOCKET)
4393 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4394 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4395 || (csp->flags & CSP_FLAG_CHUNKED));
4397 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4398 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4400 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4402 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4404 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4405 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4406 || !socket_is_still_alive(csp->server_connection.sfd)
4407 || !(latency < csp->server_connection.keep_alive_timeout))
4409 log_error(LOG_LEVEL_CONNECT,
4410 "Closing server socket %d connected to %s. "
4411 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4412 csp->server_connection.sfd, csp->server_connection.host,
4413 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4414 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4415 socket_is_still_alive(csp->server_connection.sfd),
4416 csp->server_connection.keep_alive_timeout);
4417 #ifdef FEATURE_CONNECTION_SHARING
4418 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4420 forget_connection(csp->server_connection.sfd);
4422 #endif /* def FEATURE_CONNECTION_SHARING */
4423 #ifdef FEATURE_HTTPS_INSPECTION
4424 close_server_ssl_connection(csp);
4426 close_socket(csp->server_connection.sfd);
4427 mark_connection_closed(&csp->server_connection);
4431 if (continue_chatting && any_loaded_file_changed(csp))
4433 continue_chatting = 0;
4434 config_file_change_detected = 1;
4436 #ifdef FEATURE_HTTPS_INSPECTION
4437 if (continue_chatting && client_use_ssl(csp) &&
4438 csp->ssl_with_client_is_opened == 0)
4440 continue_chatting = 0;
4441 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4442 "The TLS session has been terminated.", csp->cfd);
4446 if (continue_chatting)
4448 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4449 && socket_is_still_alive(csp->cfd))
4451 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4452 "pipelined on socket %d and the socket is still alive.",
4453 csp->requests_received_total+1, csp->cfd);
4454 prepare_csp_for_next_request(csp);
4458 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4460 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4462 log_error(LOG_LEVEL_CONNECT,
4463 "Waiting for the next client request on socket %d. "
4464 "Keeping the server socket %d to %s open.",
4465 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4469 log_error(LOG_LEVEL_CONNECT,
4470 "Waiting for the next client request on socket %d. "
4471 "No server socket to keep open.", csp->cfd);
4475 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4476 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4477 && socket_is_still_alive(csp->cfd))
4479 log_error(LOG_LEVEL_CONNECT,
4480 "Data arrived in time on client socket %d. Requests so far: %u",
4481 csp->cfd, csp->requests_received_total);
4482 prepare_csp_for_next_request(csp);
4486 #ifdef FEATURE_CONNECTION_SHARING
4487 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4488 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4489 && (socket_is_still_alive(csp->server_connection.sfd))
4490 #ifdef FEATURE_HTTPS_INSPECTION
4491 && !server_use_ssl(csp)
4495 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4497 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4502 remember_connection(&csp->server_connection);
4503 csp->server_connection.sfd = JB_INVALID_SOCKET;
4504 drain_and_close_socket(csp->cfd);
4505 csp->cfd = JB_INVALID_SOCKET;
4506 privoxy_mutex_lock(&connection_reuse_mutex);
4507 if (!monitor_thread_running)
4509 monitor_thread_running = 1;
4510 privoxy_mutex_unlock(&connection_reuse_mutex);
4511 wait_for_alive_connections();
4512 privoxy_mutex_lock(&connection_reuse_mutex);
4513 monitor_thread_running = 0;
4515 privoxy_mutex_unlock(&connection_reuse_mutex);
4517 #endif /* def FEATURE_CONNECTION_SHARING */
4521 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4523 log_error(LOG_LEVEL_CONNECT,
4524 "Closing server socket %d connected to %s. Keep-alive: %u. "
4525 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4526 "Configuration file change detected: %u",
4527 csp->server_connection.sfd, csp->server_connection.host,
4528 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4529 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4530 socket_is_still_alive(csp->server_connection.sfd),
4531 csp->server_connection.keep_alive_timeout,
4532 config_file_change_detected);
4534 } while (continue_chatting);
4538 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4540 if (csp->cfd != JB_INVALID_SOCKET)
4542 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4543 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4544 "Configuration file change detected: %u. Requests received: %u.",
4545 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4546 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4547 config_file_change_detected, csp->requests_received_total);
4548 #ifdef FEATURE_HTTPS_INSPECTION
4549 close_client_ssl_connection(csp);
4551 drain_and_close_socket(csp->cfd);
4554 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4556 #ifdef FEATURE_CONNECTION_SHARING
4557 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4559 forget_connection(csp->server_connection.sfd);
4561 #endif /* def FEATURE_CONNECTION_SHARING */
4563 #ifdef FEATURE_HTTPS_INSPECTION
4564 close_server_ssl_connection(csp);
4565 #endif /* def FEATURE_HTTPS_INSPECTION */
4567 close_socket(csp->server_connection.sfd);
4570 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4571 mark_connection_closed(&csp->server_connection);
4574 free_csp_resources(csp);
4576 csp->flags &= ~CSP_FLAG_ACTIVE;
4582 /*********************************************************************
4584 * Function : server_thread
4586 * Description : We only exist to call `serve' in a threaded environment.
4589 * 1 : data = Current client state (buffers, headers, etc...)
4591 * Returns : Always 0.
4593 *********************************************************************/
4594 static int32 server_thread(void *data)
4596 serve((struct client_state *) data);
4603 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4604 /*********************************************************************
4608 * Description : Print usage info & exit.
4610 * Parameters : Pointer to argv[0] for identifying ourselves
4614 *********************************************************************/
4615 static void usage(const char *name)
4617 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4618 "Usage: %s [--config-test] "
4621 #endif /* defined(unix) */
4624 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4625 #endif /* defined(unix) */
4626 "[--version] [configfile]\n",
4630 show_fuzz_usage(name);
4633 printf("Aborting\n");
4638 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4641 #ifdef MUTEX_LOCKS_AVAILABLE
4642 /*********************************************************************
4644 * Function : privoxy_mutex_lock
4646 * Description : Locks a mutex.
4649 * 1 : mutex = The mutex to lock.
4651 * Returns : Void. May exit in case of errors.
4653 *********************************************************************/
4654 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4656 #ifdef FEATURE_PTHREAD
4657 int err = pthread_mutex_lock(mutex);
4660 if (mutex != &log_mutex)
4662 log_error(LOG_LEVEL_FATAL,
4663 "Mutex locking failed: %s.\n", strerror(err));
4668 EnterCriticalSection(mutex);
4669 #endif /* def FEATURE_PTHREAD */
4673 /*********************************************************************
4675 * Function : privoxy_mutex_unlock
4677 * Description : Unlocks a mutex.
4680 * 1 : mutex = The mutex to unlock.
4682 * Returns : Void. May exit in case of errors.
4684 *********************************************************************/
4685 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4687 #ifdef FEATURE_PTHREAD
4688 int err = pthread_mutex_unlock(mutex);
4691 if (mutex != &log_mutex)
4693 log_error(LOG_LEVEL_FATAL,
4694 "Mutex unlocking failed: %s.\n", strerror(err));
4699 LeaveCriticalSection(mutex);
4700 #endif /* def FEATURE_PTHREAD */
4704 /*********************************************************************
4706 * Function : privoxy_mutex_init
4708 * Description : Prepares a mutex.
4711 * 1 : mutex = The mutex to initialize.
4713 * Returns : Void. May exit in case of errors.
4715 *********************************************************************/
4716 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4718 #ifdef FEATURE_PTHREAD
4719 int err = pthread_mutex_init(mutex, 0);
4722 printf("Fatal error. Mutex initialization failed: %s.\n",
4727 InitializeCriticalSection(mutex);
4728 #endif /* def FEATURE_PTHREAD */
4730 #endif /* def MUTEX_LOCKS_AVAILABLE */
4732 /*********************************************************************
4734 * Function : initialize_mutexes
4736 * Description : Prepares mutexes if mutex support is available.
4740 * Returns : Void, exits in case of errors.
4742 *********************************************************************/
4743 static void initialize_mutexes(void)
4745 #ifdef MUTEX_LOCKS_AVAILABLE
4747 * Prepare global mutex semaphores
4750 #ifdef FEATURE_HTTPS_INSPECTION
4751 privoxy_mutex_init(&certificate_mutex);
4752 privoxy_mutex_init(&ssl_init_mutex);
4755 privoxy_mutex_init(&log_mutex);
4756 privoxy_mutex_init(&log_init_mutex);
4757 privoxy_mutex_init(&connection_reuse_mutex);
4758 #ifdef FEATURE_EXTERNAL_FILTERS
4759 privoxy_mutex_init(&external_filter_mutex);
4761 #ifdef FEATURE_CLIENT_TAGS
4762 privoxy_mutex_init(&client_tags_mutex);
4764 #ifdef FEATURE_EXTENDED_STATISTICS
4765 privoxy_mutex_init(&filter_statistics_mutex);
4766 privoxy_mutex_init(&block_statistics_mutex);
4770 * XXX: The assumptions below are a bit naive
4771 * and can cause locks that aren't necessary.
4773 * For example older FreeBSD versions (< 6.x?)
4774 * have no gethostbyname_r, but gethostbyname is
4777 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4778 privoxy_mutex_init(&resolver_mutex);
4779 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4781 * XXX: should we use a single mutex for
4782 * localtime() and gmtime() as well?
4784 #ifndef HAVE_GMTIME_R
4785 privoxy_mutex_init(&gmtime_mutex);
4786 #endif /* ndef HAVE_GMTIME_R */
4788 #ifndef HAVE_LOCALTIME_R
4789 privoxy_mutex_init(&localtime_mutex);
4790 #endif /* ndef HAVE_GMTIME_R */
4792 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4793 privoxy_mutex_init(&rand_mutex);
4794 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4796 #endif /* def MUTEX_LOCKS_AVAILABLE */
4799 /*********************************************************************
4803 * Description : Load the config file and start the listen loop.
4804 * This function is a lot more *sane* with the `load_config'
4805 * and `listen_loop' functions; although it stills does
4806 * a *little* too much for my taste.
4809 * 1 : argc = Number of parameters (including $0).
4810 * 2 : argv = Array of (char *)'s to the parameters.
4812 * Returns : 1 if : can't open config file, unrecognized directive,
4813 * stats requested in multi-thread mode, can't open the
4814 * log file, can't open the jar file, listen port is invalid,
4815 * any load fails, and can't bind port.
4817 * Else main never returns, the process must be signaled
4818 * to terminate execution. Or, on Windows, use the
4819 * "File", "Exit" menu option.
4821 *********************************************************************/
4823 int real_main(int argc, char **argv)
4825 int main(int argc, char **argv)
4829 int do_config_test = 0;
4830 #ifndef HAVE_ARC4RANDOM
4831 unsigned int random_seed;
4834 struct passwd *pw = NULL;
4835 struct group *grp = NULL;
4837 char *pre_chroot_nslookup_to_load_resolver = NULL;
4840 char *fuzz_input_type = NULL;
4841 char *fuzz_input_file = NULL;
4848 #if !defined(_WIN32)
4855 /* Prepare mutexes if supported and necessary. */
4856 initialize_mutexes();
4858 /* Enable logging until further notice. */
4862 * Parse the command line arguments
4864 * XXX: simply printing usage information in case of
4865 * invalid arguments isn't particularly user friendly.
4867 while (++argc_pos < argc)
4870 /* Check to see if the service must be installed or uninstalled */
4871 if (strncmp(argv[argc_pos], "--install", 9) == 0)
4873 const char *pName = argv[argc_pos] + 9;
4876 exit((install_service(pName)) ? 0 : 1);
4878 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4880 const char *pName = argv[argc_pos] + 11;
4883 exit((uninstall_service(pName)) ? 0 : 1);
4885 else if (strcmp(argv[argc_pos], "--service") == 0)
4887 bRunAsService = TRUE;
4888 w32_set_service_cwd();
4889 atexit(w32_service_exit_notify);
4892 #endif /* defined(_WIN32) */
4895 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4897 if (strcmp(argv[argc_pos], "--help") == 0)
4902 else if (strcmp(argv[argc_pos], "--version") == 0)
4904 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4910 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4912 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4916 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4918 if (++argc_pos == argc) usage(argv[0]);
4919 pidfile = strdup_or_die(argv[argc_pos]);
4922 else if (strcmp(argv[argc_pos], "--user") == 0)
4927 if (++argc_pos == argc) usage(argv[argc_pos]);
4929 user_arg = strdup_or_die(argv[argc_pos]);
4930 group_name = strchr(user_arg, '.');
4931 if (NULL != group_name)
4933 /* Nul-terminate the user name */
4936 /* Skip the former delimiter to actually reach the group name */
4939 grp = getgrnam(group_name);
4942 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4945 pw = getpwnam(user_arg);
4948 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4954 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4956 if (++argc_pos == argc) usage(argv[0]);
4957 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4960 else if (strcmp(argv[argc_pos], "--chroot") == 0)
4964 #endif /* defined(unix) */
4966 else if (strcmp(argv[argc_pos], "--config-test") == 0)
4971 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4974 if (argc < argc_pos + 2) usage(argv[0]);
4975 fuzz_input_type = argv[argc_pos];
4977 fuzz_input_file = argv[argc_pos];
4979 else if (strcmp(argv[argc_pos], "--stfu") == 0)
4981 set_debug_level(LOG_LEVEL_STFU);
4984 else if (argc_pos + 1 != argc)
4987 * This is neither the last command line
4988 * option, nor was it recognized before,
4989 * therefore it must be invalid.
4995 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4997 configfile = argv[argc_pos];
5000 } /* -END- while (more arguments) */
5002 show_version(Argv[0]);
5005 if (*configfile != '/')
5007 char cwd[BUFFER_SIZE];
5009 size_t abs_file_size;
5011 /* make config-filename absolute here */
5012 if (NULL == getcwd(cwd, sizeof(cwd)))
5014 perror("failed to get current working directory");
5018 basedir = strdup_or_die(cwd);
5020 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5021 abs_file = malloc_or_die(abs_file_size);
5022 strlcpy(abs_file, basedir, abs_file_size);
5023 strlcat(abs_file, "/", abs_file_size);
5024 strlcat(abs_file, configfile, abs_file_size);
5025 configfile = abs_file;
5027 #endif /* defined unix */
5031 clients->next = NULL;
5033 /* XXX: factor out initialising after the next stable release. */
5038 #ifndef HAVE_ARC4RANDOM
5039 random_seed = (unsigned int)time(NULL);
5041 srandom(random_seed);
5044 #endif /* ifdef HAVE_RANDOM */
5045 #endif /* ifndef HAVE_ARC4RANDOM */
5048 * Unix signal handling
5050 * Catch the abort, interrupt and terminate signals for a graceful exit
5051 * Catch the hangup signal so the errlog can be reopened.
5053 * Ignore the broken pipe signal as connection failures
5054 * are handled when and where they occur without relying
5057 #if !defined(_WIN32)
5060 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5062 for (idx = 0; idx < SZ(catched_signals); idx++)
5064 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5065 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5067 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5068 #endif /* ifdef sun */
5070 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5074 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5076 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5080 #else /* ifdef _WIN32 */
5081 # ifdef _WIN_CONSOLE
5083 * We *are* in a windows console app.
5084 * Print a verbose messages about FAQ's and such
5086 printf("%s", win32_blurb);
5087 # endif /* def _WIN_CONSOLE */
5088 #endif /* def _WIN32 */
5091 if (fuzz_input_type != NULL)
5093 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5095 log_error(LOG_LEVEL_FATAL,
5096 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5097 "Various data structures are static which is unsafe when using threads.");
5102 exit(NULL == load_config());
5105 /* Initialize the CGI subsystem */
5106 cgi_init_error_messages();
5109 * If running on unix and without the --no-daemon
5110 * option, become a daemon. I.e. fork, detach
5111 * from tty and get process group leadership
5120 if (pid < 0) /* error */
5125 else if (pid != 0) /* parent */
5130 * must check for errors
5131 * child died due to missing files aso
5134 wpid = waitpid(pid, &status, WNOHANG);
5146 * stderr (fd 2) will be closed later on,
5147 * when the config file has been parsed.
5153 * Reserve fd 0 and 1 to prevent abort() and friends
5154 * from sending stuff to the clients or servers.
5156 fd = open("/dev/null", O_RDONLY);
5159 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5163 if (dup2(fd, 0) == -1)
5165 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5169 fd = open("/dev/null", O_WRONLY);
5172 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5176 if (dup2(fd, 1) == -1)
5178 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5183 #ifdef FEATURE_EXTERNAL_FILTERS
5184 for (fd = 0; fd < 3; fd++)
5186 mark_socket_for_close_on_execute(fd);
5192 } /* -END- if (daemon_mode) */
5195 * As soon as we have written the PID file, we can switch
5196 * to the user and group ID indicated by the --user option
5198 if (pidfile != NULL)
5200 write_pid_file(pidfile);
5204 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5206 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5210 if (setgroups(1, &grp->gr_gid))
5212 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5215 else if (initgroups(pw->pw_name, pw->pw_gid))
5217 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5223 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5225 /* Read the time zone file from /etc before doing chroot. */
5227 if (NULL != pre_chroot_nslookup_to_load_resolver
5228 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5230 /* Initialize resolver library. */
5231 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5233 if (chroot(pw->pw_dir) < 0)
5235 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5239 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5242 if (setuid(pw->pw_uid))
5244 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5248 char putenv_dummy[64];
5250 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5251 if (putenv(putenv_dummy) != 0)
5253 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5256 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5257 if (putenv(putenv_dummy) != 0)
5259 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5265 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5268 #endif /* defined unix */
5271 /* This will be FALSE unless the command line specified --service
5275 /* Yup, so now we must attempt to establish a connection
5276 * with the service dispatcher. This will only work if this
5277 * process was launched by the service control manager to
5278 * actually run as a service. If this isn't the case, i've
5279 * known it take around 30 seconds or so for the call to return.
5282 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5283 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5285 /* Service has run, and at this point is now being stopped, so just return */
5290 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5292 /* An error occurred. Usually it's because --service was wrongly specified
5293 * and we were unable to connect to the Service Control Dispatcher because
5294 * it wasn't expecting us and is therefore not listening.
5296 * For now, just continue below to call the listen_loop function.
5299 #endif /* def _WIN32 */
5309 /*********************************************************************
5311 * Function : bind_port_helper
5313 * Description : Bind the listen port. Handles logging, and aborts
5317 * 1 : haddr = Host address to bind to. Use NULL to bind to
5319 * 2 : hport = Specifies port to bind to.
5320 * 3 : backlog = Listen backlog.
5322 * Returns : Port that was opened.
5324 *********************************************************************/
5325 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5330 result = bind_port(haddr, hport, backlog, &bfd);
5334 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5338 log_error(LOG_LEVEL_FATAL,
5339 "can't bind to %s:%d: There may be another Privoxy "
5340 "or some other proxy running on port %d",
5341 bind_address, hport, hport);
5344 log_error(LOG_LEVEL_FATAL,
5345 "can't bind to %s:%d: The hostname is not resolvable",
5346 bind_address, hport);
5349 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5350 bind_address, hport);
5353 /* shouldn't get here */
5354 return JB_INVALID_SOCKET;
5359 if (bfd >= FD_SETSIZE)
5361 log_error(LOG_LEVEL_FATAL,
5362 "Bind socket number too high to use select(): %d >= %d",
5370 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5375 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5383 /*********************************************************************
5385 * Function : bind_ports_helper
5387 * Description : Bind the listen ports. Handles logging, and aborts
5391 * 1 : config = Privoxy configuration. Specifies ports
5393 * 2 : sockets = Preallocated array of opened sockets
5394 * corresponding to specification in config.
5395 * All non-opened sockets will be set to
5396 * JB_INVALID_SOCKET.
5398 * Returns : Nothing. Inspect sockets argument.
5400 *********************************************************************/
5401 static void bind_ports_helper(struct configuration_spec * config,
5402 jb_socket sockets[])
5406 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5408 if (config->hport[i])
5410 sockets[i] = bind_port_helper(config->haddr[i],
5411 config->hport[i], config->listen_backlog);
5412 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5413 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5415 struct accept_filter_arg af_options;
5416 bzero(&af_options, sizeof(af_options));
5417 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5418 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5419 sizeof(af_options)))
5421 log_error(LOG_LEVEL_ERROR,
5422 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5429 sockets[i] = JB_INVALID_SOCKET;
5432 config->need_bind = 0;
5436 /*********************************************************************
5438 * Function : close_ports_helper
5440 * Description : Close listenings ports.
5443 * 1 : sockets = Array of opened and non-opened sockets to
5444 * close. All sockets will be set to
5445 * JB_INVALID_SOCKET.
5447 * Returns : Nothing.
5449 *********************************************************************/
5450 static void close_ports_helper(jb_socket sockets[])
5454 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5456 if (JB_INVALID_SOCKET != sockets[i])
5458 close_socket(sockets[i]);
5460 sockets[i] = JB_INVALID_SOCKET;
5466 /* Without this simple workaround we get this compiler warning from _beginthread
5467 * warning C4028: formal parameter 1 different from declaration
5469 void w32_service_listen_loop(void *p)
5473 #endif /* def _WIN32 */
5476 /*********************************************************************
5478 * Function : listen_loop
5480 * Description : bind the listen port and enter a "FOREVER" listening loop.
5486 *********************************************************************/
5487 static void listen_loop(void)
5489 struct client_states *csp_list = NULL;
5490 struct client_state *csp = NULL;
5491 jb_socket bfds[MAX_LISTENING_SOCKETS];
5492 struct configuration_spec *config;
5493 unsigned int active_threads = 0;
5494 #if defined(FEATURE_PTHREAD)
5495 pthread_attr_t attrs;
5497 pthread_attr_init(&attrs);
5498 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5501 config = load_config();
5503 #ifdef FEATURE_CONNECTION_SHARING
5505 * XXX: Should be relocated once it no
5506 * longer needs to emit log messages.
5508 initialize_reusable_connections();
5509 #endif /* def FEATURE_CONNECTION_SHARING */
5511 bind_ports_helper(config, bfds);
5513 #ifdef FEATURE_GRACEFUL_TERMINATION
5514 while (!g_terminate)
5519 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
5520 while (waitpid(-1, NULL, WNOHANG) > 0)
5522 /* zombie children */
5524 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5527 * Free data that was used by died threads
5529 active_threads = sweep();
5533 * Re-open the errlog after HUP signal
5535 if (received_hup_signal)
5537 if (NULL != config->logfile)
5539 init_error_log(Argv[0], config->logfile);
5541 received_hup_signal = 0;
5545 csp_list = zalloc_or_die(sizeof(*csp_list));
5546 csp = &csp_list->csp;
5548 log_error(LOG_LEVEL_CONNECT,
5549 "Waiting for the next client connection. Currently active threads: %u",
5553 * This config may be outdated, but for accept_connection()
5554 * it's fresh enough.
5556 csp->config = config;
5558 if (!accept_connection(csp, bfds))
5560 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5565 csp->flags |= CSP_FLAG_ACTIVE;
5566 csp->server_connection.sfd = JB_INVALID_SOCKET;
5568 csp->config = config = load_config();
5570 if (config->need_bind)
5573 * Since we were listening to the "old port", we will not see
5574 * a "listen" param change until the next request. So, at
5575 * least 1 more request must be made for us to find the new
5576 * setting. I am simply closing the old socket and binding the
5579 * Which-ever is correct, we will serve 1 more page via the
5580 * old settings. This should probably be a "show-status"
5581 * request. This should not be a so common of an operation
5582 * that this will hurt people's feelings.
5585 close_ports_helper(bfds);
5587 bind_ports_helper(config, bfds);
5590 #ifdef FEATURE_TOGGLE
5591 if (global_toggle_state)
5592 #endif /* def FEATURE_TOGGLE */
5594 csp->flags |= CSP_FLAG_TOGGLED_ON;
5597 if (run_loader(csp))
5599 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5600 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5604 if (block_acl(NULL,csp))
5606 log_error(LOG_LEVEL_CONNECT,
5607 "Connection from %s on %s (socket %d) dropped due to ACL",
5608 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5609 close_socket(csp->cfd);
5610 freez(csp->ip_addr_str);
5611 freez(csp->listen_addr_str);
5615 #endif /* def FEATURE_ACL */
5617 if ((0 != config->max_client_connections)
5618 && (active_threads >= config->max_client_connections))
5620 log_error(LOG_LEVEL_CONNECT,
5621 "Rejecting connection from %s. Maximum number of connections reached.",
5623 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5624 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5625 close_socket(csp->cfd);
5626 freez(csp->ip_addr_str);
5627 freez(csp->listen_addr_str);
5632 /* add it to the list of clients */
5633 csp_list->next = clients->next;
5634 clients->next = csp_list;
5636 if (config->multi_threaded)
5640 /* this is a switch () statement in the C preprocessor - ugh */
5641 #undef SELECTED_ONE_OPTION
5643 /* Use Pthreads in preference to native code */
5644 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5645 #define SELECTED_ONE_OPTION
5647 pthread_t the_thread;
5650 ret = pthread_create(&the_thread, &attrs,
5651 (void * (*)(void *))serve, csp);
5652 child_id = ret ? -1 : 0;
5656 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5657 #define SELECTED_ONE_OPTION
5658 child_id = _beginthread(
5659 (void (*)(void *))serve,
5664 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5665 #define SELECTED_ONE_OPTION
5667 thread_id tid = spawn_thread
5668 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5670 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5672 child_id = (int) tid;
5681 #if !defined(SELECTED_ONE_OPTION)
5684 /* This block is only needed when using fork().
5685 * When using threads, the server thread was
5686 * created and run by the call to _beginthread().
5688 if (child_id == 0) /* child */
5691 #ifdef FEATURE_TOGGLE
5692 int inherited_toggle_state = global_toggle_state;
5693 #endif /* def FEATURE_TOGGLE */
5698 * If we've been toggled or we've blocked the request, tell Mom
5701 #ifdef FEATURE_TOGGLE
5702 if (inherited_toggle_state != global_toggle_state)
5704 rc |= RC_FLAG_TOGGLED;
5706 #endif /* def FEATURE_TOGGLE */
5708 #ifdef FEATURE_STATISTICS
5709 if (csp->flags & CSP_FLAG_REJECTED)
5711 rc |= RC_FLAG_BLOCKED;
5713 #endif /* ndef FEATURE_STATISTICS */
5717 else if (child_id > 0) /* parent */
5719 /* in a fork()'d environment, the parent's
5720 * copy of the client socket and the CSP
5724 #if !defined(_WIN32) && !defined(__CYGWIN__)
5726 wait(&child_status);
5729 * Evaluate child's return code: If the child has
5730 * - been toggled, toggle ourselves
5731 * - blocked its request, bump up the stats counter
5734 #ifdef FEATURE_TOGGLE
5735 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5737 global_toggle_state = !global_toggle_state;
5739 #endif /* def FEATURE_TOGGLE */
5741 #ifdef FEATURE_STATISTICS
5743 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5747 #endif /* def FEATURE_STATISTICS */
5749 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5750 close_socket(csp->cfd);
5751 csp->flags &= ~CSP_FLAG_ACTIVE;
5755 #undef SELECTED_ONE_OPTION
5756 /* end of cpp switch () */
5761 * Spawning the child failed, assume it's because
5762 * there are too many children running already.
5763 * XXX: If you assume ...
5765 log_error(LOG_LEVEL_ERROR,
5766 "Unable to take any additional connections: %E. Active threads: %u",
5768 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5769 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5770 close_socket(csp->cfd);
5771 csp->flags &= ~CSP_FLAG_ACTIVE;
5780 #if defined(FEATURE_PTHREAD)
5781 pthread_attr_destroy(&attrs);
5784 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5786 #ifdef FEATURE_HTTPS_INSPECTION
5787 /* Clean up. Aim: free all memory (no leaks) */
5791 #ifdef FEATURE_GRACEFUL_TERMINATION
5793 log_error(LOG_LEVEL_INFO, "Graceful termination requested");
5795 unload_current_config_file();
5796 unload_current_actions_file();
5797 unload_current_re_filterfile();
5798 #ifdef FEATURE_TRUST
5799 unload_current_trust_file();
5802 if (config->multi_threaded)
5809 } while ((clients->next != NULL) && (--i > 0));
5813 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5823 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5824 /* Cleanup - remove taskbar icon etc. */
5829 #endif /* FEATURE_GRACEFUL_TERMINATION */