1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
5 * Purpose : Main file. Contains main() method, main loop, and
6 * the main connection-handling function.
8 * Copyright : Written by and Copyright (C) 2001-2020 the
9 * Privoxy team. https://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
66 # include <sys/wait.h>
67 # include <sys/time.h>
68 # include <sys/stat.h>
69 # include <sys/ioctl.h>
72 #include <sys/termios.h>
83 # include <socket.h> /* BeOS has select() for sockets only. */
84 # include <OS.h> /* declarations for threads and stuff. */
92 #endif /* def __GLIBC__ */
93 #endif /* HAVE_POLL */
100 #ifdef FEATURE_HTTPS_INSPECTION
106 #include "miscutil.h"
108 #include "jbsockets.h"
113 #include "urlmatch.h"
114 #ifdef FEATURE_CLIENT_TAGS
115 #include "client-tags.h"
119 struct client_states clients[1];
120 struct file_list files[1];
122 #ifdef FEATURE_STATISTICS
123 int urls_read = 0; /* total nr of urls read inc rejected */
124 int urls_rejected = 0; /* total nr of urls rejected */
125 #endif /* def FEATURE_STATISTICS */
127 #ifdef FEATURE_GRACEFUL_TERMINATION
132 static void sig_handler(int the_signal);
134 static int client_protocol_is_unsupported(struct client_state *csp, char *req);
135 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
136 static jb_err get_server_headers(struct client_state *csp);
137 static const char *crunch_reason(const struct http_response *rsp);
138 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
139 static char *get_request_line(struct client_state *csp);
140 static jb_err receive_client_request(struct client_state *csp);
141 static jb_err parse_client_request(struct client_state *csp);
142 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
143 static jb_err change_request_destination(struct client_state *csp);
144 static void handle_established_connection(struct client_state *csp);
145 static void chat(struct client_state *csp);
146 static void serve(struct client_state *csp);
147 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
148 static void usage(const char *myname);
150 static void initialize_mutexes(void);
151 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
152 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
153 static void close_ports_helper(jb_socket sockets[]);
154 static void listen_loop(void);
155 static void serve(struct client_state *csp);
158 static int32 server_thread(void *data);
159 #endif /* def __BEOS__ */
162 #define sleep(N) Sleep(((N) * 1000))
166 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
167 void show_fuzz_usage(const char *name);
170 #ifdef MUTEX_LOCKS_AVAILABLE
172 * XXX: Does the locking stuff really belong in this file?
174 privoxy_mutex_t log_mutex;
175 privoxy_mutex_t log_init_mutex;
176 privoxy_mutex_t connection_reuse_mutex;
178 #ifdef FEATURE_HTTPS_INSPECTION
179 privoxy_mutex_t certificate_mutex;
180 privoxy_mutex_t ssl_init_mutex;
183 #ifdef FEATURE_EXTERNAL_FILTERS
184 privoxy_mutex_t external_filter_mutex;
186 #ifdef FEATURE_CLIENT_TAGS
187 privoxy_mutex_t client_tags_mutex;
189 #ifdef FEATURE_EXTENDED_STATISTICS
190 privoxy_mutex_t filter_statistics_mutex;
191 privoxy_mutex_t block_statistics_mutex;
194 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
195 privoxy_mutex_t resolver_mutex;
196 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
198 #ifndef HAVE_GMTIME_R
199 privoxy_mutex_t gmtime_mutex;
200 #endif /* ndef HAVE_GMTIME_R */
202 #ifndef HAVE_LOCALTIME_R
203 privoxy_mutex_t localtime_mutex;
204 #endif /* ndef HAVE_GMTIME_R */
206 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
207 privoxy_mutex_t rand_mutex;
208 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
210 #endif /* def MUTEX_LOCKS_AVAILABLE */
213 const char *basedir = NULL;
214 const char *pidfile = NULL;
215 static int received_hup_signal = 0;
216 #endif /* defined unix */
218 /* HTTP snipplets. */
219 static const char CSUCCEED[] =
220 "HTTP/1.1 200 Connection established\r\n\r\n";
222 static const char CHEADER[] =
223 "HTTP/1.1 400 Invalid header received from client\r\n"
224 "Content-Type: text/plain\r\n"
225 "Connection: close\r\n\r\n"
226 "Invalid header received from client.\r\n";
228 static const char FTP_RESPONSE[] =
229 "HTTP/1.1 400 Invalid request received from client\r\n"
230 "Content-Type: text/plain\r\n"
231 "Connection: close\r\n\r\n"
232 "Invalid request. Privoxy doesn't support FTP.\r\n";
234 static const char GOPHER_RESPONSE[] =
235 "HTTP/1.1 400 Invalid request received from client\r\n"
236 "Content-Type: text/plain\r\n"
237 "Connection: close\r\n\r\n"
238 "Invalid request. Privoxy doesn't support gopher.\r\n";
240 /* XXX: should be a template */
241 static const char MISSING_DESTINATION_RESPONSE[] =
242 "HTTP/1.1 400 Bad request received from client\r\n"
243 "Content-Type: text/plain\r\n"
244 "Connection: close\r\n\r\n"
245 "Bad request. Privoxy was unable to extract the destination.\r\n";
247 /* XXX: should be a template */
248 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
249 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
250 "Content-Type: text/plain\r\n"
251 "Connection: close\r\n\r\n"
252 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
254 /* XXX: should be a template */
255 static const char MESSED_UP_REQUEST_RESPONSE[] =
256 "HTTP/1.1 400 Malformed request after rewriting\r\n"
257 "Content-Type: text/plain\r\n"
258 "Connection: close\r\n\r\n"
259 "Bad request. Messed up with header filters.\r\n";
261 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
262 "HTTP/1.1 503 Too many open connections\r\n"
263 "Content-Type: text/plain\r\n"
264 "Connection: close\r\n\r\n"
265 "Maximum number of open connections reached.\r\n";
267 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
268 "HTTP/1.1 504 Connection timeout\r\n"
269 "Content-Type: text/plain\r\n"
270 "Connection: close\r\n\r\n"
271 "The connection timed out because the client request didn't arrive in time.\r\n";
273 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
274 "HTTP/1.1 400 Failed reading client body\r\n"
275 "Content-Type: text/plain\r\n"
276 "Connection: close\r\n\r\n"
277 "Failed parsing or buffering the chunk-encoded client body.\r\n";
279 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
280 "HTTP/1.1 417 Expecting too much\r\n"
281 "Content-Type: text/plain\r\n"
282 "Connection: close\r\n\r\n"
283 "Privoxy detected an unsupported Expect header value.\r\n";
285 /* A function to crunch a response */
286 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
288 /* Crunch function flags */
289 #define CF_NO_FLAGS 0
290 /* Cruncher applies to forced requests as well */
291 #define CF_IGNORE_FORCE 1
292 /* Crunched requests are counted for the block statistics */
293 #define CF_COUNT_AS_REJECT 2
295 /* A crunch function and its flags */
298 const crunch_func_ptr cruncher;
302 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
304 /* Complete list of cruncher functions */
305 static const struct cruncher crunchers_all[] = {
306 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
307 { block_url, CF_COUNT_AS_REJECT },
309 { trust_url, CF_COUNT_AS_REJECT },
310 #endif /* def FEATURE_TRUST */
311 { redirect_url, CF_NO_FLAGS },
312 { dispatch_cgi, CF_IGNORE_FORCE},
316 /* Light version, used after tags are applied */
317 static const struct cruncher crunchers_light[] = {
318 { block_url, CF_COUNT_AS_REJECT },
319 { redirect_url, CF_NO_FLAGS },
325 * XXX: Don't we really mean
332 /*********************************************************************
334 * Function : sig_handler
336 * Description : Signal handler for different signals.
337 * Exit gracefully on TERM and INT
338 * or set a flag that will cause the errlog
339 * to be reopened by the main thread on HUP.
342 * 1 : the_signal = the signal cause this function to call
346 *********************************************************************/
347 static void sig_handler(int the_signal)
353 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
365 received_hup_signal = 1;
371 * We shouldn't be here, unless we catch signals
372 * in main() that we can't handle here!
374 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
382 /*********************************************************************
384 * Function : get_write_delay
386 * Description : Parse the delay-response parameter.
389 * 1 : csp = Current client state (buffers, headers, etc...)
391 * Returns : Number of milliseconds to delay writes.
393 *********************************************************************/
394 static unsigned int get_write_delay(const struct client_state *csp)
400 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
404 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
406 delay = (unsigned)strtol(newval, &endptr, 0);
409 log_error(LOG_LEVEL_FATAL,
410 "Invalid delay-response{} parameter: '%s'", newval);
418 /*********************************************************************
420 * Function : client_protocol_is_unsupported
422 * Description : Checks if the client used a known unsupported
423 * protocol and deals with it by sending an error
427 * 1 : csp = Current client state (buffers, headers, etc...)
428 * 2 : req = the first request line send by the client
430 * Returns : TRUE if an error response has been generated, or
431 * FALSE if the request doesn't look invalid.
433 *********************************************************************/
434 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
437 * If it's a FTP or gopher request, we don't support it.
439 * These checks are better than nothing, but they might
440 * not work in all configurations and some clients might
441 * have problems digesting the answer.
443 * They should, however, never cause more problems than
444 * Privoxy's old behaviour (returning the misleading HTML
447 * "Could not resolve http://(ftp|gopher)://example.org").
449 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
451 const char *response = NULL;
452 const char *protocol = NULL;
454 if (!strncmpic(req, "GET ftp://", 10))
456 response = FTP_RESPONSE;
461 response = GOPHER_RESPONSE;
464 log_error(LOG_LEVEL_ERROR,
465 "%s tried to use Privoxy as %s proxy: %s",
466 csp->ip_addr_str, protocol, req);
467 log_error(LOG_LEVEL_CLF,
468 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
471 #ifdef FEATURE_HTTPS_INSPECTION
472 if (client_use_ssl(csp))
474 ssl_send_data_delayed(&(csp->ssl_client_attr),
475 (const unsigned char *)response, strlen(response),
476 get_write_delay(csp));
481 write_socket_delayed(csp->cfd, response, strlen(response),
482 get_write_delay(csp));
492 /*********************************************************************
494 * Function : client_has_unsupported_expectations
496 * Description : Checks if the client used an unsupported expectation
497 * in which case an error message is delivered.
500 * 1 : csp = Current client state (buffers, headers, etc...)
502 * Returns : TRUE if an error response has been generated, or
503 * FALSE if the request doesn't look invalid.
505 *********************************************************************/
506 static int client_has_unsupported_expectations(const struct client_state *csp)
508 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
510 log_error(LOG_LEVEL_ERROR,
511 "Rejecting request from client %s with unsupported Expect header value",
513 log_error(LOG_LEVEL_CLF,
514 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
515 write_socket_delayed(csp->cfd,
516 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
517 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
518 get_write_delay(csp));
528 /*********************************************************************
530 * Function : get_request_destination_elsewhere
532 * Description : If the client's request was redirected into
533 * Privoxy without the client's knowledge,
534 * the request line lacks the destination host.
536 * This function tries to get it elsewhere,
537 * provided accept-intercepted-requests is enabled.
539 * "Elsewhere" currently only means "Host: header",
540 * but in the future we may ask the redirecting
541 * packet filter to look the destination up.
543 * If the destination stays unknown, an error
544 * response is send to the client and headers
545 * are freed so that chat() can return directly.
548 * 1 : csp = Current client state (buffers, headers, etc...)
549 * 2 : headers = a header list
551 * Returns : JB_ERR_OK if the destination is now known, or
552 * JB_ERR_PARSE if it isn't.
554 *********************************************************************/
555 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
557 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
559 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
560 " Privoxy isn't configured to accept intercepted requests.",
561 csp->ip_addr_str, csp->http->cmd);
562 /* XXX: Use correct size */
563 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
564 csp->ip_addr_str, csp->http->cmd);
566 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
567 get_write_delay(csp));
568 destroy_list(headers);
572 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
574 /* Split the domain we just got for pattern matching */
575 init_domain_components(csp->http);
581 /* We can't work without destination. Go spread the news.*/
583 /* XXX: Use correct size */
584 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
585 csp->ip_addr_str, csp->http->cmd);
586 log_error(LOG_LEVEL_ERROR,
587 "Privoxy was unable to get the destination for %s's request: %s",
588 csp->ip_addr_str, csp->http->cmd);
590 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
591 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
592 destroy_list(headers);
597 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
598 * to get the destination IP address, use it as host directly
599 * or do a reverse DNS lookup first.
604 /*********************************************************************
606 * Function : get_server_headers
608 * Description : Parses server headers in iob and fills them
609 * into csp->headers so that they can later be
613 * 1 : csp = Current client state (buffers, headers, etc...)
615 * Returns : JB_ERR_OK if everything went fine, or
616 * JB_ERR_PARSE if the headers were incomplete.
618 *********************************************************************/
619 static jb_err get_server_headers(struct client_state *csp)
621 int continue_hack_in_da_house = 0;
624 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
629 * continue hack in da house. Ignore the ending of
630 * this head and continue enlisting header lines.
631 * The reason is described below.
633 enlist(csp->headers, "");
634 continue_hack_in_da_house = 0;
637 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
640 * It's a bodyless continue response, don't
641 * stop header parsing after reaching its end.
643 * As a result Privoxy will concatenate the
644 * next response's head and parse and deliver
645 * the headers as if they belonged to one request.
647 * The client will separate them because of the
648 * empty line between them.
650 * XXX: What we're doing here is clearly against
651 * the intended purpose of the continue header,
652 * and under some conditions (HTTP/1.0 client request)
653 * it's a standard violation.
655 * Anyway, "sort of against the spec" is preferable
656 * to "always getting confused by Continue responses"
657 * (Privoxy's behaviour before this hack was added)
659 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
660 continue_hack_in_da_house = 1;
662 else if (*header == '\0')
665 * If the header is empty, but the Continue hack
666 * isn't active, we can assume that we reached the
667 * end of the buffer before we hit the end of the
670 * Inform the caller an let it decide how to handle it.
675 if (JB_ERR_MEMORY == enlist(csp->headers, header))
678 * XXX: Should we quit the request and return a
679 * out of memory error page instead?
681 log_error(LOG_LEVEL_ERROR,
682 "Out of memory while enlisting server headers. %s lost.",
692 /*********************************************************************
694 * Function : crunch_reason
696 * Description : Translates the crunch reason code into a string.
699 * 1 : rsp = a http_response
701 * Returns : A string with the crunch reason or an error description.
703 *********************************************************************/
704 static const char *crunch_reason(const struct http_response *rsp)
706 char * reason = NULL;
711 return "Internal error while searching for crunch reason";
714 switch (rsp->crunch_reason)
717 reason = "Unsupported HTTP feature";
723 reason = "Untrusted";
726 reason = "Redirected";
732 reason = "DNS failure";
734 case FORWARDING_FAILED:
735 reason = "Forwarding failed";
738 reason = "Connection failure";
741 reason = "Out of memory (may mask other reasons)";
743 case CONNECTION_TIMEOUT:
744 reason = "Connection timeout";
747 reason = "No server data received";
750 reason = "No reason recorded";
758 /*********************************************************************
760 * Function : log_applied_actions
762 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
766 * 1 : actions = Current action spec to log
770 *********************************************************************/
771 static void log_applied_actions(const struct current_action_spec *actions)
774 * The conversion to text requires lots of memory allocations so
775 * we only do the conversion if the user is actually interested.
777 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
779 char *actions_as_text = actions_to_line_of_text(actions);
780 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
781 freez(actions_as_text);
786 /*********************************************************************
788 * Function : send_crunch_response
790 * Description : Delivers already prepared response for
791 * intercepted requests, logs the interception
792 * and frees the response.
795 * 1 : csp = Current client state (buffers, headers, etc...)
796 * 2 : rsp = Fully prepared response. Will be freed on exit.
800 *********************************************************************/
801 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
803 const struct http_request *http = csp->http;
807 assert(rsp->head != NULL);
811 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
815 * Extract the status code from the actual head
816 * that will be send to the client. It is the only
817 * way to get it right for all requests, including
818 * the fixed ones for out-of-memory problems.
820 * A head starts like this: 'HTTP/1.1 200...'
824 status_code[0] = rsp->head[9];
825 status_code[1] = rsp->head[10];
826 status_code[2] = rsp->head[11];
827 status_code[3] = '\0';
829 /* Log that the request was crunched and why. */
830 log_applied_actions(csp->action);
831 #ifdef FEATURE_HTTPS_INSPECTION
832 if (client_use_ssl(csp))
834 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
835 http->hostport, http->path);
836 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
837 csp->ip_addr_str, http->gpc, http->hostport, http->path,
838 http->version, status_code, rsp->content_length);
843 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
844 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
845 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
847 /* Write the answer to the client */
848 #ifdef FEATURE_HTTPS_INSPECTION
849 if (client_use_ssl(csp))
851 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
852 (const unsigned char *)rsp->head, rsp->head_length,
853 get_write_delay(csp)) < 0)
854 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
855 (const unsigned char *)rsp->body, rsp->content_length,
856 get_write_delay(csp)) < 0))
858 /* There is nothing we can do about it. */
859 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
860 "for https://%s%s through client socket %d using TLS/SSL",
861 http->hostport, http->url, csp->cfd);
867 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
868 get_write_delay(csp))
869 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
870 get_write_delay(csp)))
872 /* There is nothing we can do about it. */
873 log_error(LOG_LEVEL_CONNECT,
874 "Couldn't deliver the error message for %s through client socket %d: %E",
875 http->url, csp->cfd);
879 /* Clean up and return */
880 if (cgi_error_memory() != rsp)
882 free_http_response(rsp);
888 /*********************************************************************
890 * Function : crunch_response_triggered
892 * Description : Checks if the request has to be crunched,
893 * and delivers the crunch response if necessary.
896 * 1 : csp = Current client state (buffers, headers, etc...)
897 * 2 : crunchers = list of cruncher functions to run
899 * Returns : TRUE if the request was answered with a crunch response
902 *********************************************************************/
903 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
905 struct http_response *rsp = NULL;
906 const struct cruncher *c;
909 * If CGI request crunching is disabled,
910 * check the CGI dispatcher out of order to
911 * prevent unintentional blocks or redirects.
913 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
914 && (NULL != (rsp = dispatch_cgi(csp))))
916 /* Deliver, log and free the interception response. */
917 send_crunch_response(csp, rsp);
918 csp->flags |= CSP_FLAG_CRUNCHED;
922 for (c = crunchers; c->cruncher != NULL; c++)
925 * Check the cruncher if either Privoxy is toggled
926 * on and the request isn't forced, or if the cruncher
927 * applies to forced requests as well.
929 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
930 !(csp->flags & CSP_FLAG_FORCED)) ||
931 (c->flags & CF_IGNORE_FORCE))
933 rsp = c->cruncher(csp);
936 /* Deliver, log and free the interception response. */
937 send_crunch_response(csp, rsp);
938 csp->flags |= CSP_FLAG_CRUNCHED;
939 #ifdef FEATURE_STATISTICS
940 if (c->flags & CF_COUNT_AS_REJECT)
942 csp->flags |= CSP_FLAG_REJECTED;
944 #endif /* def FEATURE_STATISTICS */
955 /*********************************************************************
957 * Function : build_request_line
959 * Description : Builds the HTTP request line.
961 * If a HTTP forwarder is used it expects the whole URL,
962 * web servers only get the path.
965 * 1 : csp = Current client state (buffers, headers, etc...)
966 * 2 : fwd = The forwarding spec used for the request
967 * XXX: Should use http->fwd instead.
968 * 3 : request_line = The old request line which will be replaced.
970 * Returns : Nothing. Terminates in case of memory problems.
972 *********************************************************************/
973 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
975 struct http_request *http = csp->http;
978 * Downgrade http version from 1.1 to 1.0
979 * if +downgrade action applies.
981 if ((csp->action->flags & ACTION_DOWNGRADE)
982 && (!strcmpic(http->version, "HTTP/1.1")))
984 freez(http->version);
985 http->version = strdup_or_die("HTTP/1.0");
989 * Rebuild the request line.
991 freez(*request_line);
992 *request_line = strdup(http->gpc);
993 string_append(request_line, " ");
995 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
997 string_append(request_line, http->url);
1001 string_append(request_line, http->path);
1003 string_append(request_line, " ");
1004 string_append(request_line, http->version);
1006 if (*request_line == NULL)
1008 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1010 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1014 /*********************************************************************
1016 * Function : change_request_destination
1018 * Description : Parse a (rewritten) request line and regenerate
1019 * the http request data.
1022 * 1 : csp = Current client state (buffers, headers, etc...)
1024 * Returns : Forwards the parse_http_request() return code.
1025 * Terminates in case of memory problems.
1027 *********************************************************************/
1028 static jb_err change_request_destination(struct client_state *csp)
1030 struct http_request *http = csp->http;
1033 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1034 csp->headers->first->str);
1035 free_http_request(http);
1036 err = parse_http_request(csp->headers->first->str, http);
1037 if (JB_ERR_OK != err)
1039 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1040 jb_err_to_string(err));
1047 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1048 /*********************************************************************
1050 * Function : server_response_is_complete
1052 * Description : Determines whether we should stop reading
1053 * from the server socket.
1056 * 1 : csp = Current client state (buffers, headers, etc...)
1057 * 2 : content_length = Length of content received so far.
1059 * Returns : TRUE if the response is complete,
1062 *********************************************************************/
1063 static int server_response_is_complete(struct client_state *csp,
1064 unsigned long long content_length)
1066 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1068 if (!strcmpic(csp->http->gpc, "HEAD"))
1071 * "HEAD" implies no body, we are thus expecting
1072 * no content. XXX: incomplete "list" of methods?
1074 csp->expected_content_length = 0;
1075 content_length_known = TRUE;
1076 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1079 if (csp->http->status == 204 || csp->http->status == 304)
1082 * Expect no body. XXX: incomplete "list" of status codes?
1084 csp->expected_content_length = 0;
1085 content_length_known = TRUE;
1086 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1089 return (content_length_known && ((0 == csp->expected_content_length)
1090 || (csp->expected_content_length <= content_length)));
1094 #ifdef FEATURE_CONNECTION_SHARING
1095 /*********************************************************************
1097 * Function : wait_for_alive_connections
1099 * Description : Waits for alive connections to timeout.
1105 *********************************************************************/
1106 static void wait_for_alive_connections(void)
1108 int connections_alive = close_unusable_connections();
1110 while (0 < connections_alive)
1112 log_error(LOG_LEVEL_CONNECT,
1113 "Waiting for %d connections to timeout.",
1116 connections_alive = close_unusable_connections();
1119 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1122 #endif /* def FEATURE_CONNECTION_SHARING */
1125 /*********************************************************************
1127 * Function : save_connection_destination
1129 * Description : Remembers a connection for reuse later on.
1132 * 1 : sfd = Open socket to remember.
1133 * 2 : http = The destination for the connection.
1134 * 3 : fwd = The forwarder settings used.
1135 * 4 : server_connection = storage.
1139 *********************************************************************/
1140 void save_connection_destination(jb_socket sfd,
1141 const struct http_request *http,
1142 const struct forward_spec *fwd,
1143 struct reusable_connection *server_connection)
1145 assert(sfd != JB_INVALID_SOCKET);
1146 assert(NULL != http->host);
1148 server_connection->sfd = sfd;
1149 server_connection->host = strdup_or_die(http->host);
1150 server_connection->port = http->port;
1152 assert(NULL != fwd);
1153 assert(server_connection->gateway_host == NULL);
1154 assert(server_connection->gateway_port == 0);
1155 assert(server_connection->forwarder_type == 0);
1156 assert(server_connection->forward_host == NULL);
1157 assert(server_connection->forward_port == 0);
1159 server_connection->forwarder_type = fwd->type;
1160 if (NULL != fwd->gateway_host)
1162 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1166 server_connection->gateway_host = NULL;
1168 server_connection->gateway_port = fwd->gateway_port;
1169 if (NULL != fwd->auth_username)
1171 server_connection->auth_username = strdup_or_die(fwd->auth_username);
1175 server_connection->auth_username = NULL;
1177 if (NULL != fwd->auth_password)
1179 server_connection->auth_password = strdup_or_die(fwd->auth_password);
1183 server_connection->auth_password = NULL;
1186 if (NULL != fwd->forward_host)
1188 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1192 server_connection->forward_host = NULL;
1194 server_connection->forward_port = fwd->forward_port;
1196 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1199 /*********************************************************************
1201 * Function : verify_request_length
1203 * Description : Checks if we already got the whole client requests
1204 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1207 * Data that doesn't belong to the current request is
1208 * either thrown away to let the client retry on a clean
1209 * socket, or stashed to be dealt with after the current
1210 * request is served.
1213 * 1 : csp = Current client state (buffers, headers, etc...)
1217 *********************************************************************/
1218 static void verify_request_length(struct client_state *csp)
1220 unsigned long long buffered_request_bytes =
1221 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1223 if ((csp->expected_client_content_length != 0)
1224 && (buffered_request_bytes != 0))
1226 if (csp->expected_client_content_length >= buffered_request_bytes)
1228 csp->expected_client_content_length -= buffered_request_bytes;
1229 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1230 "to account for the %llu ones we already got.",
1231 csp->expected_client_content_length, buffered_request_bytes);
1235 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1236 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1237 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1238 "Marking the server socket tainted after throwing %llu bytes away.",
1239 buffered_request_bytes - csp->expected_client_content_length);
1240 csp->expected_client_content_length = 0;
1241 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1244 if (csp->expected_client_content_length == 0)
1246 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1250 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1251 && ((csp->client_iob->cur < csp->client_iob->eod)
1252 || (csp->expected_client_content_length != 0)))
1254 if (strcmpic(csp->http->gpc, "GET")
1255 && strcmpic(csp->http->gpc, "HEAD")
1256 && strcmpic(csp->http->gpc, "TRACE")
1257 && strcmpic(csp->http->gpc, "OPTIONS")
1258 && strcmpic(csp->http->gpc, "DELETE"))
1260 /* XXX: this is an incomplete hack */
1261 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1262 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1266 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1268 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1270 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1271 log_error(LOG_LEVEL_CONNECT,
1272 "Possible pipeline attempt detected. The connection will not "
1273 "be kept alive and we will only serve the first request.");
1274 /* Nuke the pipelined requests from orbit, just to be sure. */
1275 clear_iob(csp->client_iob);
1280 * Keep the pipelined data around for now, we'll deal with
1281 * it once we're done serving the current request.
1283 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1284 assert(csp->client_iob->eod >= csp->client_iob->cur);
1285 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1286 "%d bytes of pipelined data received.",
1287 (int)(csp->client_iob->eod - csp->client_iob->cur));
1293 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1294 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1299 /*********************************************************************
1301 * Function : mark_server_socket_tainted
1303 * Description : Makes sure we don't reuse a server socket
1304 * (if we didn't read everything the server sent
1305 * us reusing the socket would lead to garbage).
1308 * 1 : csp = Current client state (buffers, headers, etc...)
1312 *********************************************************************/
1313 static void mark_server_socket_tainted(struct client_state *csp)
1316 * For consistency we always mark the server socket
1317 * tainted, however, to reduce the log noise we only
1318 * emit a log message if the server socket could have
1319 * actually been reused.
1321 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1322 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1324 log_error(LOG_LEVEL_CONNECT,
1325 "Marking the server socket %d tainted.",
1326 csp->server_connection.sfd);
1328 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1331 /*********************************************************************
1333 * Function : get_request_line
1335 * Description : Read the client request line.
1338 * 1 : csp = Current client state (buffers, headers, etc...)
1340 * Returns : Pointer to request line or NULL in case of errors.
1342 *********************************************************************/
1343 static char *get_request_line(struct client_state *csp)
1345 char buf[BUFFER_SIZE];
1346 char *request_line = NULL;
1349 memset(buf, 0, sizeof(buf));
1351 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1354 * If there are multiple pipelined requests waiting,
1355 * the flag will be set again once the next request
1358 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1360 request_line = get_header(csp->client_iob);
1361 if ((NULL != request_line) && ('\0' != *request_line))
1363 return request_line;
1367 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1368 "received yet. Continuing reading from %d.", csp->cfd);
1376 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1378 !data_is_available(csp->cfd, csp->config->socket_timeout)
1381 if (socket_is_still_alive(csp->cfd))
1383 log_error(LOG_LEVEL_CONNECT,
1384 "No request line on socket %d received in time. Timeout: %d.",
1385 csp->cfd, csp->config->socket_timeout);
1386 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1387 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1388 get_write_delay(csp));
1392 log_error(LOG_LEVEL_CONNECT,
1393 "The client side of the connection on socket %d got "
1394 "closed without sending a complete request line.", csp->cfd);
1399 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1401 if (len <= 0) return NULL;
1404 * If there is no memory left for buffering the
1405 * request, there is nothing we can do but hang up
1407 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1412 request_line = get_header(csp->client_iob);
1414 } while ((NULL != request_line) && ('\0' == *request_line));
1416 return request_line;
1422 CHUNK_STATUS_MISSING_DATA,
1423 CHUNK_STATUS_BODY_COMPLETE,
1424 CHUNK_STATUS_PARSE_ERROR
1428 /*********************************************************************
1430 * Function : chunked_body_is_complete
1432 * Description : Figures out whether or not a chunked body is complete.
1434 * Currently it always starts at the beginning of the
1435 * buffer which is somewhat wasteful and prevents Privoxy
1436 * from starting to forward the correctly parsed chunks
1437 * as soon as theoretically possible.
1439 * Should be modified to work with a common buffer,
1440 * and allow the caller to skip already parsed chunks.
1442 * This would allow the function to be used for unbuffered
1443 * response bodies as well.
1446 * 1 : iob = Buffer with the body to check.
1447 * 2 : length = Length of complete body
1449 * Returns : Enum with the result of the check.
1451 *********************************************************************/
1452 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1454 unsigned int chunksize;
1460 * We need at least a single digit, followed by "\r\n",
1461 * followed by an unknown amount of data, followed by "\r\n".
1463 if (p + 5 > iob->eod)
1465 return CHUNK_STATUS_MISSING_DATA;
1467 if (sscanf(p, "%x", &chunksize) != 1)
1469 return CHUNK_STATUS_PARSE_ERROR;
1473 * We want at least a single digit, followed by "\r\n",
1474 * followed by the specified amount of data, followed by "\r\n".
1476 if (p + chunksize + 5 > iob->eod)
1478 return CHUNK_STATUS_MISSING_DATA;
1481 /* Skip chunk-size. */
1482 p = strstr(p, "\r\n");
1485 return CHUNK_STATUS_PARSE_ERROR;
1487 /* Move beyond the chunkdata. */
1490 /* There should be another "\r\n" to skip */
1491 if (memcmp(p, "\r\n", 2))
1493 return CHUNK_STATUS_PARSE_ERROR;
1496 } while (chunksize > 0U);
1498 *length = (size_t)(p - iob->cur);
1499 assert(*length <= (size_t)(iob->eod - iob->cur));
1500 assert(p <= iob->eod);
1502 return CHUNK_STATUS_BODY_COMPLETE;
1507 /*********************************************************************
1509 * Function : receive_chunked_client_request_body
1511 * Description : Read the chunk-encoded client request body.
1512 * Failures are dealt with.
1515 * 1 : csp = Current client state (buffers, headers, etc...)
1517 * Returns : JB_ERR_OK or JB_ERR_PARSE
1519 *********************************************************************/
1520 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1523 enum chunk_status status;
1525 while (CHUNK_STATUS_MISSING_DATA ==
1526 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1528 char buf[BUFFER_SIZE];
1531 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1533 log_error(LOG_LEVEL_ERROR,
1534 "Timeout while waiting for the client body.");
1537 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1540 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1543 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1548 if (status != CHUNK_STATUS_BODY_COMPLETE)
1550 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1551 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1552 log_error(LOG_LEVEL_CLF,
1553 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1554 return JB_ERR_PARSE;
1556 log_error(LOG_LEVEL_CONNECT,
1557 "Chunked client body completely read. Length: %lu", body_length);
1558 csp->expected_client_content_length = body_length;
1566 /*********************************************************************
1568 * Function : fuzz_chunked_transfer_encoding
1570 * Description : Treat the fuzzed input as chunked transfer encoding
1571 * to check and dechunk.
1574 * 1 : csp = Used to store the data.
1575 * 2 : fuzz_input_file = File to read the input from.
1577 * Returns : Result of dechunking
1579 *********************************************************************/
1580 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1583 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1584 enum chunk_status status;
1586 status = chunked_body_is_complete(csp->iob, &length);
1587 if (CHUNK_STATUS_BODY_COMPLETE != status)
1589 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1592 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1597 /*********************************************************************
1599 * Function : fuzz_client_request
1601 * Description : Try to get a client request from the fuzzed input.
1604 * 1 : csp = Current client state (buffers, headers, etc...)
1605 * 2 : fuzz_input_file = File to read the input from.
1607 * Returns : Result of fuzzing.
1609 *********************************************************************/
1610 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1615 csp->ip_addr_str = "fuzzer";
1617 if (strcmp(fuzz_input_file, "-") != 0)
1619 log_error(LOG_LEVEL_FATAL,
1620 "Fuzzed client requests can currently only be read from stdin (-).");
1622 err = receive_client_request(csp);
1623 if (err != JB_ERR_OK)
1627 err = parse_client_request(csp);
1628 if (err != JB_ERR_OK)
1636 #endif /* def FUZZ */
1639 #ifdef FEATURE_FORCE_LOAD
1640 /*********************************************************************
1642 * Function : force_required
1644 * Description : Checks a request line to see if it contains
1645 * the FORCE_PREFIX. If it does, it is removed
1646 * unless enforcing requests has beend disabled.
1649 * 1 : request_line = HTTP request line
1651 * Returns : TRUE if force is required, FALSE otherwise.
1653 *********************************************************************/
1654 static int force_required(const struct client_state *csp, char *request_line)
1658 p = strstr(request_line, "http://");
1662 p += strlen("http://");
1666 /* Intercepted request usually don't specify the protocol. */
1670 /* Go to the beginning of the path */
1675 * If the path is missing the request line is invalid and we
1676 * are done here. The client-visible rejection happens later on.
1681 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1683 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1685 /* XXX: Should clean more carefully */
1686 strclean(request_line, FORCE_PREFIX);
1687 log_error(LOG_LEVEL_FORCE,
1688 "Enforcing request: \"%s\".", request_line);
1692 log_error(LOG_LEVEL_FORCE,
1693 "Ignored force prefix in request: \"%s\".", request_line);
1699 #endif /* def FEATURE_FORCE_LOAD */
1702 /*********************************************************************
1704 * Function : receive_client_request
1706 * Description : Read the client's request (more precisely the
1707 * client headers) and answer it if necessary.
1710 * 1 : csp = Current client state (buffers, headers, etc...)
1712 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1714 *********************************************************************/
1715 static jb_err receive_client_request(struct client_state *csp)
1717 char buf[BUFFER_SIZE];
1720 struct http_request *http;
1724 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1725 struct list header_list;
1726 struct list *headers = &header_list;
1728 /* We don't care if the arriving data is a valid HTTP request or not. */
1729 csp->requests_received_total++;
1733 memset(buf, 0, sizeof(buf));
1735 req = get_request_line(csp);
1738 mark_server_socket_tainted(csp);
1739 return JB_ERR_PARSE;
1741 assert(*req != '\0');
1743 if (client_protocol_is_unsupported(csp, req))
1745 return JB_ERR_PARSE;
1748 #ifdef FEATURE_FORCE_LOAD
1749 if (force_required(csp, req))
1751 csp->flags |= CSP_FLAG_FORCED;
1753 #endif /* def FEATURE_FORCE_LOAD */
1755 err = parse_http_request(req, http);
1757 if (JB_ERR_OK != err)
1759 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1760 get_write_delay(csp));
1761 /* XXX: Use correct size */
1762 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1763 log_error(LOG_LEVEL_ERROR,
1764 "Couldn't parse request line received from %s: %s",
1765 csp->ip_addr_str, jb_err_to_string(err));
1767 free_http_request(http);
1768 return JB_ERR_PARSE;
1771 /* grab the rest of the client's headers */
1775 p = get_header(csp->client_iob);
1779 /* There are no additional headers to read. */
1786 * We didn't receive a complete header
1787 * line yet, get the rest of it.
1789 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1791 log_error(LOG_LEVEL_ERROR,
1792 "Stopped grabbing the client headers.");
1793 destroy_list(headers);
1794 return JB_ERR_PARSE;
1797 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1800 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1801 destroy_list(headers);
1802 return JB_ERR_PARSE;
1805 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1808 * If there is no memory left for buffering the
1809 * request, there is nothing we can do but hang up
1811 destroy_list(headers);
1812 return JB_ERR_MEMORY;
1817 if (!strncmpic(p, "Transfer-Encoding:", 18))
1820 * XXX: should be called through sed()
1821 * but currently can't.
1823 client_transfer_encoding(csp, &p);
1826 * We were able to read a complete
1827 * header and can finally enlist it.
1834 if (http->host == NULL)
1837 * If we still don't know the request destination,
1838 * the request is invalid or the client uses
1839 * Privoxy without its knowledge.
1841 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1844 * Our attempts to get the request destination
1845 * elsewhere failed or Privoxy is configured
1846 * to only accept proxy requests.
1848 * An error response has already been send
1849 * and we're done here.
1851 return JB_ERR_PARSE;
1855 #ifdef FEATURE_CLIENT_TAGS
1856 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1857 set_client_address(csp, headers);
1858 get_tag_list_for_client(csp->client_tags, csp->client_address);
1862 * Determine the actions for this URL
1864 #ifdef FEATURE_TOGGLE
1865 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1867 /* Most compatible set of actions (i.e. none) */
1868 init_current_action(csp->action);
1871 #endif /* ndef FEATURE_TOGGLE */
1873 get_url_actions(csp, http);
1876 enlist(csp->headers, http->cmd);
1878 /* Append the previously read headers */
1879 err = list_append_list_unique(csp->headers, headers);
1880 destroy_list(headers);
1887 /*********************************************************************
1889 * Function : parse_client_request
1891 * Description : Parses the client's request and decides what to do
1894 * Note that since we're not using select() we could get
1895 * blocked here if a client connected, then didn't say
1899 * 1 : csp = Current client state (buffers, headers, etc...)
1901 * Returns : JB_ERR_OK or JB_ERR_PARSE
1903 *********************************************************************/
1904 static jb_err parse_client_request(struct client_state *csp)
1906 struct http_request *http = csp->http;
1909 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1910 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1911 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1912 && (csp->http->ssl == 0))
1914 /* Assume persistence until further notice */
1915 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1917 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1919 if (csp->http->ssl == 0)
1922 * This whole block belongs to chat() but currently
1923 * has to be executed before sed().
1925 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1927 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1929 return JB_ERR_PARSE;
1934 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1936 verify_request_length(csp);
1938 #ifndef FEATURE_HTTPS_INSPECTION
1941 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1945 err = sed(csp, FILTER_CLIENT_HEADERS);
1946 if (JB_ERR_OK != err)
1948 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1950 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1951 csp->ip_addr_str, csp->http->cmd);
1952 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1953 return JB_ERR_PARSE;
1955 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1957 /* Check request line for rewrites. */
1958 if ((NULL == csp->headers->first->str)
1959 || (strcmp(http->cmd, csp->headers->first->str) &&
1960 (JB_ERR_OK != change_request_destination(csp))))
1963 * A header filter broke the request line - bail out.
1965 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1966 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1967 /* XXX: Use correct size */
1968 log_error(LOG_LEVEL_CLF,
1969 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1970 log_error(LOG_LEVEL_ERROR,
1971 "Invalid request line after applying header filters.");
1972 free_http_request(http);
1974 return JB_ERR_PARSE;
1977 if (client_has_unsupported_expectations(csp))
1979 return JB_ERR_PARSE;
1987 /*********************************************************************
1989 * Function : send_http_request
1991 * Description : Sends the HTTP headers from the client request
1992 * and all the body data that has already been received.
1995 * 1 : csp = Current client state (buffers, headers, etc...)
1997 * Returns : 0 on success, anything else is an error.
1999 *********************************************************************/
2000 static int send_http_request(struct client_state *csp)
2005 hdr = list_to_text(csp->headers);
2008 /* FIXME Should handle error properly */
2009 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2011 list_remove_all(csp->headers);
2014 * Write the client's (modified) header to the server
2015 * (along with anything else that may be in the buffer)
2017 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2022 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2023 csp->http->hostport);
2025 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2026 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2029 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2030 csp->http->hostport);
2033 return write_failure;
2038 #ifdef FEATURE_HTTPS_INSPECTION
2039 /*********************************************************************
2041 * Function : receive_and_send_encrypted_post_data
2043 * Description : Reads remaining POST data from the client and sends
2047 * 1 : csp = Current client state (buffers, headers, etc...)
2049 * Returns : 0 on success, anything else is an error.
2051 *********************************************************************/
2052 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2054 int content_length_known = csp->expected_client_content_length != 0;
2056 while (is_ssl_pending(&(csp->ssl_client_attr))
2057 || (content_length_known && csp->expected_client_content_length != 0))
2059 unsigned char buf[BUFFER_SIZE];
2061 int max_bytes_to_read = sizeof(buf);
2063 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2065 max_bytes_to_read = (int)csp->expected_client_content_length;
2067 log_error(LOG_LEVEL_CONNECT,
2068 "Waiting for up to %d bytes of POST data from the client.",
2070 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2071 (unsigned)max_bytes_to_read);
2078 /* XXX: Does this actually happen? */
2081 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted POST data",
2083 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2088 if (csp->expected_client_content_length != 0)
2090 if (csp->expected_client_content_length >= len)
2092 csp->expected_client_content_length -= (unsigned)len;
2094 if (csp->expected_client_content_length == 0)
2096 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2102 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted POST data");
2109 /*********************************************************************
2111 * Function : send_https_request
2113 * Description : Sends the HTTP headers from the client request
2114 * and all the body data that has already been received.
2117 * 1 : csp = Current client state (buffers, headers, etc...)
2119 * Returns : 0 on success, anything else is an error.
2121 *********************************************************************/
2122 static int send_https_request(struct client_state *csp)
2128 hdr = list_to_text(csp->https_headers);
2131 /* FIXME Should handle error properly */
2132 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2134 list_remove_all(csp->https_headers);
2137 * Write the client's (modified) header to the server
2138 * (along with anything else that may be in the buffer)
2140 ret = ssl_send_data(&(csp->ssl_server_attr),
2141 (const unsigned char *)hdr, strlen(hdr));
2146 log_error(LOG_LEVEL_CONNECT,
2147 "Failed sending encrypted request headers to: %s: %E",
2148 csp->http->hostport);
2149 mark_server_socket_tainted(csp);
2153 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2154 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2155 csp->client_iob)) < 0))
2157 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2158 csp->http->hostport);
2161 if (flushed != 0 || csp->expected_client_content_length != 0)
2163 if (csp->expected_client_content_length != 0)
2165 if (csp->expected_client_content_length < flushed)
2167 log_error(LOG_LEVEL_ERROR,
2168 "Flushed %ld bytes of request body while only expecting %llu",
2169 flushed, csp->expected_client_content_length);
2170 csp->expected_client_content_length = 0;
2174 log_error(LOG_LEVEL_CONNECT,
2175 "Flushed %ld bytes of request body while expecting %llu",
2176 flushed, csp->expected_client_content_length);
2177 csp->expected_client_content_length -= (unsigned)flushed;
2178 if (receive_and_send_encrypted_post_data(csp))
2186 log_error(LOG_LEVEL_CONNECT,
2187 "Flushed %ld bytes of request body", flushed);
2191 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2198 /*********************************************************************
2200 * Function : receive_encrypted_request
2202 * Description : Receives an encrypted request.
2205 * 1 : csp = Current client state (buffers, headers, etc...)
2207 * Returns : JB_ERR_OK on success,
2208 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2210 *********************************************************************/
2211 static jb_err receive_encrypted_request(struct client_state *csp)
2213 char buf[BUFFER_SIZE];
2219 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2220 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2221 !data_is_available(csp->cfd, csp->config->socket_timeout))
2223 log_error(LOG_LEVEL_CONNECT,
2224 "Socket %d timed out while waiting for client headers", csp->cfd);
2225 return JB_ERR_PARSE;
2227 len = ssl_recv_data(&(csp->ssl_client_attr),
2228 (unsigned char *)buf, sizeof(buf));
2231 log_error(LOG_LEVEL_CONNECT,
2232 "Socket %d closed while waiting for client headers", csp->cfd);
2233 return JB_ERR_PARSE;
2237 return JB_ERR_PARSE;
2239 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2241 return JB_ERR_MEMORY;
2243 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2244 } while (p == NULL);
2246 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2252 /*********************************************************************
2254 * Function : process_encrypted_request
2256 * Description : Receives and parses an encrypted request.
2259 * 1 : csp = Current client state (buffers, headers, etc...)
2261 * Returns : JB_ERR_OK on success,
2262 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2264 *********************************************************************/
2265 static jb_err process_encrypted_request(struct client_state *csp)
2270 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2271 struct list header_list;
2272 struct list *headers = &header_list;
2274 assert(csp->ssl_with_client_is_opened);
2276 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2277 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2279 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2282 err = receive_encrypted_request(csp);
2283 if (err != JB_ERR_OK)
2285 if (csp->client_iob->cur == NULL ||
2286 csp->client_iob->cur == csp->client_iob->eod)
2289 * We did not receive any data, most likely because the
2290 * client is done. Don't log this as a parse failure.
2292 return JB_ERR_PARSE;
2294 /* XXX: Also used for JB_ERR_MEMORY */
2295 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2296 jb_err_to_string(err));
2297 ssl_send_data_delayed(&(csp->ssl_client_attr),
2298 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2302 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2303 request_line = get_header(csp->client_iob);
2304 if (request_line == NULL)
2306 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2307 ssl_send_data_delayed(&(csp->ssl_client_attr),
2308 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2309 return JB_ERR_PARSE;
2311 assert(*request_line != '\0');
2313 if (client_protocol_is_unsupported(csp, request_line))
2316 * If the protocol is unsupported we're done here.
2317 * client_protocol_is_unsupported() took care of sending
2318 * the error response and logging the error message.
2320 return JB_ERR_PARSE;
2323 #ifdef FEATURE_FORCE_LOAD
2324 if (force_required(csp, request_line))
2326 csp->flags |= CSP_FLAG_FORCED;
2328 #endif /* def FEATURE_FORCE_LOAD */
2330 free_http_request(csp->http);
2332 err = parse_http_request(request_line, csp->http);
2333 /* XXX: Restore ssl setting. This is ugly */
2334 csp->http->client_ssl = 1;
2335 csp->http->server_ssl = 1;
2337 freez(request_line);
2338 if (JB_ERR_OK != err)
2340 ssl_send_data_delayed(&(csp->ssl_client_attr),
2341 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2342 /* XXX: Use correct size */
2343 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2344 log_error(LOG_LEVEL_ERROR,
2345 "Couldn't parse request line received from %s: %s",
2346 csp->ip_addr_str, jb_err_to_string(err));
2348 free_http_request(csp->http);
2349 return JB_ERR_PARSE;
2352 /* Parse the rest of the client's headers. */
2356 p = get_header(csp->client_iob);
2360 /* There are no additional headers to read. */
2367 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2370 * Our attempts to get the request destination
2373 log_error(LOG_LEVEL_ERROR,
2374 "Failed to get the encrypted request destination");
2375 ssl_send_data_delayed(&(csp->ssl_client_attr),
2376 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2377 return JB_ERR_PARSE;
2380 /* Split the domain we just got for pattern matching */
2381 init_domain_components(csp->http);
2383 #ifdef FEATURE_CLIENT_TAGS
2384 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2385 if (csp->client_address == NULL)
2387 set_client_address(csp, headers);
2388 get_tag_list_for_client(csp->client_tags, csp->client_address);
2392 #ifdef FEATURE_TOGGLE
2393 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2397 * Determine the actions for this request after
2398 * clearing the ones from the previous one.
2400 free_current_action(csp->action);
2401 get_url_actions(csp, csp->http);
2404 enlist(csp->https_headers, csp->http->cmd);
2406 /* Append the previously read headers */
2407 err = list_append_list_unique(csp->https_headers, headers);
2408 destroy_list(headers);
2409 if (JB_ERR_OK != err)
2411 /* XXX: Send error message */
2415 /* XXX: Work around crash */
2416 csp->error_message = NULL;
2418 /* XXX: Why do this here? */
2421 err = sed_https(csp);
2422 if (JB_ERR_OK != err)
2424 ssl_send_data_delayed(&(csp->ssl_client_attr),
2425 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2426 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2428 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2429 csp->ip_addr_str, csp->http->cmd);
2430 return JB_ERR_PARSE;
2433 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2434 log_applied_actions(csp->action);
2435 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2442 /*********************************************************************
2444 * Function : cgi_page_requested
2446 * Description : Checks if a request is for an internal CGI page.
2449 * 1 : host = The host requested by the client.
2451 * Returns : 1 if a CGI page has been requested, 0 otherwise
2453 *********************************************************************/
2454 static int cgi_page_requested(const char *host)
2456 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2457 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2458 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2459 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2469 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2470 /*********************************************************************
2472 * Function : continue_https_chat
2474 * Description : Behaves similar to chat() but only deals with
2475 * https-inspected requests that arrive on an already
2476 * established connection. The first request is always
2477 * served by chat() which is a lot more complex as it
2478 * has to deal with forwarding settings and connection
2481 * If a connection to the server has already been
2482 * opened it is reused unless the request is blocked
2483 * or the forwarder changed.
2485 * If a connection to the server has not yet been
2486 * opened (because the previous request was crunched),
2487 * or the forwarder changed, the connection is dropped
2488 * so that the client retries on a fresh one.
2491 * 1 : csp = Current client state (buffers, headers, etc...)
2493 * Returns : Nothing.
2495 *********************************************************************/
2496 static void continue_https_chat(struct client_state *csp)
2498 const struct forward_spec *fwd;
2500 if (JB_ERR_OK != process_encrypted_request(csp))
2505 csp->requests_received_total++;
2508 * We have an encrypted request. Check if one of the crunchers wants it.
2510 if (crunch_response_triggered(csp, crunchers_all))
2513 * Yes. The client got the crunch response and we're done here.
2517 if (csp->ssl_with_server_is_opened == 0)
2519 log_error(LOG_LEVEL_CONNECT,
2520 "Dropping the client connection on socket %d. "
2521 "The server connection has not been established yet.",
2523 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2526 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2528 fwd = forward_url(csp, csp->http);
2529 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2531 log_error(LOG_LEVEL_CONNECT,
2532 "Dropping the client connection on socket %d with "
2533 "server socket %d connected to %s. The forwarder has changed.",
2534 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2535 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2539 log_error(LOG_LEVEL_CONNECT,
2540 "Reusing server socket %d connected to %s. Requests already sent: %u.",
2541 csp->server_connection.sfd, csp->server_connection.host,
2542 csp->server_connection.requests_sent_total);
2544 if (send_https_request(csp))
2547 * Most likely the server connection timed out. We can't easily
2548 * create a new one so simply drop the client connection without a
2549 * error response to let the client retry.
2551 log_error(LOG_LEVEL_CONNECT,
2552 "Dropping client connection on socket %d. "
2553 "Forwarding the encrypted client request failed.",
2557 csp->server_connection.requests_sent_total++;
2558 handle_established_connection(csp);
2559 freez(csp->receive_buffer);
2561 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2565 /*********************************************************************
2567 * Function : handle_established_connection
2569 * Description : Shuffle data between client and server once the
2570 * connection has been established.
2573 * 1 : csp = Current client state (buffers, headers, etc...)
2575 * Returns : Nothing.
2577 *********************************************************************/
2578 static void handle_established_connection(struct client_state *csp)
2583 struct pollfd poll_fds[2];
2585 int ms_iis5_hack = 0;
2586 unsigned long long byte_count = 0;
2587 struct http_request *http;
2588 long len = 0; /* for buffer sizes (and negative error codes) */
2589 int buffer_and_filter_content = 0;
2590 unsigned int write_delay;
2591 #ifdef FEATURE_HTTPS_INSPECTION
2593 int use_ssl_tunnel = 0;
2594 csp->dont_verify_certificate = 0;
2596 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2598 /* Pass encrypted content without filtering. */
2603 /* Skeleton for HTTP response, if we should intercept the request */
2604 struct http_response *rsp;
2605 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2606 int watch_client_socket;
2609 csp->receive_buffer_size = csp->config->receive_buffer_size;
2610 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2611 if (csp->receive_buffer == NULL)
2613 log_error(LOG_LEVEL_ERROR,
2614 "Out of memory. Failed to allocate the receive buffer.");
2615 rsp = cgi_error_memory();
2616 send_crunch_response(csp, rsp);
2622 /* pass data between the client and server
2623 * until one or the other shuts down the connection.
2628 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2629 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2631 write_delay = get_write_delay(csp);
2635 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2636 if ((csp->flags & CSP_FLAG_CHUNKED)
2637 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2638 && ((csp->iob->eod - csp->iob->cur) >= 5)
2639 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2642 * XXX: This check should be obsolete now,
2643 * but let's wait a while to be sure.
2645 log_error(LOG_LEVEL_CONNECT,
2646 "Looks like we got the last chunk together with "
2647 "the server headers but didn't detect it earlier. "
2648 "We better stop reading.");
2649 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2650 csp->expected_content_length = byte_count;
2651 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2653 if (server_body && server_response_is_complete(csp, byte_count))
2655 if (csp->expected_content_length == byte_count)
2657 log_error(LOG_LEVEL_CONNECT,
2658 "Done reading from server. Content length: %llu as expected. "
2659 "Bytes most recently read: %ld.",
2664 log_error(LOG_LEVEL_CONNECT,
2665 "Done reading from server. Expected content length: %llu. "
2666 "Actual content length: %llu. Bytes most recently read: %ld.",
2667 csp->expected_content_length, byte_count, len);
2671 * XXX: Should not jump around, handle_established_connection()
2672 * is complicated enough already.
2676 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2678 poll_fds[0].fd = csp->cfd;
2679 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2680 if (!watch_client_socket)
2683 * Ignore incoming data, but still watch out
2684 * for disconnects etc. These flags are always
2685 * implied anyway but explicitly setting them
2688 poll_fds[0].events = POLLERR|POLLHUP;
2693 poll_fds[0].events = POLLIN;
2695 poll_fds[1].fd = csp->server_connection.sfd;
2696 poll_fds[1].events = POLLIN;
2697 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2699 /*server or client not responding in timeout */
2702 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2703 csp->config->socket_timeout, http->url);
2704 if ((byte_count == 0) && (http->ssl == 0))
2706 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2708 mark_server_socket_tainted(csp);
2709 #ifdef FEATURE_HTTPS_INSPECTION
2710 close_client_and_server_ssl_connections(csp);
2716 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2717 mark_server_socket_tainted(csp);
2718 #ifdef FEATURE_HTTPS_INSPECTION
2719 close_client_and_server_ssl_connections(csp);
2725 * This is the body of the browser's request,
2726 * just read and write it.
2728 * Receives data from browser and sends it to server
2730 * XXX: Make sure the client doesn't use pipelining
2731 * behind Privoxy's back.
2733 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2735 log_error(LOG_LEVEL_CONNECT,
2736 "The client socket %d has become unusable while "
2737 "the server socket %d is still open.",
2738 csp->cfd, csp->server_connection.sfd);
2739 mark_server_socket_tainted(csp);
2743 if (poll_fds[0].revents != 0)
2745 int max_bytes_to_read = (int)csp->receive_buffer_size;
2747 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2748 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2750 if (data_is_available(csp->cfd, 0))
2753 * If the next request is already waiting, we have
2754 * to stop poll()ing the client socket. Otherwise
2755 * we would always return right away and get nothing
2758 watch_client_socket = 0;
2759 log_error(LOG_LEVEL_CONNECT,
2760 "Stop watching client socket %d. "
2761 "There's already another request waiting.",
2766 * If the client socket is set, but there's no data
2767 * available on the socket, the client went fishing
2768 * and continuing talking to the server makes no sense.
2770 log_error(LOG_LEVEL_CONNECT,
2771 "The client closed socket %d while "
2772 "the server socket %d is still open.",
2773 csp->cfd, csp->server_connection.sfd);
2774 mark_server_socket_tainted(csp);
2777 if (csp->expected_client_content_length != 0)
2779 if (csp->expected_client_content_length < csp->receive_buffer_size)
2781 max_bytes_to_read = (int)csp->expected_client_content_length;
2783 log_error(LOG_LEVEL_CONNECT,
2784 "Waiting for up to %d bytes from the client.",
2787 assert(max_bytes_to_read <= csp->receive_buffer_size);
2788 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2790 #ifdef FEATURE_HTTPS_INSPECTION
2791 if (client_use_ssl(csp))
2793 if (csp->http->status == 101)
2795 len = ssl_recv_data(&(csp->ssl_client_attr),
2796 (unsigned char *)csp->receive_buffer,
2797 (size_t)max_bytes_to_read);
2800 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
2801 "on client socket %d for an upgraded connection",
2807 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
2808 "on client socket %d for an upgraded connection",
2812 byte_count += (unsigned long long)len;
2813 len = ssl_send_data(&(csp->ssl_server_attr),
2814 (unsigned char *)csp->receive_buffer, (size_t)len);
2817 log_error(LOG_LEVEL_ERROR, "Failed to send data "
2818 "on server socket %d for an upgraded connection",
2819 csp->server_connection.sfd);
2824 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
2828 #endif /* def FEATURE_HTTPS_INSPECTION */
2830 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2834 /* XXX: not sure if this is necessary. */
2835 mark_server_socket_tainted(csp);
2836 break; /* "game over, man" */
2839 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2840 if (csp->expected_client_content_length != 0)
2842 assert(len <= max_bytes_to_read);
2843 csp->expected_client_content_length -= (unsigned)len;
2844 log_error(LOG_LEVEL_CONNECT,
2845 "Expected client content length set to %llu "
2846 "after reading %ld bytes.",
2847 csp->expected_client_content_length, len);
2848 if (csp->expected_client_content_length == 0)
2850 log_error(LOG_LEVEL_CONNECT,
2851 "Done reading from the client.");
2852 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2855 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2857 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2859 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2860 mark_server_socket_tainted(csp);
2868 * The server wants to talk. It could be the header or the body.
2869 * If `hdr' is null, then it's the header otherwise it's the body.
2870 * FIXME: Does `hdr' really mean `host'? No.
2872 if (poll_fds[1].revents != 0)
2874 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2876 * If we are buffering content, we don't want to eat up to
2877 * buffer-limit bytes if the client no longer cares about them.
2878 * If we aren't buffering, however, a dead client socket will be
2879 * noticed pretty much right away anyway, so we can reduce the
2880 * overhead by skipping the check.
2882 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2885 log_error(LOG_LEVEL_CONNECT,
2886 "The server still wants to talk, but the client may already have hung up on us.");
2888 log_error(LOG_LEVEL_CONNECT,
2889 "The server still wants to talk, but the client hung up on us.");
2890 mark_server_socket_tainted(csp);
2891 #ifdef FEATURE_HTTPS_INSPECTION
2892 close_client_and_server_ssl_connections(csp);
2895 #endif /* def _WIN32 */
2897 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2899 #ifdef FEATURE_HTTPS_INSPECTION
2901 * Reading data from standard or secured connection (HTTP/HTTPS)
2903 if (server_use_ssl(csp))
2905 len = ssl_recv_data(&(csp->ssl_server_attr),
2906 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2911 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2912 (int)csp->receive_buffer_size);
2917 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2919 if ((http->ssl && (csp->fwd == NULL))
2920 #ifdef FEATURE_HTTPS_INSPECTION
2926 * Just hang up. We already confirmed the client's CONNECT
2927 * request with status code 200 and unencrypted content is
2928 * no longer welcome.
2930 log_error(LOG_LEVEL_ERROR,
2931 "CONNECT already confirmed. Unable to tell the client about the problem.");
2934 else if (byte_count)
2937 * Just hang up. We already transmitted the original headers
2938 * and parts of the original content and therefore missed the
2939 * chance to send an error message (without risking data corruption).
2941 * XXX: we could retry with a fancy range request here.
2943 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2944 "Unable to tell the client about the problem.");
2945 mark_server_socket_tainted(csp);
2946 #ifdef FEATURE_HTTPS_INSPECTION
2947 close_client_and_server_ssl_connections(csp);
2952 * XXX: Consider handling the cases above the same.
2954 mark_server_socket_tainted(csp);
2958 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2959 if (csp->flags & CSP_FLAG_CHUNKED)
2961 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2963 /* XXX: this is a temporary hack */
2964 log_error(LOG_LEVEL_CONNECT,
2965 "Looks like we reached the end of the last chunk. "
2966 "We better stop reading.");
2967 csp->expected_content_length = byte_count + (unsigned long long)len;
2968 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2972 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2975 * This is guaranteed by allocating with zalloc_or_die()
2976 * and never (intentionally) writing to the last byte.
2978 * csp->receive_buffer_size is the size of the part of the
2979 * buffer we intentionally write to, but we actually
2980 * allocated csp->receive_buffer_size+1 bytes so the assertion
2981 * stays within the allocated range.
2983 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2986 * Add a trailing zero to let be able to use string operations.
2987 * XXX: do we still need this with filter_popups gone?
2989 assert(len <= csp->receive_buffer_size);
2990 csp->receive_buffer[len] = '\0';
2993 * Normally, this would indicate that we've read
2994 * as much as the server has sent us and we can
2995 * close the client connection. However, Microsoft
2996 * in its wisdom has released IIS/5 with a bug that
2997 * prevents it from sending the trailing \r\n in
2998 * a 302 redirect header (and possibly other headers).
2999 * To work around this if we've haven't parsed
3000 * a full header we'll append a trailing \r\n
3001 * and see if this now generates a valid one.
3003 * This hack shouldn't have any impacts. If we've
3004 * already transmitted the header or if this is a
3005 * SSL connection, then we won't bother with this
3006 * hack. So we only work on partially received
3007 * headers. If we append a \r\n and this still
3008 * doesn't generate a valid header, then we won't
3009 * transmit anything to the client.
3014 if (server_body || (http->ssl
3015 #ifdef FEATURE_HTTPS_INSPECTION
3021 * If we have been buffering up the document,
3022 * now is the time to apply content modification
3023 * and send the result to the client.
3025 if (buffer_and_filter_content)
3027 p = execute_content_filters(csp);
3029 * If content filtering fails, use the original
3030 * buffer and length.
3031 * (see p != NULL ? p : csp->iob->cur below)
3035 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3037 #ifdef FEATURE_COMPRESSION
3038 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3039 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3041 char *compressed_content = compress_buffer(p,
3042 (size_t *)&csp->content_length, csp->config->compression_level);
3043 if (compressed_content != NULL)
3046 p = compressed_content;
3047 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3052 if (JB_ERR_OK != update_server_headers(csp))
3054 log_error(LOG_LEVEL_FATAL,
3055 "Failed to update server headers. after filtering.");
3058 hdr = list_to_text(csp->headers);
3061 /* FIXME Should handle error properly */
3062 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3065 #ifdef FEATURE_HTTPS_INSPECTION
3067 * Sending data with standard or secured connection (HTTP/HTTPS)
3069 if (client_use_ssl(csp))
3071 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3072 (const unsigned char *)hdr, strlen(hdr),
3073 get_write_delay(csp)) < 0)
3074 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3075 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3076 csp->content_length, get_write_delay(csp)) < 0))
3078 log_error(LOG_LEVEL_ERROR, "write modified content to "
3079 "client over TLS/SSL failed");
3082 mark_server_socket_tainted(csp);
3083 close_client_and_server_ssl_connections(csp);
3088 #endif /* def FEATURE_HTTPS_INSPECTION */
3090 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3091 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3092 (size_t)csp->content_length, write_delay))
3094 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3097 mark_server_socket_tainted(csp);
3106 break; /* "game over, man" */
3110 * This is NOT the body, so
3111 * Let's pretend the server just sent us a blank line.
3113 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3114 len = (int)strlen(csp->receive_buffer);
3117 * Now, let the normal header parsing algorithm below do its
3118 * job. If it fails, we'll exit instead of continuing.
3125 * If we're in the body of the server document, just write it to
3126 * the client, unless we need to buffer the body for later
3127 * content-filtering.
3129 if (server_body || (http->ssl
3130 #ifdef FEATURE_HTTPS_INSPECTION
3135 if (buffer_and_filter_content)
3138 * If there is no memory left for buffering the content, or the buffer limit
3139 * has been reached, switch to non-filtering mode, i.e. make & write the
3140 * header, flush the iob and buf, and get out of the way.
3142 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3147 log_error(LOG_LEVEL_INFO,
3148 "Flushing header and buffers. Stepping back from filtering.");
3150 hdr = list_to_text(csp->headers);
3154 * Memory is too tight to even generate the header.
3155 * Send our static "Out-of-memory" page.
3157 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3158 rsp = cgi_error_memory();
3159 send_crunch_response(csp, rsp);
3160 mark_server_socket_tainted(csp);
3161 #ifdef FEATURE_HTTPS_INSPECTION
3162 close_client_and_server_ssl_connections(csp);
3166 hdrlen = strlen(hdr);
3168 #ifdef FEATURE_HTTPS_INSPECTION
3170 * Sending data with standard or secured connection (HTTP/HTTPS)
3172 if (client_use_ssl(csp))
3174 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3175 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3176 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3178 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3179 (const unsigned char *)csp->receive_buffer, (size_t)len,
3180 get_write_delay(csp)) < 0))
3182 log_error(LOG_LEVEL_CONNECT,
3183 "Flush header and buffers to client failed");
3185 mark_server_socket_tainted(csp);
3186 close_client_and_server_ssl_connections(csp);
3191 #endif /* def FEATURE_HTTPS_INSPECTION */
3193 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3194 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3195 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3198 log_error(LOG_LEVEL_CONNECT,
3199 "Flush header and buffers to client failed: %E");
3201 mark_server_socket_tainted(csp);
3207 * Reset the byte_count to the amount of bytes
3208 * we just flushed. len will be added a few lines below,
3209 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3211 byte_count = (unsigned long long)flushed;
3213 buffer_and_filter_content = 0;
3219 #ifdef FEATURE_HTTPS_INSPECTION
3221 * Sending data with standard or secured connection (HTTP/HTTPS)
3223 if (client_use_ssl(csp))
3225 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3226 (const unsigned char *)csp->receive_buffer, (size_t)len,
3227 get_write_delay(csp));
3230 log_error(LOG_LEVEL_ERROR,
3231 "Sending data to client failed");
3232 mark_server_socket_tainted(csp);
3233 close_client_and_server_ssl_connections(csp);
3238 #endif /* def FEATURE_HTTPS_INSPECTION */
3240 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3241 (size_t)len, write_delay))
3243 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3244 mark_server_socket_tainted(csp);
3249 byte_count += (unsigned long long)len;
3255 * We're still looking for the end of the server's header.
3256 * Buffer up the data we just read. If that fails, there's
3257 * little we can do but send our static out-of-memory page.
3259 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3261 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3262 rsp = cgi_error_memory();
3263 send_crunch_response(csp, rsp);
3264 mark_server_socket_tainted(csp);
3265 #ifdef FEATURE_HTTPS_INSPECTION
3266 close_client_and_server_ssl_connections(csp);
3271 /* Convert iob into something sed() can digest */
3272 if (JB_ERR_PARSE == get_server_headers(csp))
3277 * Well, we tried our MS IIS/5 hack and it didn't work.
3278 * The header is incomplete and there isn't anything
3279 * we can do about it.
3281 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3282 "Applying the MS IIS5 hack didn't help.");
3283 log_error(LOG_LEVEL_CLF,
3284 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3285 #ifdef FEATURE_HTTPS_INSPECTION
3287 * Sending data with standard or secured connection (HTTP/HTTPS)
3289 if (client_use_ssl(csp))
3291 ssl_send_data_delayed(&(csp->ssl_client_attr),
3292 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3293 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3296 #endif /* def FEATURE_HTTPS_INSPECTION */
3298 write_socket_delayed(csp->cfd,
3299 INVALID_SERVER_HEADERS_RESPONSE,
3300 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3302 mark_server_socket_tainted(csp);
3303 #ifdef FEATURE_HTTPS_INSPECTION
3304 close_client_and_server_ssl_connections(csp);
3311 * Since we have to wait for more from the server before
3312 * we can parse the headers we just continue here.
3314 log_error(LOG_LEVEL_CONNECT,
3315 "Continuing buffering server headers from socket %d. "
3316 "Bytes most recently read: %ld.", csp->cfd, len);
3323 * Account for the content bytes we
3324 * might have gotten with the headers.
3326 assert(csp->iob->eod >= csp->iob->cur);
3327 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3330 /* Did we actually get anything? */
3331 if (NULL == csp->headers->first)
3333 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3335 log_error(LOG_LEVEL_ERROR,
3336 "No server or forwarder response received on socket %d. "
3337 "Closing client socket %d without sending data.",
3338 csp->server_connection.sfd, csp->cfd);
3339 log_error(LOG_LEVEL_CLF,
3340 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3344 log_error(LOG_LEVEL_ERROR,
3345 "No server or forwarder response received on socket %d.",
3346 csp->server_connection.sfd);
3347 send_crunch_response(csp, error_response(csp, "no-server-data"));
3349 free_http_request(http);
3350 mark_server_socket_tainted(csp);
3351 #ifdef FEATURE_HTTPS_INSPECTION
3352 close_client_and_server_ssl_connections(csp);
3357 if (!csp->headers->first->str)
3359 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3361 assert(csp->headers->first->str);
3363 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3364 strncmpic(csp->headers->first->str, "ICY", 3))
3367 * It doesn't look like a HTTP (or Shoutcast) response:
3368 * tell the client and log the problem.
3370 if (strlen(csp->headers->first->str) > 30)
3372 csp->headers->first->str[30] = '\0';
3374 log_error(LOG_LEVEL_ERROR,
3375 "Invalid server or forwarder response. Starts with: %s",
3376 csp->headers->first->str);
3377 log_error(LOG_LEVEL_CLF,
3378 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3379 #ifdef FEATURE_HTTPS_INSPECTION
3381 * Sending data with standard or secured connection (HTTP/HTTPS)
3383 if (client_use_ssl(csp))
3385 ssl_send_data_delayed(&(csp->ssl_client_attr),
3386 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3387 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3388 get_write_delay(csp));
3391 #endif /* def FEATURE_HTTPS_INSPECTION */
3393 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3394 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3396 free_http_request(http);
3397 mark_server_socket_tainted(csp);
3398 #ifdef FEATURE_HTTPS_INSPECTION
3399 close_client_and_server_ssl_connections(csp);
3405 * We have now received the entire server header,
3406 * filter it and send the result to the client
3408 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3410 log_error(LOG_LEVEL_CLF,
3411 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3412 #ifdef FEATURE_HTTPS_INSPECTION
3414 * Sending data with standard or secured connection (HTTP/HTTPS)
3416 if (client_use_ssl(csp))
3418 ssl_send_data_delayed(&(csp->ssl_client_attr),
3419 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3420 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3421 get_write_delay(csp));
3426 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3427 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3429 free_http_request(http);
3430 mark_server_socket_tainted(csp);
3431 #ifdef FEATURE_HTTPS_INSPECTION
3432 close_client_and_server_ssl_connections(csp);
3436 hdr = list_to_text(csp->headers);
3439 /* FIXME Should handle error properly */
3440 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3443 if ((csp->flags & CSP_FLAG_CHUNKED)
3444 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3445 && ((csp->iob->eod - csp->iob->cur) >= 5)
3446 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3448 log_error(LOG_LEVEL_CONNECT,
3449 "Looks like we got the last chunk together with "
3450 "the server headers. We better stop reading.");
3451 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3452 csp->expected_content_length = byte_count;
3453 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3456 csp->server_connection.response_received = time(NULL);
3458 if (crunch_response_triggered(csp, crunchers_light))
3461 * One of the tags created by a server-header
3462 * tagger triggered a crunch. We already
3463 * delivered the crunch response to the client
3464 * and are done here after cleaning up.
3467 mark_server_socket_tainted(csp);
3468 #ifdef FEATURE_HTTPS_INSPECTION
3469 close_client_and_server_ssl_connections(csp);
3474 /* Buffer and pcrs filter this if appropriate. */
3475 buffer_and_filter_content = content_requires_filtering(csp);
3477 if (!buffer_and_filter_content)
3480 * Write the server's (modified) header to
3481 * the client (along with anything else that
3482 * may be in the buffer). Use standard or secured
3485 #ifdef FEATURE_HTTPS_INSPECTION
3486 if (client_use_ssl(csp))
3488 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3489 (const unsigned char *)hdr, strlen(hdr),
3490 get_write_delay(csp)) < 0)
3491 || (len = ssl_flush_socket(&(csp->ssl_client_attr),
3494 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3497 * The write failed, so don't bother mentioning it
3498 * to the client... it probably can't hear us anyway.
3501 mark_server_socket_tainted(csp);
3502 #ifdef FEATURE_HTTPS_INSPECTION
3503 close_client_and_server_ssl_connections(csp);
3509 #endif /* def FEATURE_HTTPS_INSPECTION */
3511 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3512 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3514 log_error(LOG_LEVEL_ERROR,
3515 "write header to client failed");
3517 * The write failed, so don't bother mentioning it
3518 * to the client... it probably can't hear us anyway.
3521 mark_server_socket_tainted(csp);
3527 /* we're finished with the server's header */
3533 * If this was a MS IIS/5 hack then it means the server
3534 * has already closed the connection. Nothing more to read.
3539 log_error(LOG_LEVEL_ERROR,
3540 "Closed server connection detected. "
3541 "Applying the MS IIS5 hack didn't help.");
3542 log_error(LOG_LEVEL_CLF,
3543 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3544 #ifdef FEATURE_HTTPS_INSPECTION
3546 * Sending data with standard or secured connection (HTTP/HTTPS)
3548 if (client_use_ssl(csp))
3550 ssl_send_data_delayed(&(csp->ssl_client_attr),
3551 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3552 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3553 get_write_delay(csp));
3556 #endif /* def FEATURE_HTTPS_INSPECTION */
3558 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3559 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3561 mark_server_socket_tainted(csp);
3562 #ifdef FEATURE_HTTPS_INSPECTION
3563 close_client_and_server_ssl_connections(csp);
3570 mark_server_socket_tainted(csp);
3571 #ifdef FEATURE_HTTPS_INSPECTION
3572 close_client_and_server_ssl_connections(csp);
3574 return; /* huh? we should never get here */
3577 if (csp->content_length == 0)
3580 * If Privoxy didn't recalculate the Content-Length,
3581 * byte_count is still correct.
3583 csp->content_length = byte_count;
3586 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3587 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3588 && (csp->expected_content_length != byte_count))
3590 log_error(LOG_LEVEL_CONNECT,
3591 "Received %llu bytes while expecting %llu.",
3592 byte_count, csp->expected_content_length);
3593 mark_server_socket_tainted(csp);
3597 #ifdef FEATURE_HTTPS_INSPECTION
3598 if (client_use_ssl(csp))
3600 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
3601 csp->ip_addr_str, http->gpc, http->hostport, http->path,
3602 http->version, csp->content_length);
3607 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3608 csp->ip_addr_str, http->ocmd, csp->content_length);
3610 csp->server_connection.timestamp = time(NULL);
3614 /*********************************************************************
3618 * Description : Once a connection from the client has been accepted,
3619 * this function is called (via serve()) to handle the
3620 * main business of the communication. This function
3621 * returns after dealing with a single request. It can
3622 * be called multiple times with the same client socket
3623 * if the client is keeping the connection alive.
3625 * The decision whether or not a client connection will
3626 * be kept alive is up to the caller which also must
3627 * close the client socket when done.
3629 * FIXME: chat is nearly thousand lines long.
3633 * 1 : csp = Current client state (buffers, headers, etc...)
3635 * Returns : Nothing.
3637 *********************************************************************/
3638 static void chat(struct client_state *csp)
3640 const struct forward_spec *fwd;
3641 struct http_request *http;
3642 /* Skeleton for HTTP response, if we should intercept the request */
3643 struct http_response *rsp;
3644 #ifdef FEATURE_HTTPS_INSPECTION
3645 int use_ssl_tunnel = 0;
3650 if (receive_client_request(csp) != JB_ERR_OK)
3654 if (parse_client_request(csp) != JB_ERR_OK)
3659 /* decide how to route the HTTP request */
3660 fwd = forward_url(csp, http);
3662 #ifdef FEATURE_HTTPS_INSPECTION
3664 * Setting flags to use old solution with SSL tunnel and to disable
3665 * certificate verification.
3667 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
3668 && !cgi_page_requested(csp->http->host))
3673 if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
3675 csp->dont_verify_certificate = 1;
3680 * build the http request to send to the server
3681 * we have to do one of the following:
3683 * create = use the original HTTP request to create a new
3684 * HTTP request that has either the path component
3685 * without the http://domainspec (w/path) or the
3686 * full orininal URL (w/url)
3687 * Note that the path and/or the HTTP version may
3688 * have been altered by now.
3690 * SSL proxy = Open a socket to the host:port of the server
3691 * and create TLS/SSL connection with server and
3692 * with client. Then behave like mediator between
3693 * client and server over TLS/SSL.
3695 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3696 * with request to a parent proxy. Note that we'll be sending
3697 * forwarding the CFAIL message ourselves if connecting to the parent
3698 * fails, but we won't send a CSUCCEED message if it works,
3699 * since that would result in a double message (ours and the
3700 * parent's). After sending the request to the parent, we
3701 * must parse answer and send it to client. If connection
3702 * with server is established, we do TLS/SSL proxy. Otherwise
3703 * we send parent response to client and close connections.
3705 * here's the matrix:
3708 * +--------+--------+
3710 * 0 | create | SSL |
3711 * | w/path | proxy |
3712 * Forwarding +--------+--------+
3714 * 1 | create | proxy |
3715 * | w/url |+forward|
3716 * +--------+--------+
3720 #ifdef FEATURE_HTTPS_INSPECTION
3722 * Presetting SSL client and server flags
3724 if (http->ssl && !use_ssl_tunnel)
3726 http->client_ssl = 1;
3727 http->server_ssl = 1;
3731 http->client_ssl = 0;
3732 http->server_ssl = 0;
3736 #ifdef FEATURE_HTTPS_INSPECTION
3738 * Log the request unless we're https inspecting
3739 * in which case we don't have the path yet and
3740 * will log the request later.
3742 if (!client_use_ssl(csp))
3745 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
3748 if (http->ssl && connect_port_is_forbidden(csp))
3750 const char *acceptable_connect_ports =
3751 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3752 assert(NULL != acceptable_connect_ports);
3753 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3754 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3755 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3756 csp->action->flags |= ACTION_BLOCK;
3758 #ifdef FEATURE_HTTPS_INSPECTION
3759 http->client_ssl = 0;
3760 http->server_ssl = 0;
3765 freez(csp->headers->first->str);
3766 build_request_line(csp, fwd, &csp->headers->first->str);
3769 * We have a request. Check if one of the crunchers wants it
3770 * unless the client wants to use TLS/SSL in which case we
3771 * haven't setup the TLS context yet and will send the crunch
3775 #ifdef FEATURE_HTTPS_INSPECTION
3776 !client_use_ssl(csp) &&
3778 crunch_response_triggered(csp, crunchers_all))
3781 * Yes. The client got the crunch response and we're done here.
3786 log_applied_actions(csp->action);
3787 if (fwd->forward_host)
3789 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3790 fwd->forward_host, fwd->forward_port, http->hostport);
3794 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3797 /* here we connect to the server, gateway, or the forwarder */
3799 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3800 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3801 && socket_is_still_alive(csp->server_connection.sfd)
3802 && connection_destination_matches(&csp->server_connection, http, fwd))
3804 log_error(LOG_LEVEL_CONNECT,
3805 "Reusing server socket %d connected to %s. Total requests: %u.",
3806 csp->server_connection.sfd, csp->server_connection.host,
3807 csp->server_connection.requests_sent_total);
3811 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3813 #ifdef FEATURE_CONNECTION_SHARING
3814 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
3815 #ifdef FEATURE_HTTPS_INSPECTION
3816 && !server_use_ssl(csp)
3820 remember_connection(&csp->server_connection);
3823 #endif /* def FEATURE_CONNECTION_SHARING */
3825 log_error(LOG_LEVEL_CONNECT,
3826 "Closing server socket %d connected to %s. Total requests: %u.",
3827 csp->server_connection.sfd, csp->server_connection.host,
3828 csp->server_connection.requests_sent_total);
3829 close_socket(csp->server_connection.sfd);
3831 mark_connection_closed(&csp->server_connection);
3833 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3834 #ifdef FEATURE_HTTPS_INSPECTION
3835 if (http->ssl && !use_ssl_tunnel)
3839 * Creating a SSL proxy.
3841 * By sending the CSUCCEED message we're lying to the client as
3842 * the connection hasn't actually been established yet. We don't
3843 * establish the connection until we have seen and parsed the
3844 * encrypted client headers.
3846 if (write_socket_delayed(csp->cfd, CSUCCEED,
3847 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3849 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3853 ret = create_client_ssl_connection(csp);
3856 log_error(LOG_LEVEL_ERROR,
3857 "Failed to open a secure connection with the client");
3860 if (JB_ERR_OK != process_encrypted_request(csp))
3862 close_client_ssl_connection(csp);
3866 * We have an encrypted request. Check if one of the crunchers now
3867 * wants it (for example because the previously invisible path was
3868 * required to match).
3870 if (crunch_response_triggered(csp, crunchers_all))
3873 * Yes. The client got the crunch response and we're done here.
3880 * Connecting to destination server
3882 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3884 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3886 if (fwd->type != SOCKS_NONE)
3889 rsp = error_response(csp, "forwarding-failed");
3891 else if (errno == EINVAL)
3893 rsp = error_response(csp, "no-such-domain");
3897 rsp = error_response(csp, "connect-failed");
3900 /* Write the answer to the client */
3903 send_crunch_response(csp, rsp);
3907 * Temporary workaround to prevent already-read client
3908 * bodies from being parsed as new requests. For now we
3909 * err on the safe side and throw all the following
3910 * requests under the bus, even if no client body has been
3911 * buffered. A compliant client will repeat the dropped
3912 * requests on an untainted connection.
3914 * The proper fix is to discard the no longer needed
3915 * client body in the buffer (if there is one) and to
3916 * continue parsing the bytes that follow.
3918 #ifdef FEATURE_HTTPS_INSPECTION
3919 close_client_ssl_connection(csp);
3921 drain_and_close_socket(csp->cfd);
3922 csp->cfd = JB_INVALID_SOCKET;
3927 #ifdef FEATURE_HTTPS_INSPECTION
3929 * Creating TLS/SSL connections with destination server or parent
3930 * proxy. If forwarding is enabled, we must send client request to
3931 * parent proxy and receive, parse and resend parent proxy answer.
3933 if (http->ssl && !use_ssl_tunnel)
3935 if (fwd->forward_host != NULL)
3937 char server_response[BUFFER_SIZE];
3940 char *hdr = list_to_text(csp->headers);
3941 memset(server_response, 0, sizeof(server_response));
3945 log_error(LOG_LEVEL_FATAL,
3946 "Out of memory parsing client header");
3948 list_remove_all(csp->headers);
3951 * Sending client's CONNECT request to the parent proxy
3953 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
3959 log_error(LOG_LEVEL_CONNECT,
3960 "Sending request headers to: %s failed", http->hostport);
3961 mark_server_socket_tainted(csp);
3962 close_client_ssl_connection(csp);
3966 /* Waiting for parent proxy server response */
3967 len = read_socket(csp->server_connection.sfd, server_response,
3968 sizeof(server_response)-1);
3972 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
3973 "server on socket %d.", csp->server_connection.sfd);
3975 rsp = error_response(csp, "no-server-data");
3978 send_crunch_response(csp, rsp);
3980 mark_server_socket_tainted(csp);
3981 close_client_ssl_connection(csp);
3986 * Test if the connection to the destination server was
3987 * established successfully by the parent proxy.
3989 if (!tunnel_established_successfully(server_response, (unsigned int)len))
3991 log_error(LOG_LEVEL_ERROR,
3992 "The forwarder %s failed to establish a connection with %s",
3993 fwd->forward_host, http->host);
3994 rsp = error_response(csp, "connect-failed");
3997 send_crunch_response(csp, rsp);
3999 mark_server_socket_tainted(csp);
4000 close_client_ssl_connection(csp);
4003 } /* -END- if (fwd->forward_host != NULL) */
4006 * We can now create the TLS/SSL connection with the destination server.
4008 int ret = create_server_ssl_connection(csp);
4011 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4012 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4015 * If the server certificate is invalid, we must inform
4016 * the client and then close connection to the client.
4018 ssl_send_certificate_error(csp);
4019 close_client_and_server_ssl_connections(csp);
4022 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4023 || csp->server_cert_verification_result == SSL_CERT_VALID)
4026 * The TLS/SSL connection wasn't created but an invalid
4027 * certificate wasn't detected. Report it as connection
4030 rsp = error_response(csp, "connect-failed");
4033 send_crunch_response(csp, rsp);
4035 close_client_and_server_ssl_connections(csp);
4039 }/* -END- if (http->ssl) */
4040 #endif /* def FEATURE_HTTPS_INSPECTION */
4042 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4043 save_connection_destination(csp->server_connection.sfd,
4044 http, fwd, &csp->server_connection);
4045 csp->server_connection.keep_alive_timeout =
4046 (unsigned)csp->config->keep_alive_timeout;
4048 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4050 csp->server_connection.requests_sent_total++;
4052 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4054 /* Client headers have been sent optimistically */
4055 assert(csp->headers->last == NULL);
4057 else if (http->ssl == 0 || (fwd->forward_host
4058 #ifdef FEATURE_HTTPS_INSPECTION
4063 if (send_http_request(csp))
4065 rsp = error_response(csp, "connect-failed");
4068 send_crunch_response(csp, rsp);
4076 * Using old solution with SSL tunnel or new solution with SSL proxy
4078 list_remove_all(csp->headers);
4079 #ifdef FEATURE_HTTPS_INSPECTION
4084 * We're running an SSL tunnel and we're not forwarding,
4085 * so just ditch the client headers, send the "connect succeeded"
4086 * message to the client, flush the rest, and get out of the way.
4088 if (write_socket_delayed(csp->cfd, CSUCCEED,
4089 strlen(CSUCCEED), get_write_delay(csp)))
4094 #ifdef FEATURE_HTTPS_INSPECTION
4098 * If server certificate has been verified and is invalid,
4099 * we must inform the client and then close the connection
4100 * with client and server.
4102 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4103 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4105 ssl_send_certificate_error(csp);
4106 close_client_and_server_ssl_connections(csp);
4109 if (send_https_request(csp))
4111 rsp = error_response(csp, "connect-failed");
4114 send_crunch_response(csp, rsp);
4116 close_client_and_server_ssl_connections(csp);
4120 #endif /* def FEATURE_HTTPS_INSPECTION */
4121 clear_iob(csp->client_iob);
4122 }/* -END- else ... if (http->ssl == 1) */
4124 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4126 /* XXX: should the time start earlier for optimistically sent data? */
4127 csp->server_connection.request_sent = time(NULL);
4129 handle_established_connection(csp);
4130 freez(csp->receive_buffer);
4135 /*********************************************************************
4137 * Function : fuzz_server_response
4139 * Description : Treat the input as a whole server response.
4142 * 1 : csp = Current client state (buffers, headers, etc...)
4143 * 2 : fuzz_input_file = File to read the input from.
4147 *********************************************************************/
4148 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4150 static struct forward_spec fwd; /* Zero'd due to being static */
4153 if (strcmp(fuzz_input_file, "-") == 0)
4155 /* XXX: Doesn't work yet. */
4156 csp->server_connection.sfd = 0;
4160 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4161 if (csp->server_connection.sfd == -1)
4163 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4168 csp->content_type |= CT_GIF;
4169 csp->action->flags |= ACTION_DEANIMATE;
4170 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4172 csp->http->path = strdup_or_die("/");
4173 csp->http->host = strdup_or_die("fuzz.example.org");
4174 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4175 /* Prevent client socket monitoring */
4176 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4177 csp->flags |= CSP_FLAG_CHUNKED;
4179 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4180 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4182 csp->content_type |= CT_DECLARED|CT_GIF;
4184 csp->config->socket_timeout = 0;
4186 cgi_init_error_messages();
4188 handle_established_connection(csp);
4189 freez(csp->receive_buffer);
4196 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4197 /*********************************************************************
4199 * Function : prepare_csp_for_next_request
4201 * Description : Put the csp in a mostly vergin state.
4204 * 1 : csp = Current client state (buffers, headers, etc...)
4208 *********************************************************************/
4209 static void prepare_csp_for_next_request(struct client_state *csp)
4211 csp->content_type = 0;
4212 csp->content_length = 0;
4213 csp->expected_content_length = 0;
4214 csp->expected_client_content_length = 0;
4215 list_remove_all(csp->headers);
4216 clear_iob(csp->iob);
4217 freez(csp->error_message);
4218 free_http_request(csp->http);
4219 destroy_list(csp->headers);
4220 #ifdef FEATURE_HTTPS_INSPECTION
4221 destroy_list(csp->https_headers);
4223 destroy_list(csp->tags);
4224 #ifdef FEATURE_CLIENT_TAGS
4225 destroy_list(csp->client_tags);
4226 freez(csp->client_address);
4228 free_current_action(csp->action);
4229 if (NULL != csp->fwd)
4231 unload_forward_spec(csp->fwd);
4234 /* XXX: Store per-connection flags someplace else. */
4235 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4236 #ifdef FEATURE_TOGGLE
4237 if (global_toggle_state)
4238 #endif /* def FEATURE_TOGGLE */
4240 csp->flags |= CSP_FLAG_TOGGLED_ON;
4243 if (csp->client_iob->eod > csp->client_iob->cur)
4245 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4246 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4248 assert(bytes_to_shift > 0);
4249 assert(data_length > 0);
4251 log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4252 data_length, bytes_to_shift);
4253 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4254 csp->client_iob->cur = csp->client_iob->buf;
4255 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4256 csp->client_iob->eod = csp->client_iob->buf + data_length;
4257 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4259 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4264 * We mainly care about resetting client_iob->cur so we don't
4265 * waste buffer space at the beginning and don't mess up the
4266 * request restoration done by cgi_show_request().
4268 * Freeing the buffer itself isn't technically necessary,
4269 * but makes debugging more convenient.
4271 clear_iob(csp->client_iob);
4274 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4277 /*********************************************************************
4281 * Description : This is little more than chat. We only "serve" to
4282 * to close (or remember) any socket that chat may have
4286 * 1 : csp = Current client state (buffers, headers, etc...)
4290 *********************************************************************/
4291 static void serve(struct client_state *csp)
4293 int config_file_change_detected = 0; /* Only used for debugging */
4294 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4295 #ifdef FEATURE_CONNECTION_SHARING
4296 static int monitor_thread_running = 0;
4297 #endif /* def FEATURE_CONNECTION_SHARING */
4298 int continue_chatting = 0;
4300 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4301 csp->ip_addr_str, csp->cfd);
4305 unsigned int latency;
4307 #ifdef FEATURE_HTTPS_INSPECTION
4308 if (continue_chatting && client_use_ssl(csp))
4310 continue_https_chat(csp);
4319 * If the request has been crunched,
4320 * the calculated latency is zero.
4322 latency = (unsigned)(csp->server_connection.response_received -
4323 csp->server_connection.request_sent) / 2;
4325 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4326 && (csp->flags & CSP_FLAG_CRUNCHED)
4327 && (csp->expected_client_content_length != 0))
4329 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4330 log_error(LOG_LEVEL_CONNECT,
4331 "Tainting client socket %d due to unread data.", csp->cfd);
4334 continue_chatting = (csp->config->feature_flags
4335 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4336 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4337 && (csp->cfd != JB_INVALID_SOCKET)
4338 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4339 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4340 || (csp->flags & CSP_FLAG_CHUNKED));
4342 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4343 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4345 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4347 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4349 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4350 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4351 || !socket_is_still_alive(csp->server_connection.sfd)
4352 || !(latency < csp->server_connection.keep_alive_timeout))
4354 log_error(LOG_LEVEL_CONNECT,
4355 "Closing server socket %d connected to %s. "
4356 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4357 csp->server_connection.sfd, csp->server_connection.host,
4358 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4359 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4360 socket_is_still_alive(csp->server_connection.sfd),
4361 csp->server_connection.keep_alive_timeout);
4362 #ifdef FEATURE_CONNECTION_SHARING
4363 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4365 forget_connection(csp->server_connection.sfd);
4367 #endif /* def FEATURE_CONNECTION_SHARING */
4368 #ifdef FEATURE_HTTPS_INSPECTION
4369 close_server_ssl_connection(csp);
4371 close_socket(csp->server_connection.sfd);
4372 mark_connection_closed(&csp->server_connection);
4376 if (continue_chatting && any_loaded_file_changed(csp))
4378 continue_chatting = 0;
4379 config_file_change_detected = 1;
4381 #ifdef FEATURE_HTTPS_INSPECTION
4382 if (continue_chatting && client_use_ssl(csp) &&
4383 csp->ssl_with_client_is_opened == 0)
4385 continue_chatting = 0;
4386 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4387 "The TLS session has been terminated.", csp->cfd);
4391 if (continue_chatting)
4393 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4394 && socket_is_still_alive(csp->cfd))
4396 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4397 "pipelined on socket %d and the socket is still alive.",
4398 csp->requests_received_total+1, csp->cfd);
4399 prepare_csp_for_next_request(csp);
4403 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
4405 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4407 log_error(LOG_LEVEL_CONNECT,
4408 "Waiting for the next client request on socket %d. "
4409 "Keeping the server socket %d to %s open.",
4410 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
4414 log_error(LOG_LEVEL_CONNECT,
4415 "Waiting for the next client request on socket %d. "
4416 "No server socket to keep open.", csp->cfd);
4420 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4421 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
4422 && socket_is_still_alive(csp->cfd))
4424 log_error(LOG_LEVEL_CONNECT,
4425 "Data arrived in time on client socket %d. Requests so far: %u",
4426 csp->cfd, csp->requests_received_total);
4427 prepare_csp_for_next_request(csp);
4431 #ifdef FEATURE_CONNECTION_SHARING
4432 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4433 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
4434 && (socket_is_still_alive(csp->server_connection.sfd))
4435 #ifdef FEATURE_HTTPS_INSPECTION
4436 && !server_use_ssl(csp)
4440 time_t time_open = time(NULL) - csp->server_connection.timestamp;
4442 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
4447 remember_connection(&csp->server_connection);
4448 csp->server_connection.sfd = JB_INVALID_SOCKET;
4449 drain_and_close_socket(csp->cfd);
4450 csp->cfd = JB_INVALID_SOCKET;
4451 privoxy_mutex_lock(&connection_reuse_mutex);
4452 if (!monitor_thread_running)
4454 monitor_thread_running = 1;
4455 privoxy_mutex_unlock(&connection_reuse_mutex);
4456 wait_for_alive_connections();
4457 privoxy_mutex_lock(&connection_reuse_mutex);
4458 monitor_thread_running = 0;
4460 privoxy_mutex_unlock(&connection_reuse_mutex);
4462 #endif /* def FEATURE_CONNECTION_SHARING */
4466 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4468 log_error(LOG_LEVEL_CONNECT,
4469 "Closing server socket %d connected to %s. Keep-alive: %u. "
4470 "Tainted: %u. Socket alive: %u. Timeout: %u. "
4471 "Configuration file change detected: %u",
4472 csp->server_connection.sfd, csp->server_connection.host,
4473 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4474 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4475 socket_is_still_alive(csp->server_connection.sfd),
4476 csp->server_connection.keep_alive_timeout,
4477 config_file_change_detected);
4479 } while (continue_chatting);
4483 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4485 if (csp->cfd != JB_INVALID_SOCKET)
4487 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
4488 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
4489 "Configuration file change detected: %u. Requests received: %u.",
4490 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
4491 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
4492 config_file_change_detected, csp->requests_received_total);
4493 #ifdef FEATURE_HTTPS_INSPECTION
4494 close_client_ssl_connection(csp);
4496 drain_and_close_socket(csp->cfd);
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 free_csp_resources(csp);
4521 csp->flags &= ~CSP_FLAG_ACTIVE;
4527 /*********************************************************************
4529 * Function : server_thread
4531 * Description : We only exist to call `serve' in a threaded environment.
4534 * 1 : data = Current client state (buffers, headers, etc...)
4536 * Returns : Always 0.
4538 *********************************************************************/
4539 static int32 server_thread(void *data)
4541 serve((struct client_state *) data);
4548 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4549 /*********************************************************************
4553 * Description : Print usage info & exit.
4555 * Parameters : Pointer to argv[0] for identifying ourselves
4559 *********************************************************************/
4560 static void usage(const char *name)
4562 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4563 "Usage: %s [--config-test] "
4566 #endif /* defined(unix) */
4569 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4570 #endif /* defined(unix) */
4571 "[--version] [configfile]\n",
4575 show_fuzz_usage(name);
4578 printf("Aborting\n");
4583 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4586 #ifdef MUTEX_LOCKS_AVAILABLE
4587 /*********************************************************************
4589 * Function : privoxy_mutex_lock
4591 * Description : Locks a mutex.
4594 * 1 : mutex = The mutex to lock.
4596 * Returns : Void. May exit in case of errors.
4598 *********************************************************************/
4599 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4601 #ifdef FEATURE_PTHREAD
4602 int err = pthread_mutex_lock(mutex);
4605 if (mutex != &log_mutex)
4607 log_error(LOG_LEVEL_FATAL,
4608 "Mutex locking failed: %s.\n", strerror(err));
4613 EnterCriticalSection(mutex);
4614 #endif /* def FEATURE_PTHREAD */
4618 /*********************************************************************
4620 * Function : privoxy_mutex_unlock
4622 * Description : Unlocks a mutex.
4625 * 1 : mutex = The mutex to unlock.
4627 * Returns : Void. May exit in case of errors.
4629 *********************************************************************/
4630 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4632 #ifdef FEATURE_PTHREAD
4633 int err = pthread_mutex_unlock(mutex);
4636 if (mutex != &log_mutex)
4638 log_error(LOG_LEVEL_FATAL,
4639 "Mutex unlocking failed: %s.\n", strerror(err));
4644 LeaveCriticalSection(mutex);
4645 #endif /* def FEATURE_PTHREAD */
4649 /*********************************************************************
4651 * Function : privoxy_mutex_init
4653 * Description : Prepares a mutex.
4656 * 1 : mutex = The mutex to initialize.
4658 * Returns : Void. May exit in case of errors.
4660 *********************************************************************/
4661 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4663 #ifdef FEATURE_PTHREAD
4664 int err = pthread_mutex_init(mutex, 0);
4667 printf("Fatal error. Mutex initialization failed: %s.\n",
4672 InitializeCriticalSection(mutex);
4673 #endif /* def FEATURE_PTHREAD */
4675 #endif /* def MUTEX_LOCKS_AVAILABLE */
4677 /*********************************************************************
4679 * Function : initialize_mutexes
4681 * Description : Prepares mutexes if mutex support is available.
4685 * Returns : Void, exits in case of errors.
4687 *********************************************************************/
4688 static void initialize_mutexes(void)
4690 #ifdef MUTEX_LOCKS_AVAILABLE
4692 * Prepare global mutex semaphores
4695 #ifdef FEATURE_HTTPS_INSPECTION
4696 privoxy_mutex_init(&certificate_mutex);
4697 privoxy_mutex_init(&ssl_init_mutex);
4700 privoxy_mutex_init(&log_mutex);
4701 privoxy_mutex_init(&log_init_mutex);
4702 privoxy_mutex_init(&connection_reuse_mutex);
4703 #ifdef FEATURE_EXTERNAL_FILTERS
4704 privoxy_mutex_init(&external_filter_mutex);
4706 #ifdef FEATURE_CLIENT_TAGS
4707 privoxy_mutex_init(&client_tags_mutex);
4709 #ifdef FEATURE_EXTENDED_STATISTICS
4710 privoxy_mutex_init(&filter_statistics_mutex);
4711 privoxy_mutex_init(&block_statistics_mutex);
4715 * XXX: The assumptions below are a bit naive
4716 * and can cause locks that aren't necessary.
4718 * For example older FreeBSD versions (< 6.x?)
4719 * have no gethostbyname_r, but gethostbyname is
4722 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4723 privoxy_mutex_init(&resolver_mutex);
4724 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4726 * XXX: should we use a single mutex for
4727 * localtime() and gmtime() as well?
4729 #ifndef HAVE_GMTIME_R
4730 privoxy_mutex_init(&gmtime_mutex);
4731 #endif /* ndef HAVE_GMTIME_R */
4733 #ifndef HAVE_LOCALTIME_R
4734 privoxy_mutex_init(&localtime_mutex);
4735 #endif /* ndef HAVE_GMTIME_R */
4737 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4738 privoxy_mutex_init(&rand_mutex);
4739 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4741 #endif /* def MUTEX_LOCKS_AVAILABLE */
4744 /*********************************************************************
4748 * Description : Load the config file and start the listen loop.
4749 * This function is a lot more *sane* with the `load_config'
4750 * and `listen_loop' functions; although it stills does
4751 * a *little* too much for my taste.
4754 * 1 : argc = Number of parameters (including $0).
4755 * 2 : argv = Array of (char *)'s to the parameters.
4757 * Returns : 1 if : can't open config file, unrecognized directive,
4758 * stats requested in multi-thread mode, can't open the
4759 * log file, can't open the jar file, listen port is invalid,
4760 * any load fails, and can't bind port.
4762 * Else main never returns, the process must be signaled
4763 * to terminate execution. Or, on Windows, use the
4764 * "File", "Exit" menu option.
4766 *********************************************************************/
4768 int real_main(int argc, char **argv)
4770 int main(int argc, char **argv)
4774 int do_config_test = 0;
4775 #ifndef HAVE_ARC4RANDOM
4776 unsigned int random_seed;
4779 struct passwd *pw = NULL;
4780 struct group *grp = NULL;
4782 char *pre_chroot_nslookup_to_load_resolver = NULL;
4785 char *fuzz_input_type = NULL;
4786 char *fuzz_input_file = NULL;
4793 #if !defined(_WIN32)
4800 /* Prepare mutexes if supported and necessary. */
4801 initialize_mutexes();
4803 /* Enable logging until further notice. */
4807 * Parse the command line arguments
4809 * XXX: simply printing usage information in case of
4810 * invalid arguments isn't particularly user friendly.
4812 while (++argc_pos < argc)
4815 /* Check to see if the service must be installed or uninstalled */
4816 if (strncmp(argv[argc_pos], "--install", 9) == 0)
4818 const char *pName = argv[argc_pos] + 9;
4821 exit((install_service(pName)) ? 0 : 1);
4823 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4825 const char *pName = argv[argc_pos] + 11;
4828 exit((uninstall_service(pName)) ? 0 : 1);
4830 else if (strcmp(argv[argc_pos], "--service") == 0)
4832 bRunAsService = TRUE;
4833 w32_set_service_cwd();
4834 atexit(w32_service_exit_notify);
4837 #endif /* defined(_WIN32) */
4840 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4842 if (strcmp(argv[argc_pos], "--help") == 0)
4847 else if (strcmp(argv[argc_pos], "--version") == 0)
4849 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4855 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4857 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4861 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4863 if (++argc_pos == argc) usage(argv[0]);
4864 pidfile = strdup_or_die(argv[argc_pos]);
4867 else if (strcmp(argv[argc_pos], "--user") == 0)
4872 if (++argc_pos == argc) usage(argv[argc_pos]);
4874 user_arg = strdup_or_die(argv[argc_pos]);
4875 group_name = strchr(user_arg, '.');
4876 if (NULL != group_name)
4878 /* Nul-terminate the user name */
4881 /* Skip the former delimiter to actually reach the group name */
4884 grp = getgrnam(group_name);
4887 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4890 pw = getpwnam(user_arg);
4893 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4899 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4901 if (++argc_pos == argc) usage(argv[0]);
4902 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4905 else if (strcmp(argv[argc_pos], "--chroot") == 0)
4909 #endif /* defined(unix) */
4911 else if (strcmp(argv[argc_pos], "--config-test") == 0)
4916 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4919 if (argc < argc_pos + 2) usage(argv[0]);
4920 fuzz_input_type = argv[argc_pos];
4922 fuzz_input_file = argv[argc_pos];
4924 else if (strcmp(argv[argc_pos], "--stfu") == 0)
4926 set_debug_level(LOG_LEVEL_STFU);
4929 else if (argc_pos + 1 != argc)
4932 * This is neither the last command line
4933 * option, nor was it recognized before,
4934 * therefore it must be invalid.
4940 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4942 configfile = argv[argc_pos];
4945 } /* -END- while (more arguments) */
4947 show_version(Argv[0]);
4950 if (*configfile != '/')
4952 char cwd[BUFFER_SIZE];
4954 size_t abs_file_size;
4956 /* make config-filename absolute here */
4957 if (NULL == getcwd(cwd, sizeof(cwd)))
4959 perror("failed to get current working directory");
4963 basedir = strdup_or_die(cwd);
4965 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4966 abs_file = malloc_or_die(abs_file_size);
4967 strlcpy(abs_file, basedir, abs_file_size);
4968 strlcat(abs_file, "/", abs_file_size);
4969 strlcat(abs_file, configfile, abs_file_size);
4970 configfile = abs_file;
4972 #endif /* defined unix */
4976 clients->next = NULL;
4978 /* XXX: factor out initialising after the next stable release. */
4983 #ifndef HAVE_ARC4RANDOM
4984 random_seed = (unsigned int)time(NULL);
4986 srandom(random_seed);
4989 #endif /* ifdef HAVE_RANDOM */
4990 #endif /* ifndef HAVE_ARC4RANDOM */
4993 * Unix signal handling
4995 * Catch the abort, interrupt and terminate signals for a graceful exit
4996 * Catch the hangup signal so the errlog can be reopened.
4998 * Ignore the broken pipe signal as connection failures
4999 * are handled when and where they occur without relying
5002 #if !defined(_WIN32)
5005 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5007 for (idx = 0; idx < SZ(catched_signals); idx++)
5009 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5010 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5012 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5013 #endif /* ifdef sun */
5015 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5019 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5021 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5025 #else /* ifdef _WIN32 */
5026 # ifdef _WIN_CONSOLE
5028 * We *are* in a windows console app.
5029 * Print a verbose messages about FAQ's and such
5031 printf("%s", win32_blurb);
5032 # endif /* def _WIN_CONSOLE */
5033 #endif /* def _WIN32 */
5036 if (fuzz_input_type != NULL)
5038 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5040 log_error(LOG_LEVEL_FATAL,
5041 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5042 "Various data structures are static which is unsafe when using threads.");
5047 exit(NULL == load_config());
5050 /* Initialize the CGI subsystem */
5051 cgi_init_error_messages();
5054 * If running on unix and without the --no-daemon
5055 * option, become a daemon. I.e. fork, detach
5056 * from tty and get process group leadership
5065 if (pid < 0) /* error */
5070 else if (pid != 0) /* parent */
5075 * must check for errors
5076 * child died due to missing files aso
5079 wpid = waitpid(pid, &status, WNOHANG);
5091 * stderr (fd 2) will be closed later on,
5092 * when the config file has been parsed.
5098 * Reserve fd 0 and 1 to prevent abort() and friends
5099 * from sending stuff to the clients or servers.
5101 fd = open("/dev/null", O_RDONLY);
5104 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5108 if (dup2(fd, 0) == -1)
5110 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5114 fd = open("/dev/null", O_WRONLY);
5117 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5121 if (dup2(fd, 1) == -1)
5123 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5128 #ifdef FEATURE_EXTERNAL_FILTERS
5129 for (fd = 0; fd < 3; fd++)
5131 mark_socket_for_close_on_execute(fd);
5137 } /* -END- if (daemon_mode) */
5140 * As soon as we have written the PID file, we can switch
5141 * to the user and group ID indicated by the --user option
5143 if (pidfile != NULL)
5145 write_pid_file(pidfile);
5149 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5151 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5155 if (setgroups(1, &grp->gr_gid))
5157 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5160 else if (initgroups(pw->pw_name, pw->pw_gid))
5162 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5168 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5170 /* Read the time zone file from /etc before doing chroot. */
5172 if (NULL != pre_chroot_nslookup_to_load_resolver
5173 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5175 /* Initialize resolver library. */
5176 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5178 if (chroot(pw->pw_dir) < 0)
5180 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5184 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5187 if (setuid(pw->pw_uid))
5189 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5193 char putenv_dummy[64];
5195 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5196 if (putenv(putenv_dummy) != 0)
5198 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5201 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5202 if (putenv(putenv_dummy) != 0)
5204 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5210 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5213 #endif /* defined unix */
5216 /* This will be FALSE unless the command line specified --service
5220 /* Yup, so now we must attempt to establish a connection
5221 * with the service dispatcher. This will only work if this
5222 * process was launched by the service control manager to
5223 * actually run as a service. If this isn't the case, i've
5224 * known it take around 30 seconds or so for the call to return.
5227 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5228 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5230 /* Service has run, and at this point is now being stopped, so just return */
5235 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5237 /* An error occurred. Usually it's because --service was wrongly specified
5238 * and we were unable to connect to the Service Control Dispatcher because
5239 * it wasn't expecting us and is therefore not listening.
5241 * For now, just continue below to call the listen_loop function.
5244 #endif /* def _WIN32 */
5254 /*********************************************************************
5256 * Function : bind_port_helper
5258 * Description : Bind the listen port. Handles logging, and aborts
5262 * 1 : haddr = Host address to bind to. Use NULL to bind to
5264 * 2 : hport = Specifies port to bind to.
5265 * 3 : backlog = Listen backlog.
5267 * Returns : Port that was opened.
5269 *********************************************************************/
5270 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5275 result = bind_port(haddr, hport, backlog, &bfd);
5279 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5283 log_error(LOG_LEVEL_FATAL,
5284 "can't bind to %s:%d: There may be another Privoxy "
5285 "or some other proxy running on port %d",
5286 bind_address, hport, hport);
5289 log_error(LOG_LEVEL_FATAL,
5290 "can't bind to %s:%d: The hostname is not resolvable",
5291 bind_address, hport);
5294 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5295 bind_address, hport);
5298 /* shouldn't get here */
5299 return JB_INVALID_SOCKET;
5304 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5309 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5317 /*********************************************************************
5319 * Function : bind_ports_helper
5321 * Description : Bind the listen ports. Handles logging, and aborts
5325 * 1 : config = Privoxy configuration. Specifies ports
5327 * 2 : sockets = Preallocated array of opened sockets
5328 * corresponding to specification in config.
5329 * All non-opened sockets will be set to
5330 * JB_INVALID_SOCKET.
5332 * Returns : Nothing. Inspect sockets argument.
5334 *********************************************************************/
5335 static void bind_ports_helper(struct configuration_spec * config,
5336 jb_socket sockets[])
5340 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5342 if (config->hport[i])
5344 sockets[i] = bind_port_helper(config->haddr[i],
5345 config->hport[i], config->listen_backlog);
5346 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5347 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5349 struct accept_filter_arg af_options;
5350 bzero(&af_options, sizeof(af_options));
5351 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5352 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5353 sizeof(af_options)))
5355 log_error(LOG_LEVEL_ERROR,
5356 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5363 sockets[i] = JB_INVALID_SOCKET;
5366 config->need_bind = 0;
5370 /*********************************************************************
5372 * Function : close_ports_helper
5374 * Description : Close listenings ports.
5377 * 1 : sockets = Array of opened and non-opened sockets to
5378 * close. All sockets will be set to
5379 * JB_INVALID_SOCKET.
5381 * Returns : Nothing.
5383 *********************************************************************/
5384 static void close_ports_helper(jb_socket sockets[])
5388 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5390 if (JB_INVALID_SOCKET != sockets[i])
5392 close_socket(sockets[i]);
5394 sockets[i] = JB_INVALID_SOCKET;
5400 /* Without this simple workaround we get this compiler warning from _beginthread
5401 * warning C4028: formal parameter 1 different from declaration
5403 void w32_service_listen_loop(void *p)
5407 #endif /* def _WIN32 */
5410 /*********************************************************************
5412 * Function : listen_loop
5414 * Description : bind the listen port and enter a "FOREVER" listening loop.
5420 *********************************************************************/
5421 static void listen_loop(void)
5423 struct client_states *csp_list = NULL;
5424 struct client_state *csp = NULL;
5425 jb_socket bfds[MAX_LISTENING_SOCKETS];
5426 struct configuration_spec *config;
5427 unsigned int active_threads = 0;
5428 #if defined(FEATURE_PTHREAD)
5429 pthread_attr_t attrs;
5431 pthread_attr_init(&attrs);
5432 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
5435 config = load_config();
5437 #ifdef FEATURE_CONNECTION_SHARING
5439 * XXX: Should be relocated once it no
5440 * longer needs to emit log messages.
5442 initialize_reusable_connections();
5443 #endif /* def FEATURE_CONNECTION_SHARING */
5445 bind_ports_helper(config, bfds);
5447 #ifdef FEATURE_GRACEFUL_TERMINATION
5448 while (!g_terminate)
5453 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
5454 while (waitpid(-1, NULL, WNOHANG) > 0)
5456 /* zombie children */
5458 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
5461 * Free data that was used by died threads
5463 active_threads = sweep();
5467 * Re-open the errlog after HUP signal
5469 if (received_hup_signal)
5471 if (NULL != config->logfile)
5473 init_error_log(Argv[0], config->logfile);
5475 received_hup_signal = 0;
5479 csp_list = zalloc_or_die(sizeof(*csp_list));
5480 csp = &csp_list->csp;
5482 log_error(LOG_LEVEL_CONNECT,
5483 "Waiting for the next client connection. Currently active threads: %u",
5487 * This config may be outdated, but for accept_connection()
5488 * it's fresh enough.
5490 csp->config = config;
5492 if (!accept_connection(csp, bfds))
5494 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
5499 csp->flags |= CSP_FLAG_ACTIVE;
5500 csp->server_connection.sfd = JB_INVALID_SOCKET;
5502 csp->config = config = load_config();
5504 if (config->need_bind)
5507 * Since we were listening to the "old port", we will not see
5508 * a "listen" param change until the next request. So, at
5509 * least 1 more request must be made for us to find the new
5510 * setting. I am simply closing the old socket and binding the
5513 * Which-ever is correct, we will serve 1 more page via the
5514 * old settings. This should probably be a "show-status"
5515 * request. This should not be a so common of an operation
5516 * that this will hurt people's feelings.
5519 close_ports_helper(bfds);
5521 bind_ports_helper(config, bfds);
5524 #ifdef FEATURE_TOGGLE
5525 if (global_toggle_state)
5526 #endif /* def FEATURE_TOGGLE */
5528 csp->flags |= CSP_FLAG_TOGGLED_ON;
5531 if (run_loader(csp))
5533 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5534 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5538 if (block_acl(NULL,csp))
5540 log_error(LOG_LEVEL_CONNECT,
5541 "Connection from %s on %s (socket %d) dropped due to ACL",
5542 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5543 close_socket(csp->cfd);
5544 freez(csp->ip_addr_str);
5545 freez(csp->listen_addr_str);
5549 #endif /* def FEATURE_ACL */
5551 if ((0 != config->max_client_connections)
5552 && (active_threads >= config->max_client_connections))
5554 log_error(LOG_LEVEL_CONNECT,
5555 "Rejecting connection from %s. Maximum number of connections reached.",
5557 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5558 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5559 close_socket(csp->cfd);
5560 freez(csp->ip_addr_str);
5561 freez(csp->listen_addr_str);
5566 /* add it to the list of clients */
5567 csp_list->next = clients->next;
5568 clients->next = csp_list;
5570 if (config->multi_threaded)
5574 /* this is a switch () statement in the C preprocessor - ugh */
5575 #undef SELECTED_ONE_OPTION
5577 /* Use Pthreads in preference to native code */
5578 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5579 #define SELECTED_ONE_OPTION
5581 pthread_t the_thread;
5584 ret = pthread_create(&the_thread, &attrs,
5585 (void * (*)(void *))serve, csp);
5586 child_id = ret ? -1 : 0;
5590 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5591 #define SELECTED_ONE_OPTION
5592 child_id = _beginthread(
5593 (void (*)(void *))serve,
5598 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5599 #define SELECTED_ONE_OPTION
5601 thread_id tid = spawn_thread
5602 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5604 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5606 child_id = (int) tid;
5615 #if !defined(SELECTED_ONE_OPTION)
5618 /* This block is only needed when using fork().
5619 * When using threads, the server thread was
5620 * created and run by the call to _beginthread().
5622 if (child_id == 0) /* child */
5625 #ifdef FEATURE_TOGGLE
5626 int inherited_toggle_state = global_toggle_state;
5627 #endif /* def FEATURE_TOGGLE */
5632 * If we've been toggled or we've blocked the request, tell Mom
5635 #ifdef FEATURE_TOGGLE
5636 if (inherited_toggle_state != global_toggle_state)
5638 rc |= RC_FLAG_TOGGLED;
5640 #endif /* def FEATURE_TOGGLE */
5642 #ifdef FEATURE_STATISTICS
5643 if (csp->flags & CSP_FLAG_REJECTED)
5645 rc |= RC_FLAG_BLOCKED;
5647 #endif /* ndef FEATURE_STATISTICS */
5651 else if (child_id > 0) /* parent */
5653 /* in a fork()'d environment, the parent's
5654 * copy of the client socket and the CSP
5658 #if !defined(_WIN32) && !defined(__CYGWIN__)
5660 wait(&child_status);
5663 * Evaluate child's return code: If the child has
5664 * - been toggled, toggle ourselves
5665 * - blocked its request, bump up the stats counter
5668 #ifdef FEATURE_TOGGLE
5669 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5671 global_toggle_state = !global_toggle_state;
5673 #endif /* def FEATURE_TOGGLE */
5675 #ifdef FEATURE_STATISTICS
5677 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5681 #endif /* def FEATURE_STATISTICS */
5683 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5684 close_socket(csp->cfd);
5685 csp->flags &= ~CSP_FLAG_ACTIVE;
5689 #undef SELECTED_ONE_OPTION
5690 /* end of cpp switch () */
5695 * Spawning the child failed, assume it's because
5696 * there are too many children running already.
5697 * XXX: If you assume ...
5699 log_error(LOG_LEVEL_ERROR,
5700 "Unable to take any additional connections: %E. Active threads: %u",
5702 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5703 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5704 close_socket(csp->cfd);
5705 csp->flags &= ~CSP_FLAG_ACTIVE;
5714 #if defined(FEATURE_PTHREAD)
5715 pthread_attr_destroy(&attrs);
5718 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5720 #ifdef FEATURE_HTTPS_INSPECTION
5721 /* Clean up. Aim: free all memory (no leaks) */
5725 #ifdef FEATURE_GRACEFUL_TERMINATION
5727 log_error(LOG_LEVEL_INFO, "Graceful termination requested");
5729 unload_current_config_file();
5730 unload_current_actions_file();
5731 unload_current_re_filterfile();
5732 #ifdef FEATURE_TRUST
5733 unload_current_trust_file();
5736 if (config->multi_threaded)
5743 } while ((clients->next != NULL) && (--i > 0));
5747 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5757 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5758 /* Cleanup - remove taskbar icon etc. */
5763 #endif /* FEATURE_GRACEFUL_TERMINATION */