1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
5 * Purpose : Main file. Contains main() method, main loop, and
6 * the main connection-handling function.
8 * Copyright : Written by and Copyright (C) 2001-2020 the
9 * Privoxy team. https://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
102 #endif /* def __GLIBC__ */
107 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
108 #endif /* HAVE_POLL */
115 #ifdef FEATURE_HTTPS_INSPECTION
121 #include "miscutil.h"
123 #include "jbsockets.h"
128 #include "urlmatch.h"
129 #ifdef FEATURE_CLIENT_TAGS
130 #include "client-tags.h"
134 struct client_states clients[1];
135 struct file_list files[1];
137 #ifdef FEATURE_STATISTICS
138 int urls_read = 0; /* total nr of urls read inc rejected */
139 int urls_rejected = 0; /* total nr of urls rejected */
140 #endif /* def FEATURE_STATISTICS */
142 #ifdef FEATURE_GRACEFUL_TERMINATION
146 #if !defined(_WIN32) && !defined(__OS2__)
147 static void sig_handler(int the_signal);
149 static int client_protocol_is_unsupported(struct client_state *csp, char *req);
150 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
151 static jb_err get_server_headers(struct client_state *csp);
152 static const char *crunch_reason(const struct http_response *rsp);
153 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
154 static char *get_request_line(struct client_state *csp);
155 static jb_err receive_client_request(struct client_state *csp);
156 static jb_err parse_client_request(struct client_state *csp);
157 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
158 static jb_err change_request_destination(struct client_state *csp);
159 static void handle_established_connection(struct client_state *csp);
160 static void chat(struct client_state *csp);
161 static void serve(struct client_state *csp);
162 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
163 static void usage(const char *myname);
165 static void initialize_mutexes(void);
166 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
167 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
168 static void close_ports_helper(jb_socket sockets[]);
169 static void listen_loop(void);
170 static void serve(struct client_state *csp);
173 static int32 server_thread(void *data);
174 #endif /* def __BEOS__ */
177 #define sleep(N) Sleep(((N) * 1000))
181 #define sleep(N) DosSleep(((N) * 100))
185 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
186 void show_fuzz_usage(const char *name);
189 #ifdef MUTEX_LOCKS_AVAILABLE
191 * XXX: Does the locking stuff really belong in this file?
193 privoxy_mutex_t log_mutex;
194 privoxy_mutex_t log_init_mutex;
195 privoxy_mutex_t connection_reuse_mutex;
197 #ifdef FEATURE_HTTPS_INSPECTION
198 privoxy_mutex_t certificate_mutex;
199 privoxy_mutex_t ssl_init_mutex;
202 #ifdef FEATURE_EXTERNAL_FILTERS
203 privoxy_mutex_t external_filter_mutex;
205 #ifdef FEATURE_CLIENT_TAGS
206 privoxy_mutex_t client_tags_mutex;
208 #ifdef FEATURE_EXTENDED_STATISTICS
209 privoxy_mutex_t filter_statistics_mutex;
210 privoxy_mutex_t block_statistics_mutex;
213 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
214 privoxy_mutex_t resolver_mutex;
215 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
217 #ifndef HAVE_GMTIME_R
218 privoxy_mutex_t gmtime_mutex;
219 #endif /* ndef HAVE_GMTIME_R */
221 #ifndef HAVE_LOCALTIME_R
222 privoxy_mutex_t localtime_mutex;
223 #endif /* ndef HAVE_GMTIME_R */
225 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
226 privoxy_mutex_t rand_mutex;
227 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
229 #endif /* def MUTEX_LOCKS_AVAILABLE */
232 const char *basedir = NULL;
233 const char *pidfile = NULL;
234 static int received_hup_signal = 0;
235 #endif /* defined unix */
237 /* HTTP snipplets. */
238 static const char CSUCCEED[] =
239 "HTTP/1.1 200 Connection established\r\n\r\n";
241 static const char CHEADER[] =
242 "HTTP/1.1 400 Invalid header received from client\r\n"
243 "Content-Type: text/plain\r\n"
244 "Connection: close\r\n\r\n"
245 "Invalid header received from client.\r\n";
247 static const char FTP_RESPONSE[] =
248 "HTTP/1.1 400 Invalid request received from client\r\n"
249 "Content-Type: text/plain\r\n"
250 "Connection: close\r\n\r\n"
251 "Invalid request. Privoxy doesn't support FTP.\r\n";
253 static const char GOPHER_RESPONSE[] =
254 "HTTP/1.1 400 Invalid request received from client\r\n"
255 "Content-Type: text/plain\r\n"
256 "Connection: close\r\n\r\n"
257 "Invalid request. Privoxy doesn't support gopher.\r\n";
259 /* XXX: should be a template */
260 static const char MISSING_DESTINATION_RESPONSE[] =
261 "HTTP/1.1 400 Bad request received from client\r\n"
262 "Content-Type: text/plain\r\n"
263 "Connection: close\r\n\r\n"
264 "Bad request. Privoxy was unable to extract the destination.\r\n";
266 /* XXX: should be a template */
267 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
268 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
269 "Content-Type: text/plain\r\n"
270 "Connection: close\r\n\r\n"
271 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
273 /* XXX: should be a template */
274 static const char MESSED_UP_REQUEST_RESPONSE[] =
275 "HTTP/1.1 400 Malformed request after rewriting\r\n"
276 "Content-Type: text/plain\r\n"
277 "Connection: close\r\n\r\n"
278 "Bad request. Messed up with header filters.\r\n";
280 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
281 "HTTP/1.1 503 Too many open connections\r\n"
282 "Content-Type: text/plain\r\n"
283 "Connection: close\r\n\r\n"
284 "Maximum number of open connections reached.\r\n";
286 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
287 "HTTP/1.1 504 Connection timeout\r\n"
288 "Content-Type: text/plain\r\n"
289 "Connection: close\r\n\r\n"
290 "The connection timed out because the client request didn't arrive in time.\r\n";
292 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
293 "HTTP/1.1 400 Failed reading client body\r\n"
294 "Content-Type: text/plain\r\n"
295 "Connection: close\r\n\r\n"
296 "Failed parsing or buffering the chunk-encoded client body.\r\n";
298 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
299 "HTTP/1.1 417 Expecting too much\r\n"
300 "Content-Type: text/plain\r\n"
301 "Connection: close\r\n\r\n"
302 "Privoxy detected an unsupported Expect header value.\r\n";
304 /* A function to crunch a response */
305 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
307 /* Crunch function flags */
308 #define CF_NO_FLAGS 0
309 /* Cruncher applies to forced requests as well */
310 #define CF_IGNORE_FORCE 1
311 /* Crunched requests are counted for the block statistics */
312 #define CF_COUNT_AS_REJECT 2
314 /* A crunch function and its flags */
317 const crunch_func_ptr cruncher;
321 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
323 /* Complete list of cruncher functions */
324 static const struct cruncher crunchers_all[] = {
325 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
326 { block_url, CF_COUNT_AS_REJECT },
328 { trust_url, CF_COUNT_AS_REJECT },
329 #endif /* def FEATURE_TRUST */
330 { redirect_url, CF_NO_FLAGS },
331 { dispatch_cgi, CF_IGNORE_FORCE},
335 /* Light version, used after tags are applied */
336 static const struct cruncher crunchers_light[] = {
337 { block_url, CF_COUNT_AS_REJECT },
338 { redirect_url, CF_NO_FLAGS },
344 * XXX: Don't we really mean
350 #if !defined(_WIN32) && !defined(__OS2__)
351 /*********************************************************************
353 * Function : sig_handler
355 * Description : Signal handler for different signals.
356 * Exit gracefully on TERM and INT
357 * or set a flag that will cause the errlog
358 * to be reopened by the main thread on HUP.
361 * 1 : the_signal = the signal cause this function to call
365 *********************************************************************/
366 static void sig_handler(int the_signal)
372 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
384 received_hup_signal = 1;
390 * We shouldn't be here, unless we catch signals
391 * in main() that we can't handle here!
393 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
401 /*********************************************************************
403 * Function : get_write_delay
405 * Description : Parse the delay-response parameter.
408 * 1 : csp = Current client state (buffers, headers, etc...)
410 * Returns : Number of milliseconds to delay writes.
412 *********************************************************************/
413 static unsigned int get_write_delay(const struct client_state *csp)
419 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
423 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
425 delay = (unsigned)strtol(newval, &endptr, 0);
428 log_error(LOG_LEVEL_FATAL,
429 "Invalid delay-response{} parameter: '%s'", newval);
437 /*********************************************************************
439 * Function : client_protocol_is_unsupported
441 * Description : Checks if the client used a known unsupported
442 * protocol and deals with it by sending an error
446 * 1 : csp = Current client state (buffers, headers, etc...)
447 * 2 : req = the first request line send by the client
449 * Returns : TRUE if an error response has been generated, or
450 * FALSE if the request doesn't look invalid.
452 *********************************************************************/
453 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
456 * If it's a FTP or gopher request, we don't support it.
458 * These checks are better than nothing, but they might
459 * not work in all configurations and some clients might
460 * have problems digesting the answer.
462 * They should, however, never cause more problems than
463 * Privoxy's old behaviour (returning the misleading HTML
466 * "Could not resolve http://(ftp|gopher)://example.org").
468 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
470 const char *response = NULL;
471 const char *protocol = NULL;
473 if (!strncmpic(req, "GET ftp://", 10))
475 response = FTP_RESPONSE;
480 response = GOPHER_RESPONSE;
483 log_error(LOG_LEVEL_ERROR,
484 "%s tried to use Privoxy as %s proxy: %s",
485 csp->ip_addr_str, protocol, req);
486 log_error(LOG_LEVEL_CLF,
487 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
490 #ifdef FEATURE_HTTPS_INSPECTION
491 if (client_use_ssl(csp))
493 ssl_send_data_delayed(&(csp->ssl_client_attr),
494 (const unsigned char *)response, strlen(response),
495 get_write_delay(csp));
500 write_socket_delayed(csp->cfd, response, strlen(response),
501 get_write_delay(csp));
511 /*********************************************************************
513 * Function : client_has_unsupported_expectations
515 * Description : Checks if the client used an unsupported expectation
516 * in which case an error message is delivered.
519 * 1 : csp = Current client state (buffers, headers, etc...)
521 * Returns : TRUE if an error response has been generated, or
522 * FALSE if the request doesn't look invalid.
524 *********************************************************************/
525 static int client_has_unsupported_expectations(const struct client_state *csp)
527 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
529 log_error(LOG_LEVEL_ERROR,
530 "Rejecting request from client %s with unsupported Expect header value",
532 log_error(LOG_LEVEL_CLF,
533 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
534 write_socket_delayed(csp->cfd,
535 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
536 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
537 get_write_delay(csp));
547 /*********************************************************************
549 * Function : get_request_destination_elsewhere
551 * Description : If the client's request was redirected into
552 * Privoxy without the client's knowledge,
553 * the request line lacks the destination host.
555 * This function tries to get it elsewhere,
556 * provided accept-intercepted-requests is enabled.
558 * "Elsewhere" currently only means "Host: header",
559 * but in the future we may ask the redirecting
560 * packet filter to look the destination up.
562 * If the destination stays unknown, an error
563 * response is send to the client and headers
564 * are freed so that chat() can return directly.
567 * 1 : csp = Current client state (buffers, headers, etc...)
568 * 2 : headers = a header list
570 * Returns : JB_ERR_OK if the destination is now known, or
571 * JB_ERR_PARSE if it isn't.
573 *********************************************************************/
574 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
578 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
580 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
581 " Privoxy isn't configured to accept intercepted requests.",
582 csp->ip_addr_str, csp->http->cmd);
583 /* XXX: Use correct size */
584 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
585 csp->ip_addr_str, csp->http->cmd);
587 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
588 get_write_delay(csp));
589 destroy_list(headers);
593 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
595 /* Split the domain we just got for pattern matching */
596 init_domain_components(csp->http);
602 /* We can't work without destination. Go spread the news.*/
604 req = list_to_text(headers);
606 /* XXX: Use correct size */
607 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
608 csp->ip_addr_str, csp->http->cmd);
609 log_error(LOG_LEVEL_ERROR,
610 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
611 csp->ip_addr_str, csp->http->cmd, req);
614 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
615 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
616 destroy_list(headers);
621 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
622 * to get the destination IP address, use it as host directly
623 * or do a reverse DNS lookup first.
628 /*********************************************************************
630 * Function : get_server_headers
632 * Description : Parses server headers in iob and fills them
633 * into csp->headers so that they can later be
637 * 1 : csp = Current client state (buffers, headers, etc...)
639 * Returns : JB_ERR_OK if everything went fine, or
640 * JB_ERR_PARSE if the headers were incomplete.
642 *********************************************************************/
643 static jb_err get_server_headers(struct client_state *csp)
645 int continue_hack_in_da_house = 0;
648 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
653 * continue hack in da house. Ignore the ending of
654 * this head and continue enlisting header lines.
655 * The reason is described below.
657 enlist(csp->headers, "");
658 continue_hack_in_da_house = 0;
661 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
664 * It's a bodyless continue response, don't
665 * stop header parsing after reaching its end.
667 * As a result Privoxy will concatenate the
668 * next response's head and parse and deliver
669 * the headers as if they belonged to one request.
671 * The client will separate them because of the
672 * empty line between them.
674 * XXX: What we're doing here is clearly against
675 * the intended purpose of the continue header,
676 * and under some conditions (HTTP/1.0 client request)
677 * it's a standard violation.
679 * Anyway, "sort of against the spec" is preferable
680 * to "always getting confused by Continue responses"
681 * (Privoxy's behaviour before this hack was added)
683 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
684 continue_hack_in_da_house = 1;
686 else if (*header == '\0')
689 * If the header is empty, but the Continue hack
690 * isn't active, we can assume that we reached the
691 * end of the buffer before we hit the end of the
694 * Inform the caller an let it decide how to handle it.
699 if (JB_ERR_MEMORY == enlist(csp->headers, header))
702 * XXX: Should we quit the request and return a
703 * out of memory error page instead?
705 log_error(LOG_LEVEL_ERROR,
706 "Out of memory while enlisting server headers. %s lost.",
716 /*********************************************************************
718 * Function : crunch_reason
720 * Description : Translates the crunch reason code into a string.
723 * 1 : rsp = a http_response
725 * Returns : A string with the crunch reason or an error description.
727 *********************************************************************/
728 static const char *crunch_reason(const struct http_response *rsp)
730 char * reason = NULL;
735 return "Internal error while searching for crunch reason";
738 switch (rsp->crunch_reason)
741 reason = "Unsupported HTTP feature";
747 reason = "Untrusted";
750 reason = "Redirected";
756 reason = "DNS failure";
758 case FORWARDING_FAILED:
759 reason = "Forwarding failed";
762 reason = "Connection failure";
765 reason = "Out of memory (may mask other reasons)";
767 case CONNECTION_TIMEOUT:
768 reason = "Connection timeout";
771 reason = "No server data received";
774 reason = "No reason recorded";
782 /*********************************************************************
784 * Function : log_applied_actions
786 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
790 * 1 : actions = Current action spec to log
794 *********************************************************************/
795 static void log_applied_actions(const struct current_action_spec *actions)
798 * The conversion to text requires lots of memory allocations so
799 * we only do the conversion if the user is actually interested.
801 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
803 char *actions_as_text = actions_to_line_of_text(actions);
804 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
805 freez(actions_as_text);
810 /*********************************************************************
812 * Function : send_crunch_response
814 * Description : Delivers already prepared response for
815 * intercepted requests, logs the interception
816 * and frees the response.
819 * 1 : csp = Current client state (buffers, headers, etc...)
820 * 2 : rsp = Fully prepared response. Will be freed on exit.
824 *********************************************************************/
825 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
827 const struct http_request *http = csp->http;
831 assert(rsp->head != NULL);
835 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
839 * Extract the status code from the actual head
840 * that will be send to the client. It is the only
841 * way to get it right for all requests, including
842 * the fixed ones for out-of-memory problems.
844 * A head starts like this: 'HTTP/1.1 200...'
848 status_code[0] = rsp->head[9];
849 status_code[1] = rsp->head[10];
850 status_code[2] = rsp->head[11];
851 status_code[3] = '\0';
853 /* Log that the request was crunched and why. */
854 log_applied_actions(csp->action);
855 #ifdef FEATURE_HTTPS_INSPECTION
856 if (client_use_ssl(csp))
858 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
859 http->hostport, http->path);
860 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %llu",
861 csp->ip_addr_str, http->gpc, http->hostport, http->path,
862 http->version, status_code, rsp->content_length);
867 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
868 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
869 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
871 /* Write the answer to the client */
872 #ifdef FEATURE_HTTPS_INSPECTION
873 if (client_use_ssl(csp))
875 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
876 (const unsigned char *)rsp->head, rsp->head_length,
877 get_write_delay(csp)) < 0)
878 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
879 (const unsigned char *)rsp->body, rsp->content_length,
880 get_write_delay(csp)) < 0))
882 /* There is nothing we can do about it. */
883 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
884 "for https://%s%s through client socket %d using TLS/SSL",
885 http->hostport, http->url, csp->cfd);
891 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
892 get_write_delay(csp))
893 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
894 get_write_delay(csp)))
896 /* There is nothing we can do about it. */
897 log_error(LOG_LEVEL_CONNECT,
898 "Couldn't deliver the error message for %s through client socket %d: %E",
899 http->url, csp->cfd);
903 /* Clean up and return */
904 if (cgi_error_memory() != rsp)
906 free_http_response(rsp);
912 /*********************************************************************
914 * Function : crunch_response_triggered
916 * Description : Checks if the request has to be crunched,
917 * and delivers the crunch response if necessary.
920 * 1 : csp = Current client state (buffers, headers, etc...)
921 * 2 : crunchers = list of cruncher functions to run
923 * Returns : TRUE if the request was answered with a crunch response
926 *********************************************************************/
927 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
929 struct http_response *rsp = NULL;
930 const struct cruncher *c;
933 * If CGI request crunching is disabled,
934 * check the CGI dispatcher out of order to
935 * prevent unintentional blocks or redirects.
937 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
938 && (NULL != (rsp = dispatch_cgi(csp))))
940 /* Deliver, log and free the interception response. */
941 send_crunch_response(csp, rsp);
942 csp->flags |= CSP_FLAG_CRUNCHED;
946 for (c = crunchers; c->cruncher != NULL; c++)
949 * Check the cruncher if either Privoxy is toggled
950 * on and the request isn't forced, or if the cruncher
951 * applies to forced requests as well.
953 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
954 !(csp->flags & CSP_FLAG_FORCED)) ||
955 (c->flags & CF_IGNORE_FORCE))
957 rsp = c->cruncher(csp);
960 /* Deliver, log and free the interception response. */
961 send_crunch_response(csp, rsp);
962 csp->flags |= CSP_FLAG_CRUNCHED;
963 #ifdef FEATURE_STATISTICS
964 if (c->flags & CF_COUNT_AS_REJECT)
966 csp->flags |= CSP_FLAG_REJECTED;
968 #endif /* def FEATURE_STATISTICS */
979 /*********************************************************************
981 * Function : build_request_line
983 * Description : Builds the HTTP request line.
985 * If a HTTP forwarder is used it expects the whole URL,
986 * web servers only get the path.
989 * 1 : csp = Current client state (buffers, headers, etc...)
990 * 2 : fwd = The forwarding spec used for the request
991 * XXX: Should use http->fwd instead.
992 * 3 : request_line = The old request line which will be replaced.
994 * Returns : Nothing. Terminates in case of memory problems.
996 *********************************************************************/
997 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
999 struct http_request *http = csp->http;
1002 * Downgrade http version from 1.1 to 1.0
1003 * if +downgrade action applies.
1005 if ((csp->action->flags & ACTION_DOWNGRADE)
1006 && (!strcmpic(http->version, "HTTP/1.1")))
1008 freez(http->version);
1009 http->version = strdup_or_die("HTTP/1.0");
1013 * Rebuild the request line.
1015 freez(*request_line);
1016 *request_line = strdup(http->gpc);
1017 string_append(request_line, " ");
1019 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1021 string_append(request_line, http->url);
1025 string_append(request_line, http->path);
1027 string_append(request_line, " ");
1028 string_append(request_line, http->version);
1030 if (*request_line == NULL)
1032 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1034 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1038 /*********************************************************************
1040 * Function : change_request_destination
1042 * Description : Parse a (rewritten) request line and regenerate
1043 * the http request data.
1046 * 1 : csp = Current client state (buffers, headers, etc...)
1048 * Returns : Forwards the parse_http_request() return code.
1049 * Terminates in case of memory problems.
1051 *********************************************************************/
1052 static jb_err change_request_destination(struct client_state *csp)
1054 struct http_request *http = csp->http;
1057 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1058 csp->headers->first->str);
1059 free_http_request(http);
1060 err = parse_http_request(csp->headers->first->str, http);
1061 if (JB_ERR_OK != err)
1063 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1064 jb_err_to_string(err));
1071 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1072 /*********************************************************************
1074 * Function : server_response_is_complete
1076 * Description : Determines whether we should stop reading
1077 * from the server socket.
1080 * 1 : csp = Current client state (buffers, headers, etc...)
1081 * 2 : content_length = Length of content received so far.
1083 * Returns : TRUE if the response is complete,
1086 *********************************************************************/
1087 static int server_response_is_complete(struct client_state *csp,
1088 unsigned long long content_length)
1090 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1092 if (!strcmpic(csp->http->gpc, "HEAD"))
1095 * "HEAD" implies no body, we are thus expecting
1096 * no content. XXX: incomplete "list" of methods?
1098 csp->expected_content_length = 0;
1099 content_length_known = TRUE;
1100 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1103 if (csp->http->status == 204 || csp->http->status == 304)
1106 * Expect no body. XXX: incomplete "list" of status codes?
1108 csp->expected_content_length = 0;
1109 content_length_known = TRUE;
1110 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1113 return (content_length_known && ((0 == csp->expected_content_length)
1114 || (csp->expected_content_length <= content_length)));
1118 #ifdef FEATURE_CONNECTION_SHARING
1119 /*********************************************************************
1121 * Function : wait_for_alive_connections
1123 * Description : Waits for alive connections to timeout.
1129 *********************************************************************/
1130 static void wait_for_alive_connections(void)
1132 int connections_alive = close_unusable_connections();
1134 while (0 < connections_alive)
1136 log_error(LOG_LEVEL_CONNECT,
1137 "Waiting for %d connections to timeout.",
1140 connections_alive = close_unusable_connections();
1143 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1146 #endif /* def FEATURE_CONNECTION_SHARING */
1149 /*********************************************************************
1151 * Function : save_connection_destination
1153 * Description : Remembers a connection for reuse later on.
1156 * 1 : sfd = Open socket to remember.
1157 * 2 : http = The destination for the connection.
1158 * 3 : fwd = The forwarder settings used.
1159 * 4 : server_connection = storage.
1163 *********************************************************************/
1164 void save_connection_destination(jb_socket sfd,
1165 const struct http_request *http,
1166 const struct forward_spec *fwd,
1167 struct reusable_connection *server_connection)
1169 assert(sfd != JB_INVALID_SOCKET);
1170 assert(NULL != http->host);
1172 server_connection->sfd = sfd;
1173 server_connection->host = strdup_or_die(http->host);
1174 server_connection->port = http->port;
1176 assert(NULL != fwd);
1177 assert(server_connection->gateway_host == NULL);
1178 assert(server_connection->gateway_port == 0);
1179 assert(server_connection->forwarder_type == 0);
1180 assert(server_connection->forward_host == NULL);
1181 assert(server_connection->forward_port == 0);
1183 server_connection->forwarder_type = fwd->type;
1184 if (NULL != fwd->gateway_host)
1186 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1190 server_connection->gateway_host = NULL;
1192 server_connection->gateway_port = fwd->gateway_port;
1194 if (NULL != fwd->forward_host)
1196 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1200 server_connection->forward_host = NULL;
1202 server_connection->forward_port = fwd->forward_port;
1204 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1207 /*********************************************************************
1209 * Function : verify_request_length
1211 * Description : Checks if we already got the whole client requests
1212 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1215 * Data that doesn't belong to the current request is
1216 * either thrown away to let the client retry on a clean
1217 * socket, or stashed to be dealt with after the current
1218 * request is served.
1221 * 1 : csp = Current client state (buffers, headers, etc...)
1225 *********************************************************************/
1226 static void verify_request_length(struct client_state *csp)
1228 unsigned long long buffered_request_bytes =
1229 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1231 if ((csp->expected_client_content_length != 0)
1232 && (buffered_request_bytes != 0))
1234 if (csp->expected_client_content_length >= buffered_request_bytes)
1236 csp->expected_client_content_length -= buffered_request_bytes;
1237 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1238 "to account for the %llu ones we already got.",
1239 csp->expected_client_content_length, buffered_request_bytes);
1243 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1244 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1245 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1246 "Marking the server socket tainted after throwing %llu bytes away.",
1247 buffered_request_bytes - csp->expected_client_content_length);
1248 csp->expected_client_content_length = 0;
1249 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1252 if (csp->expected_client_content_length == 0)
1254 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1258 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1259 && ((csp->client_iob->cur < csp->client_iob->eod)
1260 || (csp->expected_client_content_length != 0)))
1262 if (strcmpic(csp->http->gpc, "GET")
1263 && strcmpic(csp->http->gpc, "HEAD")
1264 && strcmpic(csp->http->gpc, "TRACE")
1265 && strcmpic(csp->http->gpc, "OPTIONS")
1266 && strcmpic(csp->http->gpc, "DELETE"))
1268 /* XXX: this is an incomplete hack */
1269 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1270 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1274 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1276 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1278 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1279 log_error(LOG_LEVEL_CONNECT,
1280 "Possible pipeline attempt detected. The connection will not "
1281 "be kept alive and we will only serve the first request.");
1282 /* Nuke the pipelined requests from orbit, just to be sure. */
1283 clear_iob(csp->client_iob);
1288 * Keep the pipelined data around for now, we'll deal with
1289 * it once we're done serving the current request.
1291 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1292 assert(csp->client_iob->eod >= csp->client_iob->cur);
1293 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1294 "%d bytes of pipelined data received.",
1295 (int)(csp->client_iob->eod - csp->client_iob->cur));
1301 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1302 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1307 /*********************************************************************
1309 * Function : mark_server_socket_tainted
1311 * Description : Makes sure we don't reuse a server socket
1312 * (if we didn't read everything the server sent
1313 * us reusing the socket would lead to garbage).
1316 * 1 : csp = Current client state (buffers, headers, etc...)
1320 *********************************************************************/
1321 static void mark_server_socket_tainted(struct client_state *csp)
1324 * For consistency we always mark the server socket
1325 * tainted, however, to reduce the log noise we only
1326 * emit a log message if the server socket could have
1327 * actually been reused.
1329 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1330 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1332 log_error(LOG_LEVEL_CONNECT,
1333 "Marking the server socket %d tainted.",
1334 csp->server_connection.sfd);
1336 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1339 /*********************************************************************
1341 * Function : get_request_line
1343 * Description : Read the client request line.
1346 * 1 : csp = Current client state (buffers, headers, etc...)
1348 * Returns : Pointer to request line or NULL in case of errors.
1350 *********************************************************************/
1351 static char *get_request_line(struct client_state *csp)
1353 char buf[BUFFER_SIZE];
1354 char *request_line = NULL;
1357 memset(buf, 0, sizeof(buf));
1359 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1362 * If there are multiple pipelined requests waiting,
1363 * the flag will be set again once the next request
1366 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1368 request_line = get_header(csp->client_iob);
1369 if ((NULL != request_line) && ('\0' != *request_line))
1371 return request_line;
1375 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1376 "received yet. Continuing reading from %d.", csp->cfd);
1384 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1386 !data_is_available(csp->cfd, csp->config->socket_timeout)
1389 if (socket_is_still_alive(csp->cfd))
1391 log_error(LOG_LEVEL_CONNECT,
1392 "No request line on socket %d received in time. Timeout: %d.",
1393 csp->cfd, csp->config->socket_timeout);
1394 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1395 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1396 get_write_delay(csp));
1400 log_error(LOG_LEVEL_CONNECT,
1401 "The client side of the connection on socket %d got "
1402 "closed without sending a complete request line.", csp->cfd);
1407 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1409 if (len <= 0) return NULL;
1412 * If there is no memory left for buffering the
1413 * request, there is nothing we can do but hang up
1415 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1420 request_line = get_header(csp->client_iob);
1422 } while ((NULL != request_line) && ('\0' == *request_line));
1424 return request_line;
1430 CHUNK_STATUS_MISSING_DATA,
1431 CHUNK_STATUS_BODY_COMPLETE,
1432 CHUNK_STATUS_PARSE_ERROR
1436 /*********************************************************************
1438 * Function : chunked_body_is_complete
1440 * Description : Figures out whether or not a chunked body is complete.
1442 * Currently it always starts at the beginning of the
1443 * buffer which is somewhat wasteful and prevents Privoxy
1444 * from starting to forward the correctly parsed chunks
1445 * as soon as theoretically possible.
1447 * Should be modified to work with a common buffer,
1448 * and allow the caller to skip already parsed chunks.
1450 * This would allow the function to be used for unbuffered
1451 * response bodies as well.
1454 * 1 : iob = Buffer with the body to check.
1455 * 2 : length = Length of complete body
1457 * Returns : Enum with the result of the check.
1459 *********************************************************************/
1460 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1462 unsigned int chunksize;
1468 * We need at least a single digit, followed by "\r\n",
1469 * followed by an unknown amount of data, followed by "\r\n".
1471 if (p + 5 > iob->eod)
1473 return CHUNK_STATUS_MISSING_DATA;
1475 if (sscanf(p, "%x", &chunksize) != 1)
1477 return CHUNK_STATUS_PARSE_ERROR;
1481 * We want at least a single digit, followed by "\r\n",
1482 * followed by the specified amount of data, followed by "\r\n".
1484 if (p + chunksize + 5 > iob->eod)
1486 return CHUNK_STATUS_MISSING_DATA;
1489 /* Skip chunk-size. */
1490 p = strstr(p, "\r\n");
1493 return CHUNK_STATUS_PARSE_ERROR;
1495 /* Move beyond the chunkdata. */
1498 /* There should be another "\r\n" to skip */
1499 if (memcmp(p, "\r\n", 2))
1501 return CHUNK_STATUS_PARSE_ERROR;
1504 } while (chunksize > 0U);
1506 *length = (size_t)(p - iob->cur);
1507 assert(*length <= (size_t)(iob->eod - iob->cur));
1508 assert(p <= iob->eod);
1510 return CHUNK_STATUS_BODY_COMPLETE;
1515 /*********************************************************************
1517 * Function : receive_chunked_client_request_body
1519 * Description : Read the chunk-encoded client request body.
1520 * Failures are dealt with.
1523 * 1 : csp = Current client state (buffers, headers, etc...)
1525 * Returns : JB_ERR_OK or JB_ERR_PARSE
1527 *********************************************************************/
1528 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1531 enum chunk_status status;
1533 while (CHUNK_STATUS_MISSING_DATA ==
1534 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1536 char buf[BUFFER_SIZE];
1539 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1541 log_error(LOG_LEVEL_ERROR,
1542 "Timeout while waiting for the client body.");
1545 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1548 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1551 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1556 if (status != CHUNK_STATUS_BODY_COMPLETE)
1558 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1559 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1560 log_error(LOG_LEVEL_CLF,
1561 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1562 return JB_ERR_PARSE;
1564 log_error(LOG_LEVEL_CONNECT,
1565 "Chunked client body completely read. Length: %d", body_length);
1566 csp->expected_client_content_length = body_length;
1574 /*********************************************************************
1576 * Function : fuzz_chunked_transfer_encoding
1578 * Description : Treat the fuzzed input as chunked transfer encoding
1579 * to check and dechunk.
1582 * 1 : csp = Used to store the data.
1583 * 2 : fuzz_input_file = File to read the input from.
1585 * Returns : Result of dechunking
1587 *********************************************************************/
1588 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1591 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1592 enum chunk_status status;
1594 status = chunked_body_is_complete(csp->iob, &length);
1595 if (CHUNK_STATUS_BODY_COMPLETE != status)
1597 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1600 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1605 /*********************************************************************
1607 * Function : fuzz_client_request
1609 * Description : Try to get a client request from the fuzzed input.
1612 * 1 : csp = Current client state (buffers, headers, etc...)
1613 * 2 : fuzz_input_file = File to read the input from.
1615 * Returns : Result of fuzzing.
1617 *********************************************************************/
1618 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1623 csp->ip_addr_str = "fuzzer";
1625 if (strcmp(fuzz_input_file, "-") != 0)
1627 log_error(LOG_LEVEL_FATAL,
1628 "Fuzzed client requests can currently only be read from stdin (-).");
1630 err = receive_client_request(csp);
1631 if (err != JB_ERR_OK)
1635 err = parse_client_request(csp);
1636 if (err != JB_ERR_OK)
1644 #endif /* def FUZZ */
1647 #ifdef FEATURE_FORCE_LOAD
1648 /*********************************************************************
1650 * Function : force_required
1652 * Description : Checks a request line to see if it contains
1653 * the FORCE_PREFIX. If it does, it is removed
1654 * unless enforcing requests has beend disabled.
1657 * 1 : request_line = HTTP request line
1659 * Returns : TRUE if force is required, FALSE otherwise.
1661 *********************************************************************/
1662 static int force_required(const struct client_state *csp, char *request_line)
1666 p = strstr(request_line, "http://");
1670 p += strlen("http://");
1674 /* Intercepted request usually don't specify the protocol. */
1678 /* Go to the beginning of the path */
1683 * If the path is missing the request line is invalid and we
1684 * are done here. The client-visible rejection happens later on.
1689 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1691 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1693 /* XXX: Should clean more carefully */
1694 strclean(request_line, FORCE_PREFIX);
1695 log_error(LOG_LEVEL_FORCE,
1696 "Enforcing request: \"%s\".", request_line);
1700 log_error(LOG_LEVEL_FORCE,
1701 "Ignored force prefix in request: \"%s\".", request_line);
1707 #endif /* def FEATURE_FORCE_LOAD */
1710 /*********************************************************************
1712 * Function : receive_client_request
1714 * Description : Read the client's request (more precisely the
1715 * client headers) and answer it if necessary.
1718 * 1 : csp = Current client state (buffers, headers, etc...)
1720 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1722 *********************************************************************/
1723 static jb_err receive_client_request(struct client_state *csp)
1725 char buf[BUFFER_SIZE];
1728 struct http_request *http;
1732 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1733 struct list header_list;
1734 struct list *headers = &header_list;
1736 /* We don't care if the arriving data is a valid HTTP request or not. */
1737 csp->requests_received_total++;
1741 memset(buf, 0, sizeof(buf));
1743 req = get_request_line(csp);
1746 mark_server_socket_tainted(csp);
1747 return JB_ERR_PARSE;
1749 assert(*req != '\0');
1751 if (client_protocol_is_unsupported(csp, req))
1753 return JB_ERR_PARSE;
1756 #ifdef FEATURE_FORCE_LOAD
1757 if (force_required(csp, req))
1759 csp->flags |= CSP_FLAG_FORCED;
1761 #endif /* def FEATURE_FORCE_LOAD */
1763 err = parse_http_request(req, http);
1765 if (JB_ERR_OK != err)
1767 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1768 get_write_delay(csp));
1769 /* XXX: Use correct size */
1770 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1771 log_error(LOG_LEVEL_ERROR,
1772 "Couldn't parse request line received from %s: %s",
1773 csp->ip_addr_str, jb_err_to_string(err));
1775 free_http_request(http);
1776 return JB_ERR_PARSE;
1779 /* grab the rest of the client's headers */
1783 p = get_header(csp->client_iob);
1787 /* There are no additional headers to read. */
1794 * We didn't receive a complete header
1795 * line yet, get the rest of it.
1797 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1799 log_error(LOG_LEVEL_ERROR,
1800 "Stopped grabbing the client headers.");
1801 destroy_list(headers);
1802 return JB_ERR_PARSE;
1805 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1808 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1809 destroy_list(headers);
1810 return JB_ERR_PARSE;
1813 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1816 * If there is no memory left for buffering the
1817 * request, there is nothing we can do but hang up
1819 destroy_list(headers);
1820 return JB_ERR_MEMORY;
1825 if (!strncmpic(p, "Transfer-Encoding:", 18))
1828 * XXX: should be called through sed()
1829 * but currently can't.
1831 client_transfer_encoding(csp, &p);
1834 * We were able to read a complete
1835 * header and can finally enlist it.
1842 if (http->host == NULL)
1845 * If we still don't know the request destination,
1846 * the request is invalid or the client uses
1847 * Privoxy without its knowledge.
1849 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1852 * Our attempts to get the request destination
1853 * elsewhere failed or Privoxy is configured
1854 * to only accept proxy requests.
1856 * An error response has already been send
1857 * and we're done here.
1859 return JB_ERR_PARSE;
1863 #ifdef FEATURE_CLIENT_TAGS
1864 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1865 set_client_address(csp, headers);
1866 get_tag_list_for_client(csp->client_tags, csp->client_address);
1870 * Determine the actions for this URL
1872 #ifdef FEATURE_TOGGLE
1873 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1875 /* Most compatible set of actions (i.e. none) */
1876 init_current_action(csp->action);
1879 #endif /* ndef FEATURE_TOGGLE */
1881 get_url_actions(csp, http);
1884 enlist(csp->headers, http->cmd);
1886 /* Append the previously read headers */
1887 err = list_append_list_unique(csp->headers, headers);
1888 destroy_list(headers);
1895 /*********************************************************************
1897 * Function : parse_client_request
1899 * Description : Parses the client's request and decides what to do
1902 * Note that since we're not using select() we could get
1903 * blocked here if a client connected, then didn't say
1907 * 1 : csp = Current client state (buffers, headers, etc...)
1909 * Returns : JB_ERR_OK or JB_ERR_PARSE
1911 *********************************************************************/
1912 static jb_err parse_client_request(struct client_state *csp)
1914 struct http_request *http = csp->http;
1917 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1918 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1919 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1920 && (csp->http->ssl == 0))
1922 /* Assume persistence until further notice */
1923 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1925 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1927 if (csp->http->ssl == 0)
1930 * This whole block belongs to chat() but currently
1931 * has to be executed before sed().
1933 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1935 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1937 return JB_ERR_PARSE;
1942 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1944 verify_request_length(csp);
1946 #ifndef FEATURE_HTTPS_INSPECTION
1949 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1953 err = sed(csp, FILTER_CLIENT_HEADERS);
1954 if (JB_ERR_OK != err)
1956 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1958 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1959 csp->ip_addr_str, csp->http->cmd);
1960 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1961 return JB_ERR_PARSE;
1963 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1965 /* Check request line for rewrites. */
1966 if ((NULL == csp->headers->first->str)
1967 || (strcmp(http->cmd, csp->headers->first->str) &&
1968 (JB_ERR_OK != change_request_destination(csp))))
1971 * A header filter broke the request line - bail out.
1973 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1974 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1975 /* XXX: Use correct size */
1976 log_error(LOG_LEVEL_CLF,
1977 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1978 log_error(LOG_LEVEL_ERROR,
1979 "Invalid request line after applying header filters.");
1980 free_http_request(http);
1982 return JB_ERR_PARSE;
1985 if (client_has_unsupported_expectations(csp))
1987 return JB_ERR_PARSE;
1995 /*********************************************************************
1997 * Function : send_http_request
1999 * Description : Sends the HTTP headers from the client request
2000 * and all the body data that has already been received.
2003 * 1 : csp = Current client state (buffers, headers, etc...)
2005 * Returns : 0 on success, anything else is an error.
2007 *********************************************************************/
2008 static int send_http_request(struct client_state *csp)
2013 hdr = list_to_text(csp->headers);
2016 /* FIXME Should handle error properly */
2017 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2019 list_remove_all(csp->headers);
2022 * Write the client's (modified) header to the server
2023 * (along with anything else that may be in the buffer)
2025 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2030 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2031 csp->http->hostport);
2033 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2034 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2037 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2038 csp->http->hostport);
2041 return write_failure;
2046 #ifdef FEATURE_HTTPS_INSPECTION
2047 /*********************************************************************
2049 * Function : receive_and_send_encrypted_post_data
2051 * Description : Reads remaining POST data from the client and sends
2055 * 1 : csp = Current client state (buffers, headers, etc...)
2057 * Returns : 0 on success, anything else is an error.
2059 *********************************************************************/
2060 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2062 int content_length_known = csp->expected_client_content_length != 0;
2064 while (is_ssl_pending(&(csp->ssl_client_attr))
2065 || (content_length_known && csp->expected_client_content_length != 0))
2067 unsigned char buf[BUFFER_SIZE];
2069 int max_bytes_to_read = sizeof(buf);
2071 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2073 max_bytes_to_read = (int)csp->expected_client_content_length;
2075 log_error(LOG_LEVEL_CONNECT,
2076 "Waiting for up to %d bytes of POST data from the client.",
2078 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2079 (unsigned)max_bytes_to_read);
2086 /* XXX: Does this actually happen? */
2089 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted POST data",
2091 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2096 if (csp->expected_client_content_length != 0)
2098 if (csp->expected_client_content_length >= len)
2100 csp->expected_client_content_length -= (unsigned)len;
2102 if (csp->expected_client_content_length == 0)
2104 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2110 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted POST data");
2117 /*********************************************************************
2119 * Function : send_https_request
2121 * Description : Sends the HTTP headers from the client request
2122 * and all the body data that has already been received.
2125 * 1 : csp = Current client state (buffers, headers, etc...)
2127 * Returns : 0 on success, anything else is an error.
2129 *********************************************************************/
2130 static int send_https_request(struct client_state *csp)
2136 hdr = list_to_text(csp->https_headers);
2139 /* FIXME Should handle error properly */
2140 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2142 list_remove_all(csp->https_headers);
2145 * Write the client's (modified) header to the server
2146 * (along with anything else that may be in the buffer)
2148 ret = ssl_send_data(&(csp->ssl_server_attr),
2149 (const unsigned char *)hdr, strlen(hdr));
2154 log_error(LOG_LEVEL_CONNECT,
2155 "Failed sending encrypted request headers to: %s: %E",
2156 csp->http->hostport);
2157 mark_server_socket_tainted(csp);
2161 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2162 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2163 csp->client_iob)) < 0))
2165 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2166 csp->http->hostport);
2171 if (csp->expected_client_content_length != 0)
2173 if (csp->expected_client_content_length < flushed)
2175 log_error(LOG_LEVEL_ERROR,
2176 "Flushed %d bytes of request body while only expecting %llu",
2177 flushed, csp->expected_client_content_length);
2178 csp->expected_client_content_length = 0;
2182 log_error(LOG_LEVEL_CONNECT,
2183 "Flushed %d bytes of request body while expecting %llu",
2184 flushed, csp->expected_client_content_length);
2185 csp->expected_client_content_length -= (unsigned)flushed;
2186 if (receive_and_send_encrypted_post_data(csp))
2194 log_error(LOG_LEVEL_CONNECT,
2195 "Flushed %d bytes of request body", flushed);
2199 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2206 /*********************************************************************
2208 * Function : receive_encrypted_request
2210 * Description : Receives an encrypted request.
2213 * 1 : csp = Current client state (buffers, headers, etc...)
2215 * Returns : JB_ERR_OK on success,
2216 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2218 *********************************************************************/
2219 static jb_err receive_encrypted_request(struct client_state *csp)
2221 char buf[BUFFER_SIZE];
2227 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2228 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2229 !data_is_available(csp->cfd, csp->config->socket_timeout))
2231 log_error(LOG_LEVEL_CONNECT,
2232 "Socket %d timed out while waiting for client headers", csp->cfd);
2233 return JB_ERR_PARSE;
2235 len = ssl_recv_data(&(csp->ssl_client_attr),
2236 (unsigned char *)buf, sizeof(buf));
2239 log_error(LOG_LEVEL_CONNECT,
2240 "Socket %d closed while waiting for client headers", csp->cfd);
2241 return JB_ERR_PARSE;
2245 return JB_ERR_PARSE;
2247 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2249 return JB_ERR_MEMORY;
2251 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2252 } while (p == NULL);
2254 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2260 /*********************************************************************
2262 * Function : process_encrypted_request
2264 * Description : Receives and parses an encrypted request.
2267 * 1 : csp = Current client state (buffers, headers, etc...)
2269 * Returns : JB_ERR_OK on success,
2270 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2272 *********************************************************************/
2273 static jb_err process_encrypted_request(struct client_state *csp)
2278 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2279 struct list header_list;
2280 struct list *headers = &header_list;
2282 assert(csp->ssl_with_client_is_opened);
2284 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2285 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2287 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2290 err = receive_encrypted_request(csp);
2291 if (err != JB_ERR_OK)
2293 if (csp->client_iob->cur == NULL)
2296 * We did not receive any data, most likely because the
2297 * client is done. Don't log this as a parse failure.
2299 return JB_ERR_PARSE;
2301 /* XXX: Also used for JB_ERR_MEMORY */
2302 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2303 jb_err_to_string(err));
2304 ssl_send_data_delayed(&(csp->ssl_client_attr),
2305 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2309 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2310 request_line = get_header(csp->client_iob);
2311 if (request_line == NULL)
2313 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2314 ssl_send_data_delayed(&(csp->ssl_client_attr),
2315 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2316 return JB_ERR_PARSE;
2318 assert(*request_line != '\0');
2320 if (client_protocol_is_unsupported(csp, request_line))
2323 * If the protocol is unsupported we're done here.
2324 * client_protocol_is_unsupported() took care of sending
2325 * the error response and logging the error message.
2327 return JB_ERR_PARSE;
2330 #ifdef FEATURE_FORCE_LOAD
2331 if (force_required(csp, request_line))
2333 csp->flags |= CSP_FLAG_FORCED;
2335 #endif /* def FEATURE_FORCE_LOAD */
2337 free_http_request(csp->http);
2339 err = parse_http_request(request_line, csp->http);
2340 /* XXX: Restore ssl setting. This is ugly */
2341 csp->http->client_ssl = 1;
2342 csp->http->server_ssl = 1;
2344 freez(request_line);
2345 if (JB_ERR_OK != err)
2347 ssl_send_data_delayed(&(csp->ssl_client_attr),
2348 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2349 /* XXX: Use correct size */
2350 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2351 log_error(LOG_LEVEL_ERROR,
2352 "Couldn't parse request line received from %s: %s",
2353 csp->ip_addr_str, jb_err_to_string(err));
2355 free_http_request(csp->http);
2356 return JB_ERR_PARSE;
2359 /* Parse the rest of the client's headers. */
2363 p = get_header(csp->client_iob);
2367 /* There are no additional headers to read. */
2374 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2377 * Our attempts to get the request destination
2380 log_error(LOG_LEVEL_ERROR,
2381 "Failed to get the encrypted request destination");
2382 ssl_send_data_delayed(&(csp->ssl_client_attr),
2383 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2384 return JB_ERR_PARSE;
2387 /* Split the domain we just got for pattern matching */
2388 init_domain_components(csp->http);
2390 #ifdef FEATURE_CLIENT_TAGS
2391 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2392 if (csp->client_address == NULL)
2394 set_client_address(csp, headers);
2395 get_tag_list_for_client(csp->client_tags, csp->client_address);
2399 #ifdef FEATURE_TOGGLE
2400 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2404 * Determine the actions for this request after
2405 * clearing the ones from the previous one.
2407 free_current_action(csp->action);
2408 get_url_actions(csp, csp->http);
2411 enlist(csp->https_headers, csp->http->cmd);
2413 /* Append the previously read headers */
2414 err = list_append_list_unique(csp->https_headers, headers);
2415 destroy_list(headers);
2416 if (JB_ERR_OK != err)
2418 /* XXX: Send error message */
2422 /* XXX: Work around crash */
2423 csp->error_message = NULL;
2425 /* XXX: Why do this here? */
2428 err = sed_https(csp);
2429 if (JB_ERR_OK != err)
2431 ssl_send_data_delayed(&(csp->ssl_client_attr),
2432 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2433 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2435 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2436 csp->ip_addr_str, csp->http->cmd);
2437 return JB_ERR_PARSE;
2440 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2441 log_applied_actions(csp->action);
2442 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2449 /*********************************************************************
2451 * Function : cgi_page_requested
2453 * Description : Checks if a request is for an internal CGI page.
2456 * 1 : host = The host requested by the client.
2458 * Returns : 1 if a CGI page has been requested, 0 otherwise
2460 *********************************************************************/
2461 static int cgi_page_requested(const char *host)
2463 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2464 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2465 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2466 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2476 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2477 /*********************************************************************
2479 * Function : continue_https_chat
2481 * Description : Behaves similar to chat() but only deals with
2482 * https-inspected requests that arrive on an already
2483 * established connection. The first request is always
2484 * served by chat() which is a lot more complex as it
2485 * has to deal with forwarding settings and connection
2488 * If a connection to the server has already been
2489 * opened it is reused unless the request is blocked.
2491 * If a connection to the server has not yet been
2492 * opened (because the previous request was crunched)
2493 * the connection is dropped so that the client retries
2496 * XXX: Forwarding settings are currently ignored.
2499 * 1 : csp = Current client state (buffers, headers, etc...)
2501 * Returns : Nothing.
2503 *********************************************************************/
2504 static void continue_https_chat(struct client_state *csp)
2506 if (JB_ERR_OK != process_encrypted_request(csp))
2511 csp->requests_received_total++;
2514 * We have an encrypted request. Check if one of the crunchers wants it.
2516 if (crunch_response_triggered(csp, crunchers_all))
2519 * Yes. The client got the crunch response and we're done here.
2523 if (csp->ssl_with_server_is_opened == 0)
2525 log_error(LOG_LEVEL_CONNECT,
2526 "Dropping the client connection on socket %d. "
2527 "The server connection has not been established yet.",
2529 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2532 if (send_https_request(csp))
2535 * Most likely the server connection timed out. We can't easily
2536 * create a new one so simply drop the client connection without a
2537 * error response to let the client retry.
2539 log_error(LOG_LEVEL_CONNECT,
2540 "Dropping client connection on socket %d. "
2541 "Forwarding the encrypted client request failed.",
2545 handle_established_connection(csp);
2546 freez(csp->receive_buffer);
2548 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2552 /*********************************************************************
2554 * Function : handle_established_connection
2556 * Description : Shuffle data between client and server once the
2557 * connection has been established.
2560 * 1 : csp = Current client state (buffers, headers, etc...)
2562 * Returns : Nothing.
2564 *********************************************************************/
2565 static void handle_established_connection(struct client_state *csp)
2571 struct pollfd poll_fds[2];
2575 struct timeval timeout;
2578 int ms_iis5_hack = 0;
2579 unsigned long long byte_count = 0;
2580 struct http_request *http;
2581 long len = 0; /* for buffer sizes (and negative error codes) */
2582 int buffer_and_filter_content = 0;
2583 unsigned int write_delay;
2584 #ifdef FEATURE_HTTPS_INSPECTION
2586 int use_ssl_tunnel = 0;
2587 csp->dont_verify_certificate = 0;
2589 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2591 /* Pass encrypted content without filtering. */
2596 /* Skeleton for HTTP response, if we should intercept the request */
2597 struct http_response *rsp;
2598 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2599 int watch_client_socket;
2602 csp->receive_buffer_size = csp->config->receive_buffer_size;
2603 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2604 if (csp->receive_buffer == NULL)
2606 log_error(LOG_LEVEL_ERROR,
2607 "Out of memory. Failed to allocate the receive buffer.");
2608 rsp = cgi_error_memory();
2609 send_crunch_response(csp, rsp);
2616 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2617 csp->cfd : csp->server_connection.sfd;
2620 /* pass data between the client and server
2621 * until one or the other shuts down the connection.
2626 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2627 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2629 write_delay = get_write_delay(csp);
2636 * FD_ZERO here seems to point to an errant macro which crashes.
2637 * So do this by hand for now...
2639 memset(&rfds,0x00,sizeof(fd_set));
2643 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2644 if (!watch_client_socket)
2646 maxfd = csp->server_connection.sfd;
2649 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2651 FD_SET(csp->cfd, &rfds);
2654 FD_SET(csp->server_connection.sfd, &rfds);
2655 #endif /* ndef HAVE_POLL */
2657 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2658 if ((csp->flags & CSP_FLAG_CHUNKED)
2659 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2660 && ((csp->iob->eod - csp->iob->cur) >= 5)
2661 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2664 * XXX: This check should be obsolete now,
2665 * but let's wait a while to be sure.
2667 log_error(LOG_LEVEL_CONNECT,
2668 "Looks like we got the last chunk together with "
2669 "the server headers but didn't detect it earlier. "
2670 "We better stop reading.");
2671 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2672 csp->expected_content_length = byte_count;
2673 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2675 if (server_body && server_response_is_complete(csp, byte_count))
2677 if (csp->expected_content_length == byte_count)
2679 log_error(LOG_LEVEL_CONNECT,
2680 "Done reading from server. Content length: %llu as expected. "
2681 "Bytes most recently read: %d.",
2686 log_error(LOG_LEVEL_CONNECT,
2687 "Done reading from server. Expected content length: %llu. "
2688 "Actual content length: %llu. Bytes most recently read: %d.",
2689 csp->expected_content_length, byte_count, len);
2693 * XXX: Should not jump around, handle_established_connection()
2694 * is complicated enough already.
2698 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2701 poll_fds[0].fd = csp->cfd;
2702 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2703 if (!watch_client_socket)
2706 * Ignore incoming data, but still watch out
2707 * for disconnects etc. These flags are always
2708 * implied anyway but explicitly setting them
2711 poll_fds[0].events = POLLERR|POLLHUP;
2716 poll_fds[0].events = POLLIN;
2718 poll_fds[1].fd = csp->server_connection.sfd;
2719 poll_fds[1].events = POLLIN;
2720 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2722 timeout.tv_sec = csp->config->socket_timeout;
2723 timeout.tv_usec = 0;
2724 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
2725 #endif /* def HAVE_POLL */
2727 /*server or client not responding in timeout */
2730 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2731 csp->config->socket_timeout, http->url);
2732 if ((byte_count == 0) && (http->ssl == 0))
2734 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2736 mark_server_socket_tainted(csp);
2737 #ifdef FEATURE_HTTPS_INSPECTION
2738 close_client_and_server_ssl_connections(csp);
2745 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2747 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2749 mark_server_socket_tainted(csp);
2750 #ifdef FEATURE_HTTPS_INSPECTION
2751 close_client_and_server_ssl_connections(csp);
2757 * This is the body of the browser's request,
2758 * just read and write it.
2760 * Receives data from browser and sends it to server
2762 * XXX: Make sure the client doesn't use pipelining
2763 * behind Privoxy's back.
2766 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2768 log_error(LOG_LEVEL_CONNECT,
2769 "The client socket %d has become unusable while "
2770 "the server socket %d is still open.",
2771 csp->cfd, csp->server_connection.sfd);
2772 mark_server_socket_tainted(csp);
2776 if (poll_fds[0].revents != 0)
2778 if (FD_ISSET(csp->cfd, &rfds))
2779 #endif /* def HAVE_POLL*/
2781 int max_bytes_to_read = (int)csp->receive_buffer_size;
2783 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2784 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2786 if (data_is_available(csp->cfd, 0))
2789 * If the next request is already waiting, we have
2790 * to stop select()ing the client socket. Otherwise
2791 * we would always return right away and get nothing
2794 watch_client_socket = 0;
2795 log_error(LOG_LEVEL_CONNECT,
2796 "Stop watching client socket %d. "
2797 "There's already another request waiting.",
2802 * If the client socket is set, but there's no data
2803 * available on the socket, the client went fishing
2804 * and continuing talking to the server makes no sense.
2806 log_error(LOG_LEVEL_CONNECT,
2807 "The client closed socket %d while "
2808 "the server socket %d is still open.",
2809 csp->cfd, csp->server_connection.sfd);
2810 mark_server_socket_tainted(csp);
2813 if (csp->expected_client_content_length != 0)
2815 if (csp->expected_client_content_length < csp->receive_buffer_size)
2817 max_bytes_to_read = (int)csp->expected_client_content_length;
2819 log_error(LOG_LEVEL_CONNECT,
2820 "Waiting for up to %d bytes from the client.",
2823 assert(max_bytes_to_read <= csp->receive_buffer_size);
2824 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2826 #ifdef FEATURE_HTTPS_INSPECTION
2827 if (client_use_ssl(csp))
2829 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
2833 #endif /* def FEATURE_HTTPS_INSPECTION */
2835 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2839 /* XXX: not sure if this is necessary. */
2840 mark_server_socket_tainted(csp);
2841 break; /* "game over, man" */
2844 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2845 if (csp->expected_client_content_length != 0)
2847 assert(len <= max_bytes_to_read);
2848 csp->expected_client_content_length -= (unsigned)len;
2849 log_error(LOG_LEVEL_CONNECT,
2850 "Expected client content length set to %llu "
2851 "after reading %d bytes.",
2852 csp->expected_client_content_length, len);
2853 if (csp->expected_client_content_length == 0)
2855 log_error(LOG_LEVEL_CONNECT,
2856 "Done reading from the client.");
2857 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2860 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2862 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2864 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2865 mark_server_socket_tainted(csp);
2873 * The server wants to talk. It could be the header or the body.
2874 * If `hdr' is null, then it's the header otherwise it's the body.
2875 * FIXME: Does `hdr' really mean `host'? No.
2878 if (poll_fds[1].revents != 0)
2880 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2881 #endif /* HAVE_POLL */
2883 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2885 * If we are buffering content, we don't want to eat up to
2886 * buffer-limit bytes if the client no longer cares about them.
2887 * If we aren't buffering, however, a dead client socket will be
2888 * noticed pretty much right away anyway, so we can reduce the
2889 * overhead by skipping the check.
2891 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2894 log_error(LOG_LEVEL_CONNECT,
2895 "The server still wants to talk, but the client may already have hung up on us.");
2897 log_error(LOG_LEVEL_CONNECT,
2898 "The server still wants to talk, but the client hung up on us.");
2899 mark_server_socket_tainted(csp);
2900 #ifdef FEATURE_HTTPS_INSPECTION
2901 close_client_and_server_ssl_connections(csp);
2904 #endif /* def _WIN32 */
2906 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2908 #ifdef FEATURE_HTTPS_INSPECTION
2910 * Reading data from standard or secured connection (HTTP/HTTPS)
2912 if (server_use_ssl(csp))
2914 len = ssl_recv_data(&(csp->ssl_server_attr),
2915 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2920 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2921 (int)csp->receive_buffer_size);
2926 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2928 if ((http->ssl && (csp->fwd == NULL))
2929 #ifdef FEATURE_HTTPS_INSPECTION
2935 * Just hang up. We already confirmed the client's CONNECT
2936 * request with status code 200 and unencrypted content is
2937 * no longer welcome.
2939 log_error(LOG_LEVEL_ERROR,
2940 "CONNECT already confirmed. Unable to tell the client about the problem.");
2943 else if (byte_count)
2946 * Just hang up. We already transmitted the original headers
2947 * and parts of the original content and therefore missed the
2948 * chance to send an error message (without risking data corruption).
2950 * XXX: we could retry with a fancy range request here.
2952 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2953 "Unable to tell the client about the problem.");
2954 mark_server_socket_tainted(csp);
2955 #ifdef FEATURE_HTTPS_INSPECTION
2956 close_client_and_server_ssl_connections(csp);
2961 * XXX: Consider handling the cases above the same.
2963 mark_server_socket_tainted(csp);
2967 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2968 if (csp->flags & CSP_FLAG_CHUNKED)
2970 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2972 /* XXX: this is a temporary hack */
2973 log_error(LOG_LEVEL_CONNECT,
2974 "Looks like we reached the end of the last chunk. "
2975 "We better stop reading.");
2976 csp->expected_content_length = byte_count + (unsigned long long)len;
2977 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2981 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2984 * This is guaranteed by allocating with zalloc_or_die()
2985 * and never (intentionally) writing to the last byte.
2987 * csp->receive_buffer_size is the size of the part of the
2988 * buffer we intentionally write to, but we actually
2989 * allocated csp->receive_buffer_size+1 bytes so the assertion
2990 * stays within the allocated range.
2992 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2995 * Add a trailing zero to let be able to use string operations.
2996 * XXX: do we still need this with filter_popups gone?
2998 assert(len <= csp->receive_buffer_size);
2999 csp->receive_buffer[len] = '\0';
3002 * Normally, this would indicate that we've read
3003 * as much as the server has sent us and we can
3004 * close the client connection. However, Microsoft
3005 * in its wisdom has released IIS/5 with a bug that
3006 * prevents it from sending the trailing \r\n in
3007 * a 302 redirect header (and possibly other headers).
3008 * To work around this if we've haven't parsed
3009 * a full header we'll append a trailing \r\n
3010 * and see if this now generates a valid one.
3012 * This hack shouldn't have any impacts. If we've
3013 * already transmitted the header or if this is a
3014 * SSL connection, then we won't bother with this
3015 * hack. So we only work on partially received
3016 * headers. If we append a \r\n and this still
3017 * doesn't generate a valid header, then we won't
3018 * transmit anything to the client.
3023 if (server_body || (http->ssl
3024 #ifdef FEATURE_HTTPS_INSPECTION
3030 * If we have been buffering up the document,
3031 * now is the time to apply content modification
3032 * and send the result to the client.
3034 if (buffer_and_filter_content)
3036 p = execute_content_filters(csp);
3038 * If content filtering fails, use the original
3039 * buffer and length.
3040 * (see p != NULL ? p : csp->iob->cur below)
3044 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3046 #ifdef FEATURE_COMPRESSION
3047 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3048 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3050 char *compressed_content = compress_buffer(p,
3051 (size_t *)&csp->content_length, csp->config->compression_level);
3052 if (compressed_content != NULL)
3055 p = compressed_content;
3056 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3061 if (JB_ERR_OK != update_server_headers(csp))
3063 log_error(LOG_LEVEL_FATAL,
3064 "Failed to update server headers. after filtering.");
3067 hdr = list_to_text(csp->headers);
3070 /* FIXME Should handle error properly */
3071 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3074 #ifdef FEATURE_HTTPS_INSPECTION
3076 * Sending data with standard or secured connection (HTTP/HTTPS)
3078 if (client_use_ssl(csp))
3080 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3081 (const unsigned char *)hdr, strlen(hdr),
3082 get_write_delay(csp)) < 0)
3083 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3084 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3085 csp->content_length, get_write_delay(csp)) < 0))
3087 log_error(LOG_LEVEL_ERROR, "write modified content to "
3088 "client over TLS/SSL failed");
3091 mark_server_socket_tainted(csp);
3092 close_client_and_server_ssl_connections(csp);
3097 #endif /* def FEATURE_HTTPS_INSPECTION */
3099 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3100 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3101 (size_t)csp->content_length, write_delay))
3103 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3106 mark_server_socket_tainted(csp);
3115 break; /* "game over, man" */
3119 * This is NOT the body, so
3120 * Let's pretend the server just sent us a blank line.
3122 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3123 len = (int)strlen(csp->receive_buffer);
3126 * Now, let the normal header parsing algorithm below do its
3127 * job. If it fails, we'll exit instead of continuing.
3134 * If we're in the body of the server document, just write it to
3135 * the client, unless we need to buffer the body for later
3136 * content-filtering.
3138 if (server_body || (http->ssl
3139 #ifdef FEATURE_HTTPS_INSPECTION
3144 if (buffer_and_filter_content)
3147 * If there is no memory left for buffering the content, or the buffer limit
3148 * has been reached, switch to non-filtering mode, i.e. make & write the
3149 * header, flush the iob and buf, and get out of the way.
3151 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3156 log_error(LOG_LEVEL_INFO,
3157 "Flushing header and buffers. Stepping back from filtering.");
3159 hdr = list_to_text(csp->headers);
3163 * Memory is too tight to even generate the header.
3164 * Send our static "Out-of-memory" page.
3166 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3167 rsp = cgi_error_memory();
3168 send_crunch_response(csp, rsp);
3169 mark_server_socket_tainted(csp);
3170 #ifdef FEATURE_HTTPS_INSPECTION
3171 close_client_and_server_ssl_connections(csp);
3175 hdrlen = strlen(hdr);
3177 #ifdef FEATURE_HTTPS_INSPECTION
3179 * Sending data with standard or secured connection (HTTP/HTTPS)
3181 if (client_use_ssl(csp))
3183 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3184 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3185 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3187 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3188 (const unsigned char *)csp->receive_buffer, (size_t)len,
3189 get_write_delay(csp)) < 0))
3191 log_error(LOG_LEVEL_CONNECT,
3192 "Flush header and buffers to client failed");
3194 mark_server_socket_tainted(csp);
3195 close_client_and_server_ssl_connections(csp);
3200 #endif /* def FEATURE_HTTPS_INSPECTION */
3202 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3203 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3204 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3207 log_error(LOG_LEVEL_CONNECT,
3208 "Flush header and buffers to client failed: %E");
3210 mark_server_socket_tainted(csp);
3216 * Reset the byte_count to the amount of bytes
3217 * we just flushed. len will be added a few lines below,
3218 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3220 byte_count = (unsigned long long)flushed;
3222 buffer_and_filter_content = 0;
3228 #ifdef FEATURE_HTTPS_INSPECTION
3230 * Sending data with standard or secured connection (HTTP/HTTPS)
3232 if (client_use_ssl(csp))
3234 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3235 (const unsigned char *)csp->receive_buffer, (size_t)len,
3236 get_write_delay(csp));
3239 log_error(LOG_LEVEL_ERROR,
3240 "Sending data to client failed");
3241 mark_server_socket_tainted(csp);
3242 close_client_and_server_ssl_connections(csp);
3247 #endif /* def FEATURE_HTTPS_INSPECTION */
3249 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3250 (size_t)len, write_delay))
3252 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3253 mark_server_socket_tainted(csp);
3258 byte_count += (unsigned long long)len;
3264 * We're still looking for the end of the server's header.
3265 * Buffer up the data we just read. If that fails, there's
3266 * little we can do but send our static out-of-memory page.
3268 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3270 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3271 rsp = cgi_error_memory();
3272 send_crunch_response(csp, rsp);
3273 mark_server_socket_tainted(csp);
3274 #ifdef FEATURE_HTTPS_INSPECTION
3275 close_client_and_server_ssl_connections(csp);
3280 /* Convert iob into something sed() can digest */
3281 if (JB_ERR_PARSE == get_server_headers(csp))
3286 * Well, we tried our MS IIS/5 hack and it didn't work.
3287 * The header is incomplete and there isn't anything
3288 * we can do about it.
3290 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3291 "Applying the MS IIS5 hack didn't help.");
3292 log_error(LOG_LEVEL_CLF,
3293 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3294 #ifdef FEATURE_HTTPS_INSPECTION
3296 * Sending data with standard or secured connection (HTTP/HTTPS)
3298 if (client_use_ssl(csp))
3300 ssl_send_data_delayed(&(csp->ssl_client_attr),
3301 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3302 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3305 #endif /* def FEATURE_HTTPS_INSPECTION */
3307 write_socket_delayed(csp->cfd,
3308 INVALID_SERVER_HEADERS_RESPONSE,
3309 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3311 mark_server_socket_tainted(csp);
3312 #ifdef FEATURE_HTTPS_INSPECTION
3313 close_client_and_server_ssl_connections(csp);
3320 * Since we have to wait for more from the server before
3321 * we can parse the headers we just continue here.
3323 log_error(LOG_LEVEL_CONNECT,
3324 "Continuing buffering server headers from socket %d. "
3325 "Bytes most recently read: %d.", csp->cfd, len);
3332 * Account for the content bytes we
3333 * might have gotten with the headers.
3335 assert(csp->iob->eod >= csp->iob->cur);
3336 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3339 /* Did we actually get anything? */
3340 if (NULL == csp->headers->first)
3342 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3344 log_error(LOG_LEVEL_ERROR,
3345 "No server or forwarder response received on socket %d. "
3346 "Closing client socket %d without sending data.",
3347 csp->server_connection.sfd, csp->cfd);
3348 log_error(LOG_LEVEL_CLF,
3349 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3353 log_error(LOG_LEVEL_ERROR,
3354 "No server or forwarder response received on socket %d.",
3355 csp->server_connection.sfd);
3356 send_crunch_response(csp, error_response(csp, "no-server-data"));
3358 free_http_request(http);
3359 mark_server_socket_tainted(csp);
3360 #ifdef FEATURE_HTTPS_INSPECTION
3361 close_client_and_server_ssl_connections(csp);
3366 if (!csp->headers->first->str)
3368 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3370 assert(csp->headers->first->str);
3372 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3373 strncmpic(csp->headers->first->str, "ICY", 3))
3376 * It doesn't look like a HTTP (or Shoutcast) response:
3377 * tell the client and log the problem.
3379 if (strlen(csp->headers->first->str) > 30)
3381 csp->headers->first->str[30] = '\0';
3383 log_error(LOG_LEVEL_ERROR,
3384 "Invalid server or forwarder response. Starts with: %s",
3385 csp->headers->first->str);
3386 log_error(LOG_LEVEL_CLF,
3387 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3388 #ifdef FEATURE_HTTPS_INSPECTION
3390 * Sending data with standard or secured connection (HTTP/HTTPS)
3392 if (client_use_ssl(csp))
3394 ssl_send_data_delayed(&(csp->ssl_client_attr),
3395 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3396 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3397 get_write_delay(csp));
3400 #endif /* def FEATURE_HTTPS_INSPECTION */
3402 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3403 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3405 free_http_request(http);
3406 mark_server_socket_tainted(csp);
3407 #ifdef FEATURE_HTTPS_INSPECTION
3408 close_client_and_server_ssl_connections(csp);
3414 * We have now received the entire server header,
3415 * filter it and send the result to the client
3417 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3419 log_error(LOG_LEVEL_CLF,
3420 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3421 #ifdef FEATURE_HTTPS_INSPECTION
3423 * Sending data with standard or secured connection (HTTP/HTTPS)
3425 if (client_use_ssl(csp))
3427 ssl_send_data_delayed(&(csp->ssl_client_attr),
3428 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3429 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3430 get_write_delay(csp));
3435 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3436 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3438 free_http_request(http);
3439 mark_server_socket_tainted(csp);
3440 #ifdef FEATURE_HTTPS_INSPECTION
3441 close_client_and_server_ssl_connections(csp);
3445 hdr = list_to_text(csp->headers);
3448 /* FIXME Should handle error properly */
3449 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3452 if ((csp->flags & CSP_FLAG_CHUNKED)
3453 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3454 && ((csp->iob->eod - csp->iob->cur) >= 5)
3455 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3457 log_error(LOG_LEVEL_CONNECT,
3458 "Looks like we got the last chunk together with "
3459 "the server headers. We better stop reading.");
3460 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3461 csp->expected_content_length = byte_count;
3462 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3465 csp->server_connection.response_received = time(NULL);
3467 if (crunch_response_triggered(csp, crunchers_light))
3470 * One of the tags created by a server-header
3471 * tagger triggered a crunch. We already
3472 * delivered the crunch response to the client
3473 * and are done here after cleaning up.
3476 mark_server_socket_tainted(csp);
3477 #ifdef FEATURE_HTTPS_INSPECTION
3478 close_client_and_server_ssl_connections(csp);
3483 /* Buffer and pcrs filter this if appropriate. */
3484 buffer_and_filter_content = content_requires_filtering(csp);
3486 if (!buffer_and_filter_content)
3489 * Write the server's (modified) header to
3490 * the client (along with anything else that
3491 * may be in the buffer). Use standard or secured
3494 #ifdef FEATURE_HTTPS_INSPECTION
3495 if (client_use_ssl(csp))
3497 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3498 (const unsigned char *)hdr, strlen(hdr),
3499 get_write_delay(csp)) < 0)
3500 || (len = ssl_flush_socket(&(csp->ssl_client_attr),
3503 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3506 * The write failed, so don't bother mentioning it
3507 * to the client... it probably can't hear us anyway.
3510 mark_server_socket_tainted(csp);
3511 #ifdef FEATURE_HTTPS_INSPECTION
3512 close_client_and_server_ssl_connections(csp);
3518 #endif /* def FEATURE_HTTPS_INSPECTION */
3520 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3521 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3523 log_error(LOG_LEVEL_ERROR,
3524 "write header to client failed");
3526 * The write failed, so don't bother mentioning it
3527 * to the client... it probably can't hear us anyway.
3530 mark_server_socket_tainted(csp);
3536 /* we're finished with the server's header */
3542 * If this was a MS IIS/5 hack then it means the server
3543 * has already closed the connection. Nothing more to read.
3548 log_error(LOG_LEVEL_ERROR,
3549 "Closed server connection detected. "
3550 "Applying the MS IIS5 hack didn't help.");
3551 log_error(LOG_LEVEL_CLF,
3552 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3553 #ifdef FEATURE_HTTPS_INSPECTION
3555 * Sending data with standard or secured connection (HTTP/HTTPS)
3557 if (client_use_ssl(csp))
3559 ssl_send_data_delayed(&(csp->ssl_client_attr),
3560 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3561 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3562 get_write_delay(csp));
3565 #endif /* def FEATURE_HTTPS_INSPECTION */
3567 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3568 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3570 mark_server_socket_tainted(csp);
3571 #ifdef FEATURE_HTTPS_INSPECTION
3572 close_client_and_server_ssl_connections(csp);
3579 mark_server_socket_tainted(csp);
3580 #ifdef FEATURE_HTTPS_INSPECTION
3581 close_client_and_server_ssl_connections(csp);
3583 return; /* huh? we should never get here */
3586 if (csp->content_length == 0)
3589 * If Privoxy didn't recalculate the Content-Length,
3590 * byte_count is still correct.
3592 csp->content_length = byte_count;
3595 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3596 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3597 && (csp->expected_content_length != byte_count))
3599 log_error(LOG_LEVEL_CONNECT,
3600 "Received %llu bytes while expecting %llu.",
3601 byte_count, csp->expected_content_length);
3602 mark_server_socket_tainted(csp);
3606 #ifdef FEATURE_HTTPS_INSPECTION
3607 if (client_use_ssl(csp))
3609 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
3610 csp->ip_addr_str, http->gpc, http->hostport, http->path,
3611 http->version, csp->content_length);
3616 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3617 csp->ip_addr_str, http->ocmd, csp->content_length);
3619 csp->server_connection.timestamp = time(NULL);
3623 /*********************************************************************
3627 * Description : Once a connection from the client has been accepted,
3628 * this function is called (via serve()) to handle the
3629 * main business of the communication. This function
3630 * returns after dealing with a single request. It can
3631 * be called multiple times with the same client socket
3632 * if the client is keeping the connection alive.
3634 * The decision whether or not a client connection will
3635 * be kept alive is up to the caller which also must
3636 * close the client socket when done.
3638 * FIXME: chat is nearly thousand lines long.
3642 * 1 : csp = Current client state (buffers, headers, etc...)
3644 * Returns : Nothing.
3646 *********************************************************************/
3647 static void chat(struct client_state *csp)
3649 const struct forward_spec *fwd;
3650 struct http_request *http;
3651 /* Skeleton for HTTP response, if we should intercept the request */
3652 struct http_response *rsp;
3653 #ifdef FEATURE_HTTPS_INSPECTION
3654 int use_ssl_tunnel = 0;
3659 if (receive_client_request(csp) != JB_ERR_OK)
3663 if (parse_client_request(csp) != JB_ERR_OK)
3668 /* decide how to route the HTTP request */
3669 fwd = forward_url(csp, http);
3672 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
3673 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3677 #ifdef FEATURE_HTTPS_INSPECTION
3679 * Setting flags to use old solution with SSL tunnel and to disable
3680 * certificate verification.
3682 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
3683 && !cgi_page_requested(csp->http->host))
3688 if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3690 csp->dont_verify_certificate = 1;
3695 * build the http request to send to the server
3696 * we have to do one of the following:
3698 * create = use the original HTTP request to create a new
3699 * HTTP request that has either the path component
3700 * without the http://domainspec (w/path) or the
3701 * full orininal URL (w/url)
3702 * Note that the path and/or the HTTP version may
3703 * have been altered by now.
3705 * SSL proxy = Open a socket to the host:port of the server
3706 * and create TLS/SSL connection with server and
3707 * with client. Then behave like mediator between
3708 * client and server over TLS/SSL.
3710 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3711 * with request to a parent proxy. Note that we'll be sending
3712 * forwarding the CFAIL message ourselves if connecting to the parent
3713 * fails, but we won't send a CSUCCEED message if it works,
3714 * since that would result in a double message (ours and the
3715 * parent's). After sending the request to the parent, we
3716 * must parse answer and send it to client. If connection
3717 * with server is established, we do TLS/SSL proxy. Otherwise
3718 * we send parent response to client and close connections.
3720 * here's the matrix:
3723 * +--------+--------+
3725 * 0 | create | SSL |
3726 * | w/path | proxy |
3727 * Forwarding +--------+--------+
3729 * 1 | create | proxy |
3730 * | w/url |+forward|
3731 * +--------+--------+
3735 #ifdef FEATURE_HTTPS_INSPECTION
3737 * Presetting SSL client and server flags
3739 if (http->ssl && !use_ssl_tunnel)
3741 http->client_ssl = 1;
3742 http->server_ssl = 1;
3746 http->client_ssl = 0;
3747 http->server_ssl = 0;
3751 #ifdef FEATURE_HTTPS_INSPECTION
3753 * Log the request unless we're https inspecting
3754 * in which case we don't have the path yet and
3755 * will log the request later.
3757 if (!client_use_ssl(csp))
3760 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
3763 if (http->ssl && connect_port_is_forbidden(csp))
3765 const char *acceptable_connect_ports =
3766 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3767 assert(NULL != acceptable_connect_ports);
3768 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3769 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3770 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3771 csp->action->flags |= ACTION_BLOCK;
3773 #ifdef FEATURE_HTTPS_INSPECTION
3774 http->client_ssl = 0;
3775 http->server_ssl = 0;
3780 freez(csp->headers->first->str);
3781 build_request_line(csp, fwd, &csp->headers->first->str);
3784 * We have a request. Check if one of the crunchers wants it
3785 * unless the client wants to use TLS/SSL in which case we
3786 * haven't setup the TLS context yet and will send the crunch
3790 #ifdef FEATURE_HTTPS_INSPECTION
3791 !client_use_ssl(csp) &&
3793 crunch_response_triggered(csp, crunchers_all))
3796 * Yes. The client got the crunch response and we're done here.
3801 log_applied_actions(csp->action);
3802 if (fwd->forward_host)
3804 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3805 fwd->forward_host, fwd->forward_port, http->hostport);
3809 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3812 /* here we connect to the server, gateway, or the forwarder */
3814 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3815 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3816 && socket_is_still_alive(csp->server_connection.sfd)
3817 && connection_destination_matches(&csp->server_connection, http, fwd))
3819 log_error(LOG_LEVEL_CONNECT,
3820 "Reusing server socket %d connected to %s. Total requests: %u.",
3821 csp->server_connection.sfd, csp->server_connection.host,
3822 csp->server_connection.requests_sent_total);
3826 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3828 #ifdef FEATURE_CONNECTION_SHARING
3829 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
3830 #ifdef FEATURE_HTTPS_INSPECTION
3831 && !server_use_ssl(csp)
3835 remember_connection(&csp->server_connection);
3838 #endif /* def FEATURE_CONNECTION_SHARING */
3840 log_error(LOG_LEVEL_CONNECT,
3841 "Closing server socket %d connected to %s. Total requests: %u.",
3842 csp->server_connection.sfd, csp->server_connection.host,
3843 csp->server_connection.requests_sent_total);
3844 close_socket(csp->server_connection.sfd);
3846 mark_connection_closed(&csp->server_connection);
3848 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3849 #ifdef FEATURE_HTTPS_INSPECTION
3850 if (http->ssl && !use_ssl_tunnel)
3854 * Creating a SSL proxy.
3856 * By sending the CSUCCEED message we're lying to the client as
3857 * the connection hasn't actually been established yet. We don't
3858 * establish the connection until we have seen and parsed the
3859 * encrypted client headers.
3861 if (write_socket_delayed(csp->cfd, CSUCCEED,
3862 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3864 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3868 ret = create_client_ssl_connection(csp);
3871 log_error(LOG_LEVEL_ERROR,
3872 "Failed to open a secure connection with the client");
3875 if (JB_ERR_OK != process_encrypted_request(csp))
3877 log_error(LOG_LEVEL_ERROR, "Failed to parse encrypted request.");
3878 close_client_ssl_connection(csp);
3882 * We have an encrypted request. Check if one of the crunchers now
3883 * wants it (for example because the previously invisible path was
3884 * required to match).
3886 if (crunch_response_triggered(csp, crunchers_all))
3889 * Yes. The client got the crunch response and we're done here.
3896 * Connecting to destination server
3898 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3900 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3902 if (fwd->type != SOCKS_NONE)
3905 rsp = error_response(csp, "forwarding-failed");
3907 else if (errno == EINVAL)
3909 rsp = error_response(csp, "no-such-domain");
3913 rsp = error_response(csp, "connect-failed");
3916 /* Write the answer to the client */
3919 send_crunch_response(csp, rsp);
3923 * Temporary workaround to prevent already-read client
3924 * bodies from being parsed as new requests. For now we
3925 * err on the safe side and throw all the following
3926 * requests under the bus, even if no client body has been
3927 * buffered. A compliant client will repeat the dropped
3928 * requests on an untainted connection.
3930 * The proper fix is to discard the no longer needed
3931 * client body in the buffer (if there is one) and to
3932 * continue parsing the bytes that follow.
3934 #ifdef FEATURE_HTTPS_INSPECTION
3935 close_client_ssl_connection(csp);
3937 drain_and_close_socket(csp->cfd);
3938 csp->cfd = JB_INVALID_SOCKET;
3943 #ifdef FEATURE_HTTPS_INSPECTION
3945 * Creating TLS/SSL connections with destination server or parent
3946 * proxy. If forwarding is enabled, we must send client request to
3947 * parent proxy and receive, parse and resend parent proxy answer.
3949 if (http->ssl && !use_ssl_tunnel)
3951 if (fwd->forward_host != NULL)
3953 char server_response[BUFFER_SIZE];
3956 char *hdr = list_to_text(csp->headers);
3957 memset(server_response, 0, sizeof(server_response));
3961 log_error(LOG_LEVEL_FATAL,
3962 "Out of memory parsing client header");
3964 list_remove_all(csp->headers);
3967 * Sending client's CONNECT request to the parent proxy
3969 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
3975 log_error(LOG_LEVEL_CONNECT,
3976 "Sending request headers to: %s failed", http->hostport);
3977 mark_server_socket_tainted(csp);
3978 close_client_ssl_connection(csp);
3982 /* Waiting for parent proxy server response */
3983 len = read_socket(csp->server_connection.sfd, server_response,
3984 sizeof(server_response)-1);
3988 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
3989 "server on socket %d.", csp->server_connection.sfd);
3991 rsp = error_response(csp, "no-server-data");
3994 send_crunch_response(csp, rsp);
3996 mark_server_socket_tainted(csp);
3997 close_client_ssl_connection(csp);
4002 * Test if the connection to the destination server was
4003 * established successfully by the parent proxy.
4005 if (!tunnel_established_successfully(server_response, (unsigned int)len))
4007 log_error(LOG_LEVEL_ERROR,
4008 "The forwarder %s failed to establish a connection with %s",
4009 fwd->forward_host, http->host);
4010 rsp = error_response(csp, "connect-failed");
4013 send_crunch_response(csp, rsp);
4015 mark_server_socket_tainted(csp);
4016 close_client_ssl_connection(csp);
4019 } /* -END- if (fwd->forward_host != NULL) */
4022 * We can now create the TLS/SSL connection with the destination server.
4024 int ret = create_server_ssl_connection(csp);
4027 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4028 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4031 * If the server certificate is invalid, we must inform
4032 * the client and then close connection to the client.
4034 ssl_send_certificate_error(csp);
4035 close_client_and_server_ssl_connections(csp);
4038 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4039 || csp->server_cert_verification_result == SSL_CERT_VALID)
4042 * The TLS/SSL connection wasn't created but an invalid
4043 * certificate wasn't detected. Report it as connection
4046 rsp = error_response(csp, "connect-failed");
4049 send_crunch_response(csp, rsp);
4051 close_client_and_server_ssl_connections(csp);
4055 }/* -END- if (http->ssl) */
4056 #endif /* def FEATURE_HTTPS_INSPECTION */
4058 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4059 save_connection_destination(csp->server_connection.sfd,
4060 http, fwd, &csp->server_connection);
4061 csp->server_connection.keep_alive_timeout =
4062 (unsigned)csp->config->keep_alive_timeout;
4064 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4066 csp->server_connection.requests_sent_total++;
4068 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4070 /* Client headers have been sent optimistically */
4071 assert(csp->headers->last == NULL);
4073 else if (http->ssl == 0 || (fwd->forward_host
4074 #ifdef FEATURE_HTTPS_INSPECTION
4079 if (send_http_request(csp))
4081 rsp = error_response(csp, "connect-failed");
4084 send_crunch_response(csp, rsp);
4092 * Using old solution with SSL tunnel or new solution with SSL proxy
4094 list_remove_all(csp->headers);
4095 #ifdef FEATURE_HTTPS_INSPECTION
4100 * We're running an SSL tunnel and we're not forwarding,
4101 * so just ditch the client headers, send the "connect succeeded"
4102 * message to the client, flush the rest, and get out of the way.
4104 if (write_socket_delayed(csp->cfd, CSUCCEED,
4105 strlen(CSUCCEED), get_write_delay(csp)))
4110 #ifdef FEATURE_HTTPS_INSPECTION
4114 * If server certificate is invalid, we must inform client and then
4115 * close connection with client.
4117 if (csp->server_cert_verification_result != SSL_CERT_VALID)
4119 ssl_send_certificate_error(csp);
4120 close_client_and_server_ssl_connections(csp);
4123 if (send_https_request(csp))
4125 rsp = error_response(csp, "connect-failed");
4128 send_crunch_response(csp, rsp);
4130 close_client_and_server_ssl_connections(csp);
4134 #endif /* def FEATURE_HTTPS_INSPECTION */
4135 clear_iob(csp->client_iob);
4136 }/* -END- else ... if (http->ssl == 1) */
4138 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4140 /* XXX: should the time start earlier for optimistically sent data? */
4141 csp->server_connection.request_sent = time(NULL);
4143 handle_established_connection(csp);
4144 freez(csp->receive_buffer);
4149 /*********************************************************************
4151 * Function : fuzz_server_response
4153 * Description : Treat the input as a whole server response.
4156 * 1 : csp = Current client state (buffers, headers, etc...)
4157 * 2 : fuzz_input_file = File to read the input from.
4161 *********************************************************************/
4162 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4164 static struct forward_spec fwd; /* Zero'd due to being static */
4167 if (strcmp(fuzz_input_file, "-") == 0)
4169 /* XXX: Doesn't work yet. */
4170 csp->server_connection.sfd = 0;
4174 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4175 if (csp->server_connection.sfd == -1)
4177 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4182 csp->content_type |= CT_GIF;
4183 csp->action->flags |= ACTION_DEANIMATE;
4184 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4186 csp->http->path = strdup_or_die("/");
4187 csp->http->host = strdup_or_die("fuzz.example.org");
4188 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4189 /* Prevent client socket monitoring */
4190 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4191 csp->flags |= CSP_FLAG_CHUNKED;
4193 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4194 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4196 csp->content_type |= CT_DECLARED|CT_GIF;
4198 csp->config->socket_timeout = 0;
4200 cgi_init_error_messages();
4202 handle_established_connection(csp);
4203 freez(csp->receive_buffer);
4210 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4211 /*********************************************************************
4213 * Function : prepare_csp_for_next_request
4215 * Description : Put the csp in a mostly vergin state.
4218 * 1 : csp = Current client state (buffers, headers, etc...)
4222 *********************************************************************/
4223 static void prepare_csp_for_next_request(struct client_state *csp)
4225 csp->content_type = 0;
4226 csp->content_length = 0;
4227 csp->expected_content_length = 0;
4228 csp->expected_client_content_length = 0;
4229 list_remove_all(csp->headers);
4230 clear_iob(csp->iob);
4231 freez(csp->error_message);
4232 free_http_request(csp->http);
4233 destroy_list(csp->headers);
4234 #ifdef FEATURE_HTTPS_INSPECTION
4235 destroy_list(csp->https_headers);
4237 destroy_list(csp->tags);
4238 #ifdef FEATURE_CLIENT_TAGS
4239 destroy_list(csp->client_tags);
4240 freez(csp->client_address);
4242 free_current_action(csp->action);
4243 if (NULL != csp->fwd)
4245 unload_forward_spec(csp->fwd);
4248 /* XXX: Store per-connection flags someplace else. */
4249 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4250 #ifdef FEATURE_TOGGLE
4251 if (global_toggle_state)
4252 #endif /* def FEATURE_TOGGLE */
4254 csp->flags |= CSP_FLAG_TOGGLED_ON;
4257 if (csp->client_iob->eod > csp->client_iob->cur)
4259 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4260 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4262 assert(bytes_to_shift > 0);
4263 assert(data_length > 0);
4265 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
4266 data_length, bytes_to_shift);
4267 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4268 csp->client_iob->cur = csp->client_iob->buf;
4269 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4270 csp->client_iob->eod = csp->client_iob->buf + data_length;
4271 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4273 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4278 * We mainly care about resetting client_iob->cur so we don't
4279 * waste buffer space at the beginning and don't mess up the
4280 * request restoration done by cgi_show_request().
4282 * Freeing the buffer itself isn't technically necessary,
4283 * but makes debugging more convenient.
4285 clear_iob(csp->client_iob);
4288 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4291 /*********************************************************************
4295 * Description : This is little more than chat. We only "serve" to
4296 * to close (or remember) any socket that chat may have
4300 * 1 : csp = Current client state (buffers, headers, etc...)
4304 *********************************************************************/
4305 static void serve(struct client_state *csp)
4307 int config_file_change_detected = 0; /* Only used for debugging */
4308 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4309 #ifdef FEATURE_CONNECTION_SHARING
4310 static int monitor_thread_running = 0;
4311 #endif /* def FEATURE_CONNECTION_SHARING */
4312 int continue_chatting = 0;
4314 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4315 csp->ip_addr_str, csp->cfd);
4319 unsigned int latency;
4321 #ifdef FEATURE_HTTPS_INSPECTION
4322 if (continue_chatting && client_use_ssl(csp))
4324 continue_https_chat(csp);
4333 * If the request has been crunched,
4334 * the calculated latency is zero.
4336 latency = (unsigned)(csp->server_connection.response_received -
4337 csp->server_connection.request_sent) / 2;
4339 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4340 && (csp->flags & CSP_FLAG_CRUNCHED)
4341 && (csp->expected_client_content_length != 0))
4343 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4344 log_error(LOG_LEVEL_CONNECT,
4345 "Tainting client socket %d due to unread data.", csp->cfd);
4348 continue_chatting = (csp->config->feature_flags
4349 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4350 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4351 && (csp->cfd != JB_INVALID_SOCKET)
4352 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4353 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4354 || (csp->flags & CSP_FLAG_CHUNKED));
4356 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4357 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4359 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4361 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4363 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4364 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4365 || !socket_is_still_alive(csp->server_connection.sfd)
4366 || !(latency < csp->server_connection.keep_alive_timeout))
4368 log_error(LOG_LEVEL_CONNECT,
4369 "Closing server socket %d connected to %s. "
4370 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4371 csp->server_connection.sfd, csp->server_connection.host,
4372 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4373 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4374 socket_is_still_alive(csp->server_connection.sfd),
4375 csp->server_connection.keep_alive_timeout);
4376 #ifdef FEATURE_CONNECTION_SHARING
4377 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4379 forget_connection(csp->server_connection.sfd);
4381 #endif /* def FEATURE_CONNECTION_SHARING */
4382 #ifdef FEATURE_HTTPS_INSPECTION
4383 close_server_ssl_connection(csp);
4385 close_socket(csp->server_connection.sfd);
4386 mark_connection_closed(&csp->server_connection);
4390 if (continue_chatting && any_loaded_file_changed(csp))
4392 continue_chatting = 0;
4393 config_file_change_detected = 1;
4395 #ifdef FEATURE_HTTPS_INSPECTION
4396 if (continue_chatting && client_use_ssl(csp) &&
4397 csp->ssl_with_client_is_opened == 0)
4399 continue_chatting = 0;
4400 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4401 "The TLS session has been terminated.", csp->cfd);
4405 if (continue_chatting)
4407 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4408 && socket_is_still_alive(csp->cfd))
4410 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4411 "pipelined on socket %d and the socket is still alive.",
4412 csp->requests_received_total+1, csp->cfd);
4413 prepare_csp_for_next_request(csp);
4417 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4419 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4421 log_error(LOG_LEVEL_CONNECT,
4422 "Waiting for the next client request on socket %d. "
4423 "Keeping the server socket %d to %s open.",
4424 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4428 log_error(LOG_LEVEL_CONNECT,
4429 "Waiting for the next client request on socket %d. "
4430 "No server socket to keep open.", csp->cfd);
4434 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4435 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4436 && socket_is_still_alive(csp->cfd))
4438 log_error(LOG_LEVEL_CONNECT,
4439 "Data arrived in time on client socket %d. Requests so far: %u",
4440 csp->cfd, csp->requests_received_total);
4441 prepare_csp_for_next_request(csp);
4445 #ifdef FEATURE_CONNECTION_SHARING
4446 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4447 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4448 && (socket_is_still_alive(csp->server_connection.sfd))
4449 #ifdef FEATURE_HTTPS_INSPECTION
4450 && !server_use_ssl(csp)
4454 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4456 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4461 remember_connection(&csp->server_connection);
4462 csp->server_connection.sfd = JB_INVALID_SOCKET;
4463 drain_and_close_socket(csp->cfd);
4464 csp->cfd = JB_INVALID_SOCKET;
4465 privoxy_mutex_lock(&connection_reuse_mutex);
4466 if (!monitor_thread_running)
4468 monitor_thread_running = 1;
4469 privoxy_mutex_unlock(&connection_reuse_mutex);
4470 wait_for_alive_connections();
4471 privoxy_mutex_lock(&connection_reuse_mutex);
4472 monitor_thread_running = 0;
4474 privoxy_mutex_unlock(&connection_reuse_mutex);
4476 #endif /* def FEATURE_CONNECTION_SHARING */
4480 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4482 log_error(LOG_LEVEL_CONNECT,
4483 "Closing server socket %d connected to %s. Keep-alive: %u. "
4484 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4485 "Configuration file change detected: %u",
4486 csp->server_connection.sfd, csp->server_connection.host,
4487 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4488 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4489 socket_is_still_alive(csp->server_connection.sfd),
4490 csp->server_connection.keep_alive_timeout,
4491 config_file_change_detected);
4493 } while (continue_chatting);
4497 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4499 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4501 #ifdef FEATURE_CONNECTION_SHARING
4502 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4504 forget_connection(csp->server_connection.sfd);
4506 #endif /* def FEATURE_CONNECTION_SHARING */
4508 #ifdef FEATURE_HTTPS_INSPECTION
4509 close_server_ssl_connection(csp);
4510 #endif /* def FEATURE_HTTPS_INSPECTION */
4512 close_socket(csp->server_connection.sfd);
4515 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4516 mark_connection_closed(&csp->server_connection);
4519 if (csp->cfd != JB_INVALID_SOCKET)
4521 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4522 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4523 "Configuration file change detected: %u. Requests received: %u.",
4524 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4525 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4526 config_file_change_detected, csp->requests_received_total);
4527 #ifdef FEATURE_HTTPS_INSPECTION
4528 close_client_ssl_connection(csp);
4530 drain_and_close_socket(csp->cfd);
4533 free_csp_resources(csp);
4535 csp->flags &= ~CSP_FLAG_ACTIVE;
4541 /*********************************************************************
4543 * Function : server_thread
4545 * Description : We only exist to call `serve' in a threaded environment.
4548 * 1 : data = Current client state (buffers, headers, etc...)
4550 * Returns : Always 0.
4552 *********************************************************************/
4553 static int32 server_thread(void *data)
4555 serve((struct client_state *) data);
4562 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4563 /*********************************************************************
4567 * Description : Print usage info & exit.
4569 * Parameters : Pointer to argv[0] for identifying ourselves
4573 *********************************************************************/
4574 static void usage(const char *name)
4576 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4577 "Usage: %s [--config-test] "
4580 #endif /* defined(unix) */
4583 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4584 #endif /* defined(unix) */
4585 "[--version] [configfile]\n",
4589 show_fuzz_usage(name);
4592 printf("Aborting\n");
4597 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4600 #ifdef MUTEX_LOCKS_AVAILABLE
4601 /*********************************************************************
4603 * Function : privoxy_mutex_lock
4605 * Description : Locks a mutex.
4608 * 1 : mutex = The mutex to lock.
4610 * Returns : Void. May exit in case of errors.
4612 *********************************************************************/
4613 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4615 #ifdef FEATURE_PTHREAD
4616 int err = pthread_mutex_lock(mutex);
4619 if (mutex != &log_mutex)
4621 log_error(LOG_LEVEL_FATAL,
4622 "Mutex locking failed: %s.\n", strerror(err));
4627 EnterCriticalSection(mutex);
4628 #endif /* def FEATURE_PTHREAD */
4632 /*********************************************************************
4634 * Function : privoxy_mutex_unlock
4636 * Description : Unlocks a mutex.
4639 * 1 : mutex = The mutex to unlock.
4641 * Returns : Void. May exit in case of errors.
4643 *********************************************************************/
4644 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4646 #ifdef FEATURE_PTHREAD
4647 int err = pthread_mutex_unlock(mutex);
4650 if (mutex != &log_mutex)
4652 log_error(LOG_LEVEL_FATAL,
4653 "Mutex unlocking failed: %s.\n", strerror(err));
4658 LeaveCriticalSection(mutex);
4659 #endif /* def FEATURE_PTHREAD */
4663 /*********************************************************************
4665 * Function : privoxy_mutex_init
4667 * Description : Prepares a mutex.
4670 * 1 : mutex = The mutex to initialize.
4672 * Returns : Void. May exit in case of errors.
4674 *********************************************************************/
4675 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4677 #ifdef FEATURE_PTHREAD
4678 int err = pthread_mutex_init(mutex, 0);
4681 printf("Fatal error. Mutex initialization failed: %s.\n",
4686 InitializeCriticalSection(mutex);
4687 #endif /* def FEATURE_PTHREAD */
4689 #endif /* def MUTEX_LOCKS_AVAILABLE */
4691 /*********************************************************************
4693 * Function : initialize_mutexes
4695 * Description : Prepares mutexes if mutex support is available.
4699 * Returns : Void, exits in case of errors.
4701 *********************************************************************/
4702 static void initialize_mutexes(void)
4704 #ifdef MUTEX_LOCKS_AVAILABLE
4706 * Prepare global mutex semaphores
4709 #ifdef FEATURE_HTTPS_INSPECTION
4710 privoxy_mutex_init(&certificate_mutex);
4711 privoxy_mutex_init(&ssl_init_mutex);
4714 privoxy_mutex_init(&log_mutex);
4715 privoxy_mutex_init(&log_init_mutex);
4716 privoxy_mutex_init(&connection_reuse_mutex);
4717 #ifdef FEATURE_EXTERNAL_FILTERS
4718 privoxy_mutex_init(&external_filter_mutex);
4720 #ifdef FEATURE_CLIENT_TAGS
4721 privoxy_mutex_init(&client_tags_mutex);
4723 #ifdef FEATURE_EXTENDED_STATISTICS
4724 privoxy_mutex_init(&filter_statistics_mutex);
4725 privoxy_mutex_init(&block_statistics_mutex);
4729 * XXX: The assumptions below are a bit naive
4730 * and can cause locks that aren't necessary.
4732 * For example older FreeBSD versions (< 6.x?)
4733 * have no gethostbyname_r, but gethostbyname is
4736 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4737 privoxy_mutex_init(&resolver_mutex);
4738 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4740 * XXX: should we use a single mutex for
4741 * localtime() and gmtime() as well?
4743 #ifndef HAVE_GMTIME_R
4744 privoxy_mutex_init(&gmtime_mutex);
4745 #endif /* ndef HAVE_GMTIME_R */
4747 #ifndef HAVE_LOCALTIME_R
4748 privoxy_mutex_init(&localtime_mutex);
4749 #endif /* ndef HAVE_GMTIME_R */
4751 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4752 privoxy_mutex_init(&rand_mutex);
4753 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4755 #endif /* def MUTEX_LOCKS_AVAILABLE */
4758 /*********************************************************************
4762 * Description : Load the config file and start the listen loop.
4763 * This function is a lot more *sane* with the `load_config'
4764 * and `listen_loop' functions; although it stills does
4765 * a *little* too much for my taste.
4768 * 1 : argc = Number of parameters (including $0).
4769 * 2 : argv = Array of (char *)'s to the parameters.
4771 * Returns : 1 if : can't open config file, unrecognized directive,
4772 * stats requested in multi-thread mode, can't open the
4773 * log file, can't open the jar file, listen port is invalid,
4774 * any load fails, and can't bind port.
4776 * Else main never returns, the process must be signaled
4777 * to terminate execution. Or, on Windows, use the
4778 * "File", "Exit" menu option.
4780 *********************************************************************/
4782 int real_main(int argc, char **argv)
4784 int main(int argc, char **argv)
4788 int do_config_test = 0;
4789 #ifndef HAVE_ARC4RANDOM
4790 unsigned int random_seed;
4793 struct passwd *pw = NULL;
4794 struct group *grp = NULL;
4796 char *pre_chroot_nslookup_to_load_resolver = NULL;
4799 char *fuzz_input_type = NULL;
4800 char *fuzz_input_file = NULL;
4807 #if !defined(_WIN32)
4814 /* Prepare mutexes if supported and necessary. */
4815 initialize_mutexes();
4817 /* Enable logging until further notice. */
4821 * Parse the command line arguments
4823 * XXX: simply printing usage information in case of
4824 * invalid arguments isn't particularly user friendly.
4826 while (++argc_pos < argc)
4829 /* Check to see if the service must be installed or uninstalled */
4830 if (strncmp(argv[argc_pos], "--install", 9) == 0)
4832 const char *pName = argv[argc_pos] + 9;
4835 exit((install_service(pName)) ? 0 : 1);
4837 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4839 const char *pName = argv[argc_pos] + 11;
4842 exit((uninstall_service(pName)) ? 0 : 1);
4844 else if (strcmp(argv[argc_pos], "--service") == 0)
4846 bRunAsService = TRUE;
4847 w32_set_service_cwd();
4848 atexit(w32_service_exit_notify);
4851 #endif /* defined(_WIN32) */
4854 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4856 if (strcmp(argv[argc_pos], "--help") == 0)
4861 else if (strcmp(argv[argc_pos], "--version") == 0)
4863 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4869 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4871 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4875 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4877 if (++argc_pos == argc) usage(argv[0]);
4878 pidfile = strdup_or_die(argv[argc_pos]);
4881 else if (strcmp(argv[argc_pos], "--user") == 0)
4886 if (++argc_pos == argc) usage(argv[argc_pos]);
4888 user_arg = strdup_or_die(argv[argc_pos]);
4889 group_name = strchr(user_arg, '.');
4890 if (NULL != group_name)
4892 /* Nul-terminate the user name */
4895 /* Skip the former delimiter to actually reach the group name */
4898 grp = getgrnam(group_name);
4901 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4904 pw = getpwnam(user_arg);
4907 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4913 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4915 if (++argc_pos == argc) usage(argv[0]);
4916 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4919 else if (strcmp(argv[argc_pos], "--chroot") == 0)
4923 #endif /* defined(unix) */
4925 else if (strcmp(argv[argc_pos], "--config-test") == 0)
4930 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4933 if (argc < argc_pos + 2) usage(argv[0]);
4934 fuzz_input_type = argv[argc_pos];
4936 fuzz_input_file = argv[argc_pos];
4938 else if (strcmp(argv[argc_pos], "--stfu") == 0)
4940 set_debug_level(LOG_LEVEL_STFU);
4943 else if (argc_pos + 1 != argc)
4946 * This is neither the last command line
4947 * option, nor was it recognized before,
4948 * therefore it must be invalid.
4954 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4956 configfile = argv[argc_pos];
4959 } /* -END- while (more arguments) */
4961 show_version(Argv[0]);
4964 if (*configfile != '/')
4966 char cwd[BUFFER_SIZE];
4968 size_t abs_file_size;
4970 /* make config-filename absolute here */
4971 if (NULL == getcwd(cwd, sizeof(cwd)))
4973 perror("failed to get current working directory");
4977 basedir = strdup_or_die(cwd);
4979 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4980 abs_file = malloc_or_die(abs_file_size);
4981 strlcpy(abs_file, basedir, abs_file_size);
4982 strlcat(abs_file, "/", abs_file_size);
4983 strlcat(abs_file, configfile, abs_file_size);
4984 configfile = abs_file;
4986 #endif /* defined unix */
4990 clients->next = NULL;
4992 /* XXX: factor out initialising after the next stable release. */
4997 #ifndef HAVE_ARC4RANDOM
4998 random_seed = (unsigned int)time(NULL);
5000 srandom(random_seed);
5003 #endif /* ifdef HAVE_RANDOM */
5004 #endif /* ifndef HAVE_ARC4RANDOM */
5007 * Unix signal handling
5009 * Catch the abort, interrupt and terminate signals for a graceful exit
5010 * Catch the hangup signal so the errlog can be reopened.
5012 * Ignore the broken pipe signal as connection failures
5013 * are handled when and where they occur without relying
5016 #if !defined(_WIN32) && !defined(__OS2__)
5019 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5021 for (idx = 0; idx < SZ(catched_signals); idx++)
5023 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5024 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5026 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5027 #endif /* ifdef sun */
5029 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5033 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5035 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5039 #else /* ifdef _WIN32 */
5040 # ifdef _WIN_CONSOLE
5042 * We *are* in a windows console app.
5043 * Print a verbose messages about FAQ's and such
5045 printf("%s", win32_blurb);
5046 # endif /* def _WIN_CONSOLE */
5047 #endif /* def _WIN32 */
5050 if (fuzz_input_type != NULL)
5052 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5054 log_error(LOG_LEVEL_FATAL,
5055 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5056 "Various data structures are static which is unsafe when using threads.");
5061 exit(NULL == load_config());
5064 /* Initialize the CGI subsystem */
5065 cgi_init_error_messages();
5068 * If running on unix and without the --no-daemon
5069 * option, become a daemon. I.e. fork, detach
5070 * from tty and get process group leadership
5079 if (pid < 0) /* error */
5084 else if (pid != 0) /* parent */
5089 * must check for errors
5090 * child died due to missing files aso
5093 wpid = waitpid(pid, &status, WNOHANG);
5105 * stderr (fd 2) will be closed later on,
5106 * when the config file has been parsed.
5112 * Reserve fd 0 and 1 to prevent abort() and friends
5113 * from sending stuff to the clients or servers.
5115 fd = open("/dev/null", O_RDONLY);
5118 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5122 if (dup2(fd, 0) == -1)
5124 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5128 fd = open("/dev/null", O_WRONLY);
5131 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5135 if (dup2(fd, 1) == -1)
5137 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5142 #ifdef FEATURE_EXTERNAL_FILTERS
5143 for (fd = 0; fd < 3; fd++)
5145 mark_socket_for_close_on_execute(fd);
5151 } /* -END- if (daemon_mode) */
5154 * As soon as we have written the PID file, we can switch
5155 * to the user and group ID indicated by the --user option
5157 if (pidfile != NULL)
5159 write_pid_file(pidfile);
5163 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5165 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5169 if (setgroups(1, &grp->gr_gid))
5171 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5174 else if (initgroups(pw->pw_name, pw->pw_gid))
5176 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5182 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5184 /* Read the time zone file from /etc before doing chroot. */
5186 if (NULL != pre_chroot_nslookup_to_load_resolver
5187 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5189 /* Initialize resolver library. */
5190 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5192 if (chroot(pw->pw_dir) < 0)
5194 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5198 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5201 if (setuid(pw->pw_uid))
5203 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5207 char putenv_dummy[64];
5209 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5210 if (putenv(putenv_dummy) != 0)
5212 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5215 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5216 if (putenv(putenv_dummy) != 0)
5218 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5224 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5227 #endif /* defined unix */
5230 /* This will be FALSE unless the command line specified --service
5234 /* Yup, so now we must attempt to establish a connection
5235 * with the service dispatcher. This will only work if this
5236 * process was launched by the service control manager to
5237 * actually run as a service. If this isn't the case, i've
5238 * known it take around 30 seconds or so for the call to return.
5241 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5242 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5244 /* Service has run, and at this point is now being stopped, so just return */
5249 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5251 /* An error occurred. Usually it's because --service was wrongly specified
5252 * and we were unable to connect to the Service Control Dispatcher because
5253 * it wasn't expecting us and is therefore not listening.
5255 * For now, just continue below to call the listen_loop function.
5258 #endif /* def _WIN32 */
5268 /*********************************************************************
5270 * Function : bind_port_helper
5272 * Description : Bind the listen port. Handles logging, and aborts
5276 * 1 : haddr = Host address to bind to. Use NULL to bind to
5278 * 2 : hport = Specifies port to bind to.
5279 * 3 : backlog = Listen backlog.
5281 * Returns : Port that was opened.
5283 *********************************************************************/
5284 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5289 result = bind_port(haddr, hport, backlog, &bfd);
5293 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5297 log_error(LOG_LEVEL_FATAL,
5298 "can't bind to %s:%d: There may be another Privoxy "
5299 "or some other proxy running on port %d",
5300 bind_address, hport, hport);
5303 log_error(LOG_LEVEL_FATAL,
5304 "can't bind to %s:%d: The hostname is not resolvable",
5305 bind_address, hport);
5308 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5309 bind_address, hport);
5312 /* shouldn't get here */
5313 return JB_INVALID_SOCKET;
5318 if (bfd >= FD_SETSIZE)
5320 log_error(LOG_LEVEL_FATAL,
5321 "Bind socket number too high to use select(): %d >= %d",
5329 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5334 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5342 /*********************************************************************
5344 * Function : bind_ports_helper
5346 * Description : Bind the listen ports. Handles logging, and aborts
5350 * 1 : config = Privoxy configuration. Specifies ports
5352 * 2 : sockets = Preallocated array of opened sockets
5353 * corresponding to specification in config.
5354 * All non-opened sockets will be set to
5355 * JB_INVALID_SOCKET.
5357 * Returns : Nothing. Inspect sockets argument.
5359 *********************************************************************/
5360 static void bind_ports_helper(struct configuration_spec * config,
5361 jb_socket sockets[])
5365 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5367 if (config->hport[i])
5369 sockets[i] = bind_port_helper(config->haddr[i],
5370 config->hport[i], config->listen_backlog);
5371 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5372 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5374 struct accept_filter_arg af_options;
5375 bzero(&af_options, sizeof(af_options));
5376 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5377 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5378 sizeof(af_options)))
5380 log_error(LOG_LEVEL_ERROR,
5381 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5388 sockets[i] = JB_INVALID_SOCKET;
5391 config->need_bind = 0;
5395 /*********************************************************************
5397 * Function : close_ports_helper
5399 * Description : Close listenings ports.
5402 * 1 : sockets = Array of opened and non-opened sockets to
5403 * close. All sockets will be set to
5404 * JB_INVALID_SOCKET.
5406 * Returns : Nothing.
5408 *********************************************************************/
5409 static void close_ports_helper(jb_socket sockets[])
5413 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5415 if (JB_INVALID_SOCKET != sockets[i])
5417 close_socket(sockets[i]);
5419 sockets[i] = JB_INVALID_SOCKET;
5425 /* Without this simple workaround we get this compiler warning from _beginthread
5426 * warning C4028: formal parameter 1 different from declaration
5428 void w32_service_listen_loop(void *p)
5432 #endif /* def _WIN32 */
5435 /*********************************************************************
5437 * Function : listen_loop
5439 * Description : bind the listen port and enter a "FOREVER" listening loop.
5445 *********************************************************************/
5446 static void listen_loop(void)
5448 struct client_states *csp_list = NULL;
5449 struct client_state *csp = NULL;
5450 jb_socket bfds[MAX_LISTENING_SOCKETS];
5451 struct configuration_spec *config;
5452 unsigned int active_threads = 0;
5453 #if defined(FEATURE_PTHREAD)
5454 pthread_attr_t attrs;
5456 pthread_attr_init(&attrs);
5457 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5460 config = load_config();
5462 #ifdef FEATURE_CONNECTION_SHARING
5464 * XXX: Should be relocated once it no
5465 * longer needs to emit log messages.
5467 initialize_reusable_connections();
5468 #endif /* def FEATURE_CONNECTION_SHARING */
5470 bind_ports_helper(config, bfds);
5472 #ifdef FEATURE_GRACEFUL_TERMINATION
5473 while (!g_terminate)
5478 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
5479 while (waitpid(-1, NULL, WNOHANG) > 0)
5481 /* zombie children */
5483 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5486 * Free data that was used by died threads
5488 active_threads = sweep();
5492 * Re-open the errlog after HUP signal
5494 if (received_hup_signal)
5496 if (NULL != config->logfile)
5498 init_error_log(Argv[0], config->logfile);
5500 received_hup_signal = 0;
5504 csp_list = zalloc_or_die(sizeof(*csp_list));
5505 csp = &csp_list->csp;
5507 log_error(LOG_LEVEL_CONNECT,
5508 "Waiting for the next client connection. Currently active threads: %d",
5512 * This config may be outdated, but for accept_connection()
5513 * it's fresh enough.
5515 csp->config = config;
5517 if (!accept_connection(csp, bfds))
5519 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5524 csp->flags |= CSP_FLAG_ACTIVE;
5525 csp->server_connection.sfd = JB_INVALID_SOCKET;
5527 csp->config = config = load_config();
5529 if (config->need_bind)
5532 * Since we were listening to the "old port", we will not see
5533 * a "listen" param change until the next request. So, at
5534 * least 1 more request must be made for us to find the new
5535 * setting. I am simply closing the old socket and binding the
5538 * Which-ever is correct, we will serve 1 more page via the
5539 * old settings. This should probably be a "show-status"
5540 * request. This should not be a so common of an operation
5541 * that this will hurt people's feelings.
5544 close_ports_helper(bfds);
5546 bind_ports_helper(config, bfds);
5549 #ifdef FEATURE_TOGGLE
5550 if (global_toggle_state)
5551 #endif /* def FEATURE_TOGGLE */
5553 csp->flags |= CSP_FLAG_TOGGLED_ON;
5556 if (run_loader(csp))
5558 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5559 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5563 if (block_acl(NULL,csp))
5565 log_error(LOG_LEVEL_CONNECT,
5566 "Connection from %s on %s (socket %d) dropped due to ACL",
5567 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5568 close_socket(csp->cfd);
5569 freez(csp->ip_addr_str);
5570 freez(csp->listen_addr_str);
5574 #endif /* def FEATURE_ACL */
5576 if ((0 != config->max_client_connections)
5577 && (active_threads >= config->max_client_connections))
5579 log_error(LOG_LEVEL_CONNECT,
5580 "Rejecting connection from %s. Maximum number of connections reached.",
5582 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5583 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5584 close_socket(csp->cfd);
5585 freez(csp->ip_addr_str);
5586 freez(csp->listen_addr_str);
5591 /* add it to the list of clients */
5592 csp_list->next = clients->next;
5593 clients->next = csp_list;
5595 if (config->multi_threaded)
5599 /* this is a switch () statement in the C preprocessor - ugh */
5600 #undef SELECTED_ONE_OPTION
5602 /* Use Pthreads in preference to native code */
5603 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5604 #define SELECTED_ONE_OPTION
5606 pthread_t the_thread;
5608 errno = pthread_create(&the_thread, &attrs,
5609 (void * (*)(void *))serve, csp);
5610 child_id = errno ? -1 : 0;
5614 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5615 #define SELECTED_ONE_OPTION
5616 child_id = _beginthread(
5617 (void (*)(void *))serve,
5622 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
5623 #define SELECTED_ONE_OPTION
5624 child_id = _beginthread(
5625 (void(* _Optlink)(void*))serve,
5631 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5632 #define SELECTED_ONE_OPTION
5634 thread_id tid = spawn_thread
5635 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5637 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5639 child_id = (int) tid;
5648 #if !defined(SELECTED_ONE_OPTION)
5651 /* This block is only needed when using fork().
5652 * When using threads, the server thread was
5653 * created and run by the call to _beginthread().
5655 if (child_id == 0) /* child */
5658 #ifdef FEATURE_TOGGLE
5659 int inherited_toggle_state = global_toggle_state;
5660 #endif /* def FEATURE_TOGGLE */
5665 * If we've been toggled or we've blocked the request, tell Mom
5668 #ifdef FEATURE_TOGGLE
5669 if (inherited_toggle_state != global_toggle_state)
5671 rc |= RC_FLAG_TOGGLED;
5673 #endif /* def FEATURE_TOGGLE */
5675 #ifdef FEATURE_STATISTICS
5676 if (csp->flags & CSP_FLAG_REJECTED)
5678 rc |= RC_FLAG_BLOCKED;
5680 #endif /* ndef FEATURE_STATISTICS */
5684 else if (child_id > 0) /* parent */
5686 /* in a fork()'d environment, the parent's
5687 * copy of the client socket and the CSP
5691 #if !defined(_WIN32) && !defined(__CYGWIN__)
5693 wait(&child_status);
5696 * Evaluate child's return code: If the child has
5697 * - been toggled, toggle ourselves
5698 * - blocked its request, bump up the stats counter
5701 #ifdef FEATURE_TOGGLE
5702 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5704 global_toggle_state = !global_toggle_state;
5706 #endif /* def FEATURE_TOGGLE */
5708 #ifdef FEATURE_STATISTICS
5710 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5714 #endif /* def FEATURE_STATISTICS */
5716 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5717 close_socket(csp->cfd);
5718 csp->flags &= ~CSP_FLAG_ACTIVE;
5722 #undef SELECTED_ONE_OPTION
5723 /* end of cpp switch () */
5728 * Spawning the child failed, assume it's because
5729 * there are too many children running already.
5730 * XXX: If you assume ...
5732 log_error(LOG_LEVEL_ERROR,
5733 "Unable to take any additional connections: %E. Active threads: %d",
5735 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5736 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5737 close_socket(csp->cfd);
5738 csp->flags &= ~CSP_FLAG_ACTIVE;
5747 #if defined(FEATURE_PTHREAD)
5748 pthread_attr_destroy(&attrs);
5751 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5753 #ifdef FEATURE_HTTPS_INSPECTION
5754 /* Clean up. Aim: free all memory (no leaks) */
5758 #ifdef FEATURE_GRACEFUL_TERMINATION
5760 log_error(LOG_LEVEL_INFO, "Graceful termination requested");
5762 unload_current_config_file();
5763 unload_current_actions_file();
5764 unload_current_re_filterfile();
5765 #ifdef FEATURE_TRUST
5766 unload_current_trust_file();
5769 if (config->multi_threaded)
5776 } while ((clients->next != NULL) && (--i > 0));
5780 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5790 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5791 /* Cleanup - remove taskbar icon etc. */
5796 #endif /* FEATURE_GRACEFUL_TERMINATION */