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-2018 the
9 * Privoxy team. http://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
102 #endif /* def __GLIBC__ */
107 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
108 #endif /* HAVE_POLL */
115 #ifdef FEATURE_HTTPS_FILTERING
121 #include "miscutil.h"
123 #include "jbsockets.h"
128 #include "urlmatch.h"
129 #ifdef FEATURE_CLIENT_TAGS
130 #include "client-tags.h"
134 struct client_states clients[1];
135 struct file_list files[1];
137 #ifdef FEATURE_STATISTICS
138 int urls_read = 0; /* total nr of urls read inc rejected */
139 int urls_rejected = 0; /* total nr of urls rejected */
140 #endif /* def FEATURE_STATISTICS */
142 #ifdef FEATURE_GRACEFUL_TERMINATION
146 #if !defined(_WIN32) && !defined(__OS2__)
147 static void sig_handler(int the_signal);
149 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
150 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
151 static jb_err get_server_headers(struct client_state *csp);
152 static const char *crunch_reason(const struct http_response *rsp);
153 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp);
154 static char *get_request_line(struct client_state *csp);
155 static jb_err receive_client_request(struct client_state *csp);
156 static jb_err parse_client_request(struct client_state *csp);
157 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
158 static jb_err change_request_destination(struct client_state *csp);
159 static void chat(struct client_state *csp);
160 static void serve(struct client_state *csp);
161 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
162 static void usage(const char *myname);
164 static void initialize_mutexes(void);
165 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
166 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
167 static void close_ports_helper(jb_socket sockets[]);
168 static void listen_loop(void);
169 static void serve(struct client_state *csp);
172 static int32 server_thread(void *data);
173 #endif /* def __BEOS__ */
176 #define sleep(N) Sleep(((N) * 1000))
180 #define sleep(N) DosSleep(((N) * 100))
184 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
185 void show_fuzz_usage(const char *name);
188 #ifdef MUTEX_LOCKS_AVAILABLE
190 * XXX: Does the locking stuff really belong in this file?
192 privoxy_mutex_t log_mutex;
193 privoxy_mutex_t log_init_mutex;
194 privoxy_mutex_t connection_reuse_mutex;
196 #ifdef LIMIT_MUTEX_NUMBER
197 privoxy_mutex_t certificates_mutexes[32];
199 privoxy_mutex_t certificates_mutexes[65536];
200 #endif /* LIMIT_MUTEX_NUMBER */
201 privoxy_mutex_t rng_mutex;
203 #ifdef FEATURE_EXTERNAL_FILTERS
204 privoxy_mutex_t external_filter_mutex;
206 #ifdef FEATURE_CLIENT_TAGS
207 privoxy_mutex_t client_tags_mutex;
210 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
211 privoxy_mutex_t resolver_mutex;
212 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
214 #ifndef HAVE_GMTIME_R
215 privoxy_mutex_t gmtime_mutex;
216 #endif /* ndef HAVE_GMTIME_R */
218 #ifndef HAVE_LOCALTIME_R
219 privoxy_mutex_t localtime_mutex;
220 #endif /* ndef HAVE_GMTIME_R */
222 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
223 privoxy_mutex_t rand_mutex;
224 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
226 #endif /* def MUTEX_LOCKS_AVAILABLE */
229 const char *basedir = NULL;
230 const char *pidfile = NULL;
231 static int received_hup_signal = 0;
232 #endif /* defined unix */
234 /* HTTP snipplets. */
235 static const char CSUCCEED[] =
236 "HTTP/1.1 200 Connection established\r\n\r\n";
238 static const char CHEADER[] =
239 "HTTP/1.1 400 Invalid header received from client\r\n"
240 "Content-Type: text/plain\r\n"
241 "Connection: close\r\n\r\n"
242 "Invalid header received from client.\r\n";
244 static const char FTP_RESPONSE[] =
245 "HTTP/1.1 400 Invalid request received from client\r\n"
246 "Content-Type: text/plain\r\n"
247 "Connection: close\r\n\r\n"
248 "Invalid request. Privoxy doesn't support FTP.\r\n";
250 static const char GOPHER_RESPONSE[] =
251 "HTTP/1.1 400 Invalid request received from client\r\n"
252 "Content-Type: text/plain\r\n"
253 "Connection: close\r\n\r\n"
254 "Invalid request. Privoxy doesn't support gopher.\r\n";
256 /* XXX: should be a template */
257 static const char MISSING_DESTINATION_RESPONSE[] =
258 "HTTP/1.1 400 Bad request received from client\r\n"
259 "Content-Type: text/plain\r\n"
260 "Connection: close\r\n\r\n"
261 "Bad request. Privoxy was unable to extract the destination.\r\n";
263 /* XXX: should be a template */
264 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
265 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
266 "Content-Type: text/plain\r\n"
267 "Connection: close\r\n\r\n"
268 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
270 /* XXX: should be a template */
271 static const char MESSED_UP_REQUEST_RESPONSE[] =
272 "HTTP/1.1 400 Malformed request after rewriting\r\n"
273 "Content-Type: text/plain\r\n"
274 "Connection: close\r\n\r\n"
275 "Bad request. Messed up with header filters.\r\n";
277 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
278 "HTTP/1.1 503 Too many open connections\r\n"
279 "Content-Type: text/plain\r\n"
280 "Connection: close\r\n\r\n"
281 "Maximum number of open connections reached.\r\n";
283 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
284 "HTTP/1.1 504 Connection timeout\r\n"
285 "Content-Type: text/plain\r\n"
286 "Connection: close\r\n\r\n"
287 "The connection timed out because the client request didn't arrive in time.\r\n";
289 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
290 "HTTP/1.1 400 Failed reading client body\r\n"
291 "Content-Type: text/plain\r\n"
292 "Connection: close\r\n\r\n"
293 "Failed parsing or buffering the chunk-encoded client body.\r\n";
295 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
296 "HTTP/1.1 417 Expecting too much\r\n"
297 "Content-Type: text/plain\r\n"
298 "Connection: close\r\n\r\n"
299 "Privoxy detected an unsupported Expect header value.\r\n";
301 /* A function to crunch a response */
302 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
304 /* Crunch function flags */
305 #define CF_NO_FLAGS 0
306 /* Cruncher applies to forced requests as well */
307 #define CF_IGNORE_FORCE 1
308 /* Crunched requests are counted for the block statistics */
309 #define CF_COUNT_AS_REJECT 2
311 /* A crunch function and its flags */
314 const crunch_func_ptr cruncher;
318 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
320 /* Complete list of cruncher functions */
321 static const struct cruncher crunchers_all[] = {
322 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
323 { block_url, CF_COUNT_AS_REJECT },
325 { trust_url, CF_COUNT_AS_REJECT },
326 #endif /* def FEATURE_TRUST */
327 { redirect_url, CF_NO_FLAGS },
328 { dispatch_cgi, CF_IGNORE_FORCE},
332 /* Light version, used after tags are applied */
333 static const struct cruncher crunchers_light[] = {
334 { block_url, CF_COUNT_AS_REJECT },
335 { redirect_url, CF_NO_FLAGS },
341 * XXX: Don't we really mean
347 #if !defined(_WIN32) && !defined(__OS2__)
348 /*********************************************************************
350 * Function : sig_handler
352 * Description : Signal handler for different signals.
353 * Exit gracefully on TERM and INT
354 * or set a flag that will cause the errlog
355 * to be reopened by the main thread on HUP.
358 * 1 : the_signal = the signal cause this function to call
362 *********************************************************************/
363 static void sig_handler(int the_signal)
369 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
381 received_hup_signal = 1;
387 * We shouldn't be here, unless we catch signals
388 * in main() that we can't handle here!
390 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
398 /*********************************************************************
400 * Function : get_write_delay
402 * Description : Parse the delay-response parameter.
405 * 1 : csp = Current client state (buffers, headers, etc...)
407 * Returns : Number of milliseconds to delay writes.
409 *********************************************************************/
410 static unsigned int get_write_delay(const struct client_state *csp)
416 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
420 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
422 delay = (unsigned)strtol(newval, &endptr, 0);
425 log_error(LOG_LEVEL_FATAL,
426 "Invalid delay-response{} parameter: '%s'", newval);
434 /*********************************************************************
436 * Function : client_protocol_is_unsupported
438 * Description : Checks if the client used a known unsupported
439 * protocol and deals with it by sending an error
443 * 1 : csp = Current client state (buffers, headers, etc...)
444 * 2 : req = the first request line send by the client
446 * Returns : TRUE if an error response has been generated, or
447 * FALSE if the request doesn't look invalid.
449 *********************************************************************/
450 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
453 * If it's a FTP or gopher request, we don't support it.
455 * These checks are better than nothing, but they might
456 * not work in all configurations and some clients might
457 * have problems digesting the answer.
459 * They should, however, never cause more problems than
460 * Privoxy's old behaviour (returning the misleading HTML
463 * "Could not resolve http://(ftp|gopher)://example.org").
465 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
467 const char *response = NULL;
468 const char *protocol = NULL;
470 if (!strncmpic(req, "GET ftp://", 10))
472 response = FTP_RESPONSE;
477 response = GOPHER_RESPONSE;
480 log_error(LOG_LEVEL_ERROR,
481 "%s tried to use Privoxy as %s proxy: %s",
482 csp->ip_addr_str, protocol, req);
483 log_error(LOG_LEVEL_CLF,
484 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
486 write_socket_delayed(csp->cfd, response, strlen(response),
487 get_write_delay(csp));
496 /*********************************************************************
498 * Function : client_has_unsupported_expectations
500 * Description : Checks if the client used an unsupported expectation
501 * in which case an error message is delivered.
504 * 1 : csp = Current client state (buffers, headers, etc...)
506 * Returns : TRUE if an error response has been generated, or
507 * FALSE if the request doesn't look invalid.
509 *********************************************************************/
510 static int client_has_unsupported_expectations(const struct client_state *csp)
512 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
514 log_error(LOG_LEVEL_ERROR,
515 "Rejecting request from client %s with unsupported Expect header value",
517 log_error(LOG_LEVEL_CLF,
518 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
519 write_socket_delayed(csp->cfd,
520 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
521 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
522 get_write_delay(csp));
532 /*********************************************************************
534 * Function : get_request_destination_elsewhere
536 * Description : If the client's request was redirected into
537 * Privoxy without the client's knowledge,
538 * the request line lacks the destination host.
540 * This function tries to get it elsewhere,
541 * provided accept-intercepted-requests is enabled.
543 * "Elsewhere" currently only means "Host: header",
544 * but in the future we may ask the redirecting
545 * packet filter to look the destination up.
547 * If the destination stays unknown, an error
548 * response is send to the client and headers
549 * are freed so that chat() can return directly.
552 * 1 : csp = Current client state (buffers, headers, etc...)
553 * 2 : headers = a header list
555 * Returns : JB_ERR_OK if the destination is now known, or
556 * JB_ERR_PARSE if it isn't.
558 *********************************************************************/
559 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
563 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
565 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
566 " Privoxy isn't configured to accept intercepted requests.",
567 csp->ip_addr_str, csp->http->cmd);
568 /* XXX: Use correct size */
569 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
570 csp->ip_addr_str, csp->http->cmd);
572 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
573 get_write_delay(csp));
574 destroy_list(headers);
578 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
580 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
581 /* Split the domain we just got for pattern matching */
582 init_domain_components(csp->http);
589 /* We can't work without destination. Go spread the news.*/
591 req = list_to_text(headers);
593 /* XXX: Use correct size */
594 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
595 csp->ip_addr_str, csp->http->cmd);
596 log_error(LOG_LEVEL_ERROR,
597 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
598 csp->ip_addr_str, csp->http->cmd, req);
601 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
602 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
603 destroy_list(headers);
608 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
609 * to get the destination IP address, use it as host directly
610 * or do a reverse DNS lookup first.
615 /*********************************************************************
617 * Function : get_server_headers
619 * Description : Parses server headers in iob and fills them
620 * into csp->headers so that they can later be
624 * 1 : csp = Current client state (buffers, headers, etc...)
626 * Returns : JB_ERR_OK if everything went fine, or
627 * JB_ERR_PARSE if the headers were incomplete.
629 *********************************************************************/
630 static jb_err get_server_headers(struct client_state *csp)
632 int continue_hack_in_da_house = 0;
635 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
640 * continue hack in da house. Ignore the ending of
641 * this head and continue enlisting header lines.
642 * The reason is described below.
644 enlist(csp->headers, "");
645 continue_hack_in_da_house = 0;
648 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
651 * It's a bodyless continue response, don't
652 * stop header parsing after reaching its end.
654 * As a result Privoxy will concatenate the
655 * next response's head and parse and deliver
656 * the headers as if they belonged to one request.
658 * The client will separate them because of the
659 * empty line between them.
661 * XXX: What we're doing here is clearly against
662 * the intended purpose of the continue header,
663 * and under some conditions (HTTP/1.0 client request)
664 * it's a standard violation.
666 * Anyway, "sort of against the spec" is preferable
667 * to "always getting confused by Continue responses"
668 * (Privoxy's behaviour before this hack was added)
670 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
671 continue_hack_in_da_house = 1;
673 else if (*header == '\0')
676 * If the header is empty, but the Continue hack
677 * isn't active, we can assume that we reached the
678 * end of the buffer before we hit the end of the
681 * Inform the caller an let it decide how to handle it.
686 if (JB_ERR_MEMORY == enlist(csp->headers, header))
689 * XXX: Should we quit the request and return a
690 * out of memory error page instead?
692 log_error(LOG_LEVEL_ERROR,
693 "Out of memory while enlisting server headers. %s lost.",
703 /*********************************************************************
705 * Function : crunch_reason
707 * Description : Translates the crunch reason code into a string.
710 * 1 : rsp = a http_response
712 * Returns : A string with the crunch reason or an error description.
714 *********************************************************************/
715 static const char *crunch_reason(const struct http_response *rsp)
717 char * reason = NULL;
722 return "Internal error while searching for crunch reason";
725 switch (rsp->crunch_reason)
728 reason = "Unsupported HTTP feature";
734 reason = "Untrusted";
737 reason = "Redirected";
743 reason = "DNS failure";
745 case FORWARDING_FAILED:
746 reason = "Forwarding failed";
749 reason = "Connection failure";
752 reason = "Out of memory (may mask other reasons)";
754 case CONNECTION_TIMEOUT:
755 reason = "Connection timeout";
758 reason = "No server data received";
761 reason = "No reason recorded";
769 /*********************************************************************
771 * Function : log_applied_actions
773 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
777 * 1 : actions = Current action spec to log
781 *********************************************************************/
782 static void log_applied_actions(const struct current_action_spec *actions)
785 * The conversion to text requires lots of memory allocations so
786 * we only do the conversion if the user is actually interested.
788 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
790 char *actions_as_text = actions_to_line_of_text(actions);
791 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
792 freez(actions_as_text);
797 /*********************************************************************
799 * Function : send_crunch_response
801 * Description : Delivers already prepared response for
802 * intercepted requests, logs the interception
803 * and frees the response.
806 * 1 : csp = Current client state (buffers, headers, etc...)
807 * 2 : rsp = Fully prepared response. Will be freed on exit.
811 *********************************************************************/
812 static void send_crunch_response(const struct client_state *csp, struct http_response *rsp)
814 const struct http_request *http = csp->http;
818 assert(rsp->head != NULL);
822 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
826 * Extract the status code from the actual head
827 * that will be send to the client. It is the only
828 * way to get it right for all requests, including
829 * the fixed ones for out-of-memory problems.
831 * A head starts like this: 'HTTP/1.1 200...'
835 status_code[0] = rsp->head[9];
836 status_code[1] = rsp->head[10];
837 status_code[2] = rsp->head[11];
838 status_code[3] = '\0';
840 /* Log that the request was crunched and why. */
841 log_applied_actions(csp->action);
842 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
843 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
844 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
846 /* Write the answer to the client */
847 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length, get_write_delay(csp))
848 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length, get_write_delay(csp)))
850 /* There is nothing we can do about it. */
851 log_error(LOG_LEVEL_CONNECT,
852 "Couldn't deliver the error message for %s through client socket %d: %E",
853 http->url, csp->cfd);
856 /* Clean up and return */
857 if (cgi_error_memory() != rsp)
859 free_http_response(rsp);
865 /*********************************************************************
867 * Function : crunch_response_triggered
869 * Description : Checks if the request has to be crunched,
870 * and delivers the crunch response if necessary.
873 * 1 : csp = Current client state (buffers, headers, etc...)
874 * 2 : crunchers = list of cruncher functions to run
876 * Returns : TRUE if the request was answered with a crunch response
879 *********************************************************************/
880 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
882 struct http_response *rsp = NULL;
883 const struct cruncher *c;
886 * If CGI request crunching is disabled,
887 * check the CGI dispatcher out of order to
888 * prevent unintentional blocks or redirects.
890 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
891 && (NULL != (rsp = dispatch_cgi(csp))))
893 /* Deliver, log and free the interception response. */
894 send_crunch_response(csp, rsp);
895 csp->flags |= CSP_FLAG_CRUNCHED;
899 for (c = crunchers; c->cruncher != NULL; c++)
902 * Check the cruncher if either Privoxy is toggled
903 * on and the request isn't forced, or if the cruncher
904 * applies to forced requests as well.
906 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
907 !(csp->flags & CSP_FLAG_FORCED)) ||
908 (c->flags & CF_IGNORE_FORCE))
910 rsp = c->cruncher(csp);
913 /* Deliver, log and free the interception response. */
914 send_crunch_response(csp, rsp);
915 csp->flags |= CSP_FLAG_CRUNCHED;
916 #ifdef FEATURE_STATISTICS
917 if (c->flags & CF_COUNT_AS_REJECT)
919 csp->flags |= CSP_FLAG_REJECTED;
921 #endif /* def FEATURE_STATISTICS */
932 /*********************************************************************
934 * Function : build_request_line
936 * Description : Builds the HTTP request line.
938 * If a HTTP forwarder is used it expects the whole URL,
939 * web servers only get the path.
942 * 1 : csp = Current client state (buffers, headers, etc...)
943 * 2 : fwd = The forwarding spec used for the request
944 * XXX: Should use http->fwd instead.
945 * 3 : request_line = The old request line which will be replaced.
947 * Returns : Nothing. Terminates in case of memory problems.
949 *********************************************************************/
950 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
952 struct http_request *http = csp->http;
955 * Downgrade http version from 1.1 to 1.0
956 * if +downgrade action applies.
958 if ((csp->action->flags & ACTION_DOWNGRADE)
959 && (!strcmpic(http->ver, "HTTP/1.1")))
962 http->ver = strdup_or_die("HTTP/1.0");
966 * Rebuild the request line.
968 freez(*request_line);
969 *request_line = strdup(http->gpc);
970 string_append(request_line, " ");
972 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
974 string_append(request_line, http->url);
978 string_append(request_line, http->path);
980 string_append(request_line, " ");
981 string_append(request_line, http->ver);
983 if (*request_line == NULL)
985 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
987 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
991 /*********************************************************************
993 * Function : change_request_destination
995 * Description : Parse a (rewritten) request line and regenerate
996 * the http request data.
999 * 1 : csp = Current client state (buffers, headers, etc...)
1001 * Returns : Forwards the parse_http_request() return code.
1002 * Terminates in case of memory problems.
1004 *********************************************************************/
1005 static jb_err change_request_destination(struct client_state *csp)
1007 struct http_request *http = csp->http;
1010 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1011 csp->headers->first->str);
1012 free_http_request(http);
1013 err = parse_http_request(csp->headers->first->str, http);
1014 if (JB_ERR_OK != err)
1016 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1017 jb_err_to_string(err));
1024 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1025 /*********************************************************************
1027 * Function : server_response_is_complete
1029 * Description : Determines whether we should stop reading
1030 * from the server socket.
1033 * 1 : csp = Current client state (buffers, headers, etc...)
1034 * 2 : content_length = Length of content received so far.
1036 * Returns : TRUE if the response is complete,
1039 *********************************************************************/
1040 static int server_response_is_complete(struct client_state *csp,
1041 unsigned long long content_length)
1043 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1045 if (!strcmpic(csp->http->gpc, "HEAD"))
1048 * "HEAD" implies no body, we are thus expecting
1049 * no content. XXX: incomplete "list" of methods?
1051 csp->expected_content_length = 0;
1052 content_length_known = TRUE;
1053 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1056 if (csp->http->status == 204 || csp->http->status == 304)
1059 * Expect no body. XXX: incomplete "list" of status codes?
1061 csp->expected_content_length = 0;
1062 content_length_known = TRUE;
1063 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1066 return (content_length_known && ((0 == csp->expected_content_length)
1067 || (csp->expected_content_length <= content_length)));
1071 #ifdef FEATURE_CONNECTION_SHARING
1072 /*********************************************************************
1074 * Function : wait_for_alive_connections
1076 * Description : Waits for alive connections to timeout.
1082 *********************************************************************/
1083 static void wait_for_alive_connections(void)
1085 int connections_alive = close_unusable_connections();
1087 while (0 < connections_alive)
1089 log_error(LOG_LEVEL_CONNECT,
1090 "Waiting for %d connections to timeout.",
1093 connections_alive = close_unusable_connections();
1096 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1099 #endif /* def FEATURE_CONNECTION_SHARING */
1102 /*********************************************************************
1104 * Function : save_connection_destination
1106 * Description : Remembers a connection for reuse later on.
1109 * 1 : sfd = Open socket to remember.
1110 * 2 : http = The destination for the connection.
1111 * 3 : fwd = The forwarder settings used.
1112 * 4 : server_connection = storage.
1116 *********************************************************************/
1117 void save_connection_destination(jb_socket sfd,
1118 const struct http_request *http,
1119 const struct forward_spec *fwd,
1120 struct reusable_connection *server_connection)
1122 assert(sfd != JB_INVALID_SOCKET);
1123 assert(NULL != http->host);
1125 server_connection->sfd = sfd;
1126 server_connection->host = strdup_or_die(http->host);
1127 server_connection->port = http->port;
1129 assert(NULL != fwd);
1130 assert(server_connection->gateway_host == NULL);
1131 assert(server_connection->gateway_port == 0);
1132 assert(server_connection->forwarder_type == 0);
1133 assert(server_connection->forward_host == NULL);
1134 assert(server_connection->forward_port == 0);
1136 server_connection->forwarder_type = fwd->type;
1137 if (NULL != fwd->gateway_host)
1139 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1143 server_connection->gateway_host = NULL;
1145 server_connection->gateway_port = fwd->gateway_port;
1147 if (NULL != fwd->forward_host)
1149 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1153 server_connection->forward_host = NULL;
1155 server_connection->forward_port = fwd->forward_port;
1159 /*********************************************************************
1161 * Function : verify_request_length
1163 * Description : Checks if we already got the whole client requests
1164 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1167 * Data that doesn't belong to the current request is
1168 * either thrown away to let the client retry on a clean
1169 * socket, or stashed to be dealt with after the current
1170 * request is served.
1173 * 1 : csp = Current client state (buffers, headers, etc...)
1177 *********************************************************************/
1178 static void verify_request_length(struct client_state *csp)
1180 unsigned long long buffered_request_bytes =
1181 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1183 if ((csp->expected_client_content_length != 0)
1184 && (buffered_request_bytes != 0))
1186 if (csp->expected_client_content_length >= buffered_request_bytes)
1188 csp->expected_client_content_length -= buffered_request_bytes;
1189 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1190 "to account for the %llu ones we already got.",
1191 csp->expected_client_content_length, buffered_request_bytes);
1195 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1196 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1197 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1198 "Marking the server socket tainted after throwing %llu bytes away.",
1199 buffered_request_bytes - csp->expected_client_content_length);
1200 csp->expected_client_content_length = 0;
1201 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1204 if (csp->expected_client_content_length == 0)
1206 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1210 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1211 && ((csp->client_iob->cur < csp->client_iob->eod)
1212 || (csp->expected_client_content_length != 0)))
1214 if (strcmpic(csp->http->gpc, "GET")
1215 && strcmpic(csp->http->gpc, "HEAD")
1216 && strcmpic(csp->http->gpc, "TRACE")
1217 && strcmpic(csp->http->gpc, "OPTIONS")
1218 && strcmpic(csp->http->gpc, "DELETE"))
1220 /* XXX: this is an incomplete hack */
1221 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1222 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1226 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1228 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1230 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1231 log_error(LOG_LEVEL_CONNECT,
1232 "Possible pipeline attempt detected. The connection will not "
1233 "be kept alive and we will only serve the first request.");
1234 /* Nuke the pipelined requests from orbit, just to be sure. */
1235 clear_iob(csp->client_iob);
1240 * Keep the pipelined data around for now, we'll deal with
1241 * it once we're done serving the current request.
1243 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1244 assert(csp->client_iob->eod >= csp->client_iob->cur);
1245 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1246 "%d bytes of pipelined data received.",
1247 (int)(csp->client_iob->eod - csp->client_iob->cur));
1253 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1254 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1257 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1260 /*********************************************************************
1262 * Function : mark_server_socket_tainted
1264 * Description : Makes sure we don't reuse a server socket
1265 * (if we didn't read everything the server sent
1266 * us reusing the socket would lead to garbage).
1269 * 1 : csp = Current client state (buffers, headers, etc...)
1273 *********************************************************************/
1274 static void mark_server_socket_tainted(struct client_state *csp)
1277 * For consistency we always mark the server socket
1278 * tainted, however, to reduce the log noise we only
1279 * emit a log message if the server socket could have
1280 * actually been reused.
1282 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1283 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1285 log_error(LOG_LEVEL_CONNECT,
1286 "Marking the server socket %d tainted.",
1287 csp->server_connection.sfd);
1289 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1292 /*********************************************************************
1294 * Function : get_request_line
1296 * Description : Read the client request line.
1299 * 1 : csp = Current client state (buffers, headers, etc...)
1301 * Returns : Pointer to request line or NULL in case of errors.
1303 *********************************************************************/
1304 static char *get_request_line(struct client_state *csp)
1306 char buf[BUFFER_SIZE];
1307 char *request_line = NULL;
1310 memset(buf, 0, sizeof(buf));
1312 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1315 * If there are multiple pipelined requests waiting,
1316 * the flag will be set again once the next request
1319 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1321 request_line = get_header(csp->client_iob);
1322 if ((NULL != request_line) && ('\0' != *request_line))
1324 return request_line;
1328 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1329 "received yet. Continuing reading from %d.", csp->cfd);
1337 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1339 !data_is_available(csp->cfd, csp->config->socket_timeout)
1342 if (socket_is_still_alive(csp->cfd))
1344 log_error(LOG_LEVEL_CONNECT,
1345 "No request line on socket %d received in time. Timeout: %d.",
1346 csp->cfd, csp->config->socket_timeout);
1347 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1348 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1349 get_write_delay(csp));
1353 log_error(LOG_LEVEL_CONNECT,
1354 "The client side of the connection on socket %d got "
1355 "closed without sending a complete request line.", csp->cfd);
1360 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1362 if (len <= 0) return NULL;
1365 * If there is no memory left for buffering the
1366 * request, there is nothing we can do but hang up
1368 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1373 request_line = get_header(csp->client_iob);
1375 } while ((NULL != request_line) && ('\0' == *request_line));
1377 return request_line;
1383 CHUNK_STATUS_MISSING_DATA,
1384 CHUNK_STATUS_BODY_COMPLETE,
1385 CHUNK_STATUS_PARSE_ERROR
1389 /*********************************************************************
1391 * Function : chunked_body_is_complete
1393 * Description : Figures out whether or not a chunked body is complete.
1395 * Currently it always starts at the beginning of the
1396 * buffer which is somewhat wasteful and prevents Privoxy
1397 * from starting to forward the correctly parsed chunks
1398 * as soon as theoretically possible.
1400 * Should be modified to work with a common buffer,
1401 * and allow the caller to skip already parsed chunks.
1403 * This would allow the function to be used for unbuffered
1404 * response bodies as well.
1407 * 1 : iob = Buffer with the body to check.
1408 * 2 : length = Length of complete body
1410 * Returns : Enum with the result of the check.
1412 *********************************************************************/
1413 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1415 unsigned int chunksize;
1421 * We need at least a single digit, followed by "\r\n",
1422 * followed by an unknown amount of data, followed by "\r\n".
1424 if (p + 5 > iob->eod)
1426 return CHUNK_STATUS_MISSING_DATA;
1428 if (sscanf(p, "%x", &chunksize) != 1)
1430 return CHUNK_STATUS_PARSE_ERROR;
1434 * We want at least a single digit, followed by "\r\n",
1435 * followed by the specified amount of data, followed by "\r\n".
1437 if (p + chunksize + 5 > iob->eod)
1439 return CHUNK_STATUS_MISSING_DATA;
1442 /* Skip chunk-size. */
1443 p = strstr(p, "\r\n");
1446 return CHUNK_STATUS_PARSE_ERROR;
1448 /* Move beyond the chunkdata. */
1451 /* There should be another "\r\n" to skip */
1452 if (memcmp(p, "\r\n", 2))
1454 return CHUNK_STATUS_PARSE_ERROR;
1457 } while (chunksize > 0U);
1459 *length = (size_t)(p - iob->cur);
1460 assert(*length <= (size_t)(iob->eod - iob->cur));
1461 assert(p <= iob->eod);
1463 return CHUNK_STATUS_BODY_COMPLETE;
1468 /*********************************************************************
1470 * Function : receive_chunked_client_request_body
1472 * Description : Read the chunk-encoded client request body.
1473 * Failures are dealt with.
1476 * 1 : csp = Current client state (buffers, headers, etc...)
1478 * Returns : JB_ERR_OK or JB_ERR_PARSE
1480 *********************************************************************/
1481 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1484 enum chunk_status status;
1486 while (CHUNK_STATUS_MISSING_DATA ==
1487 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1489 char buf[BUFFER_SIZE];
1492 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1494 log_error(LOG_LEVEL_ERROR,
1495 "Timeout while waiting for the client body.");
1498 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1501 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1504 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1509 if (status != CHUNK_STATUS_BODY_COMPLETE)
1511 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1512 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1513 log_error(LOG_LEVEL_CLF,
1514 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1515 return JB_ERR_PARSE;
1517 log_error(LOG_LEVEL_CONNECT,
1518 "Chunked client body completely read. Length: %d", body_length);
1519 csp->expected_client_content_length = body_length;
1527 /*********************************************************************
1529 * Function : fuzz_chunked_transfer_encoding
1531 * Description : Treat the fuzzed input as chunked transfer encoding
1532 * to check and dechunk.
1535 * 1 : csp = Used to store the data.
1536 * 2 : fuzz_input_file = File to read the input from.
1538 * Returns : Result of dechunking
1540 *********************************************************************/
1541 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1544 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1545 enum chunk_status status;
1547 status = chunked_body_is_complete(csp->iob, &length);
1548 if (CHUNK_STATUS_BODY_COMPLETE != status)
1550 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1553 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1558 /*********************************************************************
1560 * Function : fuzz_client_request
1562 * Description : Try to get a client request from the fuzzed input.
1565 * 1 : csp = Current client state (buffers, headers, etc...)
1566 * 2 : fuzz_input_file = File to read the input from.
1568 * Returns : Result of fuzzing.
1570 *********************************************************************/
1571 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1576 csp->ip_addr_str = "fuzzer";
1578 if (strcmp(fuzz_input_file, "-") != 0)
1580 log_error(LOG_LEVEL_FATAL,
1581 "Fuzzed client requests can currenty only be read from stdin (-).");
1583 err = receive_client_request(csp);
1584 if (err != JB_ERR_OK)
1588 err = parse_client_request(csp);
1589 if (err != JB_ERR_OK)
1597 #endif /* def FUZZ */
1600 #ifdef FEATURE_FORCE_LOAD
1601 /*********************************************************************
1603 * Function : force_required
1605 * Description : Checks a request line to see if it contains
1606 * the FORCE_PREFIX. If it does, it is removed
1607 * unless enforcing requests has beend disabled.
1610 * 1 : request_line = HTTP request line
1612 * Returns : TRUE if force is required, FALSE otherwise.
1614 *********************************************************************/
1615 static int force_required(const struct client_state *csp, char *request_line)
1619 p = strstr(request_line, "http://");
1623 p += strlen("http://");
1627 /* Intercepted request usually don't specify the protocol. */
1631 /* Go to the beginning of the path */
1636 * If the path is missing the request line is invalid and we
1637 * are done here. The client-visible rejection happens later on.
1642 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1644 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1646 /* XXX: Should clean more carefully */
1647 strclean(request_line, FORCE_PREFIX);
1648 log_error(LOG_LEVEL_FORCE,
1649 "Enforcing request: \"%s\".", request_line);
1653 log_error(LOG_LEVEL_FORCE,
1654 "Ignored force prefix in request: \"%s\".", request_line);
1660 #endif /* def FEATURE_FORCE_LOAD */
1663 /*********************************************************************
1665 * Function : receive_client_request
1667 * Description : Read the client's request (more precisely the
1668 * client headers) and answer it if necessary.
1671 * 1 : csp = Current client state (buffers, headers, etc...)
1673 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1675 *********************************************************************/
1676 static jb_err receive_client_request(struct client_state *csp)
1678 char buf[BUFFER_SIZE];
1681 struct http_request *http;
1685 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1686 struct list header_list;
1687 struct list *headers = &header_list;
1689 /* We don't care if the arriving data is a valid HTTP request or not. */
1690 csp->requests_received_total++;
1694 memset(buf, 0, sizeof(buf));
1696 req = get_request_line(csp);
1699 mark_server_socket_tainted(csp);
1700 return JB_ERR_PARSE;
1702 assert(*req != '\0');
1704 if (client_protocol_is_unsupported(csp, req))
1706 return JB_ERR_PARSE;
1709 #ifdef FEATURE_FORCE_LOAD
1710 if (force_required(csp, req))
1712 csp->flags |= CSP_FLAG_FORCED;
1714 #endif /* def FEATURE_FORCE_LOAD */
1716 err = parse_http_request(req, http);
1718 if (JB_ERR_OK != err)
1720 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1721 get_write_delay(csp));
1722 /* XXX: Use correct size */
1723 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1724 log_error(LOG_LEVEL_ERROR,
1725 "Couldn't parse request line received from %s: %s",
1726 csp->ip_addr_str, jb_err_to_string(err));
1728 free_http_request(http);
1729 return JB_ERR_PARSE;
1732 /* grab the rest of the client's headers */
1736 p = get_header(csp->client_iob);
1740 /* There are no additional headers to read. */
1747 * We didn't receive a complete header
1748 * line yet, get the rest of it.
1750 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1752 log_error(LOG_LEVEL_ERROR,
1753 "Stopped grabbing the client headers.");
1754 destroy_list(headers);
1755 return JB_ERR_PARSE;
1758 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1761 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1762 destroy_list(headers);
1763 return JB_ERR_PARSE;
1766 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1769 * If there is no memory left for buffering the
1770 * request, there is nothing we can do but hang up
1772 destroy_list(headers);
1773 return JB_ERR_MEMORY;
1778 if (!strncmpic(p, "Transfer-Encoding:", 18))
1781 * XXX: should be called through sed()
1782 * but currently can't.
1784 client_transfer_encoding(csp, &p);
1787 * We were able to read a complete
1788 * header and can finally enlist it.
1795 if (http->host == NULL)
1798 * If we still don't know the request destination,
1799 * the request is invalid or the client uses
1800 * Privoxy without its knowledge.
1802 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1805 * Our attempts to get the request destination
1806 * elsewhere failed or Privoxy is configured
1807 * to only accept proxy requests.
1809 * An error response has already been send
1810 * and we're done here.
1812 return JB_ERR_PARSE;
1816 #ifdef FEATURE_CLIENT_TAGS
1817 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1818 set_client_address(csp, headers);
1819 get_tag_list_for_client(csp->client_tags, csp->client_address);
1823 * Determine the actions for this URL
1825 #ifdef FEATURE_TOGGLE
1826 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1828 /* Most compatible set of actions (i.e. none) */
1829 init_current_action(csp->action);
1832 #endif /* ndef FEATURE_TOGGLE */
1834 get_url_actions(csp, http);
1837 enlist(csp->headers, http->cmd);
1839 /* Append the previously read headers */
1840 err = list_append_list_unique(csp->headers, headers);
1841 destroy_list(headers);
1848 /*********************************************************************
1850 * Function : parse_client_request
1852 * Description : Parses the client's request and decides what to do
1855 * Note that since we're not using select() we could get
1856 * blocked here if a client connected, then didn't say
1860 * 1 : csp = Current client state (buffers, headers, etc...)
1862 * Returns : JB_ERR_OK or JB_ERR_PARSE
1864 *********************************************************************/
1865 static jb_err parse_client_request(struct client_state *csp)
1867 struct http_request *http = csp->http;
1870 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1871 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1872 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1873 && (csp->http->ssl == 0))
1875 /* Assume persistence until further notice */
1876 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1879 if (csp->http->ssl == 0)
1882 * This whole block belongs to chat() but currently
1883 * has to be executed before sed().
1885 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1887 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1889 return JB_ERR_PARSE;
1894 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1896 verify_request_length(csp);
1900 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1902 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1904 err = sed(csp, FILTER_CLIENT_HEADERS);
1905 if (JB_ERR_OK != err)
1907 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1909 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1910 csp->ip_addr_str, csp->http->cmd);
1911 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1912 return JB_ERR_PARSE;
1914 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1916 /* Check request line for rewrites. */
1917 if ((NULL == csp->headers->first->str)
1918 || (strcmp(http->cmd, csp->headers->first->str) &&
1919 (JB_ERR_OK != change_request_destination(csp))))
1922 * A header filter broke the request line - bail out.
1924 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1925 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1926 /* XXX: Use correct size */
1927 log_error(LOG_LEVEL_CLF,
1928 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1929 log_error(LOG_LEVEL_ERROR,
1930 "Invalid request line after applying header filters.");
1931 free_http_request(http);
1933 return JB_ERR_PARSE;
1936 if (client_has_unsupported_expectations(csp))
1938 return JB_ERR_PARSE;
1946 /*********************************************************************
1948 * Function : send_http_request
1950 * Description : Sends the HTTP headers from the client request
1951 * and all the body data that has already been received.
1954 * 1 : csp = Current client state (buffers, headers, etc...)
1956 * Returns : 0 on success, anything else is an error.
1958 *********************************************************************/
1959 static int send_http_request(struct client_state *csp)
1964 hdr = list_to_text(csp->headers);
1967 /* FIXME Should handle error properly */
1968 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1970 list_remove_all(csp->headers);
1973 * Write the client's (modified) header to the server
1974 * (along with anything else that may be in the buffer)
1976 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1981 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
1982 csp->http->hostport);
1984 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
1985 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
1988 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
1989 csp->http->hostport);
1992 return write_failure;
1997 /*********************************************************************
1999 * Function : handle_established_connection
2001 * Description : Shuffle data between client and server once the
2002 * connection has been established.
2005 * 1 : csp = Current client state (buffers, headers, etc...)
2007 * Returns : Nothing.
2009 *********************************************************************/
2010 static void handle_established_connection(struct client_state *csp)
2016 struct pollfd poll_fds[2];
2020 struct timeval timeout;
2023 int ms_iis5_hack = 0;
2024 unsigned long long byte_count = 0;
2025 struct http_request *http;
2026 long len = 0; /* for buffer sizes (and negative error codes) */
2027 int buffer_and_filter_content = 0;
2028 unsigned int write_delay;
2029 #ifdef FEATURE_HTTPS_FILTERING
2031 int use_ssl_tunnel = 0;
2032 csp->dont_verify_certificate = 0;
2035 * Preset flags informing if SSL connections with server or client
2036 * are opened or closed
2038 csp->ssl_with_server_is_opened = 0;
2039 csp->ssl_with_client_is_opened = 0;
2041 if (csp->http->ssl && !(csp->action->flags & ACTION_ENABLE_HTTPS_FILTER))
2043 /* Pass encrypted content without filtering. */
2048 /* Skeleton for HTTP response, if we should intercept the request */
2049 struct http_response *rsp;
2050 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2051 int watch_client_socket;
2054 csp->receive_buffer_size = csp->config->receive_buffer_size;
2055 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2056 if (csp->receive_buffer == NULL)
2058 log_error(LOG_LEVEL_ERROR,
2059 "Out of memory. Failed to allocate the receive buffer.");
2060 rsp = cgi_error_memory();
2061 send_crunch_response(csp, rsp);
2068 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2069 csp->cfd : csp->server_connection.sfd;
2072 /* pass data between the client and server
2073 * until one or the other shuts down the connection.
2078 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2079 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2081 write_delay = get_write_delay(csp);
2088 * FD_ZERO here seems to point to an errant macro which crashes.
2089 * So do this by hand for now...
2091 memset(&rfds,0x00,sizeof(fd_set));
2095 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2096 if (!watch_client_socket)
2098 maxfd = csp->server_connection.sfd;
2101 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2103 FD_SET(csp->cfd, &rfds);
2106 FD_SET(csp->server_connection.sfd, &rfds);
2107 #endif /* ndef HAVE_POLL */
2109 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2110 if ((csp->flags & CSP_FLAG_CHUNKED)
2111 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2112 && ((csp->iob->eod - csp->iob->cur) >= 5)
2113 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2116 * XXX: This check should be obsolete now,
2117 * but let's wait a while to be sure.
2119 log_error(LOG_LEVEL_CONNECT,
2120 "Looks like we got the last chunk together with "
2121 "the server headers but didn't detect it earlier. "
2122 "We better stop reading.");
2123 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2124 csp->expected_content_length = byte_count;
2125 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2127 if (server_body && server_response_is_complete(csp, byte_count))
2129 if (csp->expected_content_length == byte_count)
2131 log_error(LOG_LEVEL_CONNECT,
2132 "Done reading from server. Content length: %llu as expected. "
2133 "Bytes most recently read: %d.",
2138 log_error(LOG_LEVEL_CONNECT,
2139 "Done reading from server. Expected content length: %llu. "
2140 "Actual content length: %llu. Bytes most recently read: %d.",
2141 csp->expected_content_length, byte_count, len);
2145 * XXX: Should not jump around, handle_established_connection()
2146 * is complicated enough already.
2150 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2152 #ifdef FEATURE_HTTPS_FILTERING
2154 * Test if some data from client or destination server are pending
2155 * on TLS/SSL. We must work with them preferably. TLS/SSL data can
2156 * be pending because of maximal fragment size.
2158 int read_ssl_server = 0;
2159 int read_ssl_client = 0;
2161 if (client_use_ssl(csp))
2163 read_ssl_client = is_ssl_pending(&(csp->mbedtls_client_attr.ssl)) != 0;
2166 if (server_use_ssl(csp))
2168 read_ssl_server = is_ssl_pending(&(csp->mbedtls_server_attr.ssl)) != 0;
2171 if (!read_ssl_server && !read_ssl_client)
2175 poll_fds[0].fd = csp->cfd;
2176 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2177 if (!watch_client_socket)
2180 * Ignore incoming data, but still watch out
2181 * for disconnects etc. These flags are always
2182 * implied anyway but explicitly setting them
2185 poll_fds[0].events = POLLERR|POLLHUP;
2190 poll_fds[0].events = POLLIN;
2192 poll_fds[1].fd = csp->server_connection.sfd;
2193 poll_fds[1].events = POLLIN;
2194 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2196 timeout.tv_sec = csp->config->socket_timeout;
2197 timeout.tv_usec = 0;
2198 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
2199 #endif /* def HAVE_POLL */
2201 /*server or client not responding in timeout */
2204 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2205 csp->config->socket_timeout, http->url);
2206 if ((byte_count == 0) && (http->ssl == 0))
2208 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2210 mark_server_socket_tainted(csp);
2211 #ifdef FEATURE_HTTPS_FILTERING
2212 close_client_and_server_ssl_connections(csp);
2219 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2221 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2223 mark_server_socket_tainted(csp);
2224 #ifdef FEATURE_HTTPS_FILTERING
2225 close_client_and_server_ssl_connections(csp);
2230 #ifdef FEATURE_HTTPS_FILTERING
2233 /* set FD if some data are pending on TLS/SSL connections */
2237 if (read_ssl_client)
2240 poll_fds[0].fd = csp->cfd;
2241 poll_fds[0].events = POLLIN;
2243 FD_SET(csp->cfd, &rfds);
2248 if (read_ssl_server)
2251 poll_fds[1].fd = csp->server_connection.sfd;
2252 poll_fds[1].events = POLLIN;
2254 FD_SET(csp->server_connection.sfd, &rfds);
2261 * This is the body of the browser's request,
2262 * just read and write it.
2264 * Receives data from browser and sends it to server
2266 * XXX: Make sure the client doesn't use pipelining
2267 * behind Privoxy's back.
2270 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2272 log_error(LOG_LEVEL_CONNECT,
2273 "The client socket %d has become unusable while "
2274 "the server socket %d is still open.",
2275 csp->cfd, csp->server_connection.sfd);
2276 mark_server_socket_tainted(csp);
2280 if (poll_fds[0].revents != 0)
2282 if (FD_ISSET(csp->cfd, &rfds))
2283 #endif /* def HAVE_POLL*/
2285 int max_bytes_to_read = (int)csp->receive_buffer_size;
2287 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2288 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2290 if (data_is_available(csp->cfd, 0))
2293 * If the next request is already waiting, we have
2294 * to stop select()ing the client socket. Otherwise
2295 * we would always return right away and get nothing
2298 watch_client_socket = 0;
2299 log_error(LOG_LEVEL_CONNECT,
2300 "Stop watching client socket %d. "
2301 "There's already another request waiting.",
2306 * If the client socket is set, but there's no data
2307 * available on the socket, the client went fishing
2308 * and continuing talking to the server makes no sense.
2310 log_error(LOG_LEVEL_CONNECT,
2311 "The client closed socket %d while "
2312 "the server socket %d is still open.",
2313 csp->cfd, csp->server_connection.sfd);
2314 mark_server_socket_tainted(csp);
2317 if (csp->expected_client_content_length != 0)
2319 if (csp->expected_client_content_length < csp->receive_buffer_size)
2321 max_bytes_to_read = (int)csp->expected_client_content_length;
2323 log_error(LOG_LEVEL_CONNECT,
2324 "Waiting for up to %d bytes from the client.",
2327 assert(max_bytes_to_read <= csp->receive_buffer_size);
2328 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2330 #ifdef FEATURE_HTTPS_FILTERING
2332 * Reading data from standard or secured connection (HTTP/HTTPS)
2334 if (client_use_ssl(csp))
2337 * Receiving HTTP request from client over TLS/SSL and sending
2338 * it to server over TLS/SSL.
2340 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2341 (unsigned char *)csp->receive_buffer, (size_t)max_bytes_to_read);
2345 mark_server_socket_tainted(csp);
2349 ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2350 (const unsigned char *)csp->receive_buffer, (size_t)len);
2354 log_error(LOG_LEVEL_ERROR,
2355 "Send request over TLS/SSL to: %s failed", http->host);
2356 mark_server_socket_tainted(csp);
2357 close_client_and_server_ssl_connections(csp);
2362 #endif /* def FEATURE_HTTPS_FILTERING */
2364 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2368 /* XXX: not sure if this is necessary. */
2369 mark_server_socket_tainted(csp);
2370 break; /* "game over, man" */
2373 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2374 if (csp->expected_client_content_length != 0)
2376 assert(len <= max_bytes_to_read);
2377 csp->expected_client_content_length -= (unsigned)len;
2378 log_error(LOG_LEVEL_CONNECT,
2379 "Expected client content length set to %llu "
2380 "after reading %d bytes.",
2381 csp->expected_client_content_length, len);
2382 if (csp->expected_client_content_length == 0)
2384 log_error(LOG_LEVEL_CONNECT,
2385 "Done reading from the client.");
2386 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2389 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2391 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2393 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2394 mark_server_socket_tainted(csp);
2395 #ifdef FEATURE_HTTPS_FILTERING
2396 close_client_and_server_ssl_connections(csp);
2405 * The server wants to talk. It could be the header or the body.
2406 * If `hdr' is null, then it's the header otherwise it's the body.
2407 * FIXME: Does `hdr' really mean `host'? No.
2410 if (poll_fds[1].revents != 0)
2412 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2413 #endif /* HAVE_POLL */
2415 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2417 * If we are buffering content, we don't want to eat up to
2418 * buffer-limit bytes if the client no longer cares about them.
2419 * If we aren't buffering, however, a dead client socket will be
2420 * noticed pretty much right away anyway, so we can reduce the
2421 * overhead by skipping the check.
2423 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2426 log_error(LOG_LEVEL_CONNECT,
2427 "The server still wants to talk, but the client may already have hung up on us.");
2429 log_error(LOG_LEVEL_CONNECT,
2430 "The server still wants to talk, but the client hung up on us.");
2431 mark_server_socket_tainted(csp);
2432 #ifdef FEATURE_HTTPS_FILTERING
2433 close_client_and_server_ssl_connections(csp);
2436 #endif /* def _WIN32 */
2438 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2440 #ifdef FEATURE_HTTPS_FILTERING
2442 * Reading data from standard or secured connection (HTTP/HTTPS)
2444 if (server_use_ssl(csp))
2446 len = ssl_recv_data(&(csp->mbedtls_server_attr.ssl),
2447 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2452 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2453 (int)csp->receive_buffer_size);
2458 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2460 if ((http->ssl && (csp->fwd == NULL))
2461 #ifdef FEATURE_HTTPS_FILTERING
2467 * Just hang up. We already confirmed the client's CONNECT
2468 * request with status code 200 and unencrypted content is
2469 * no longer welcome.
2471 log_error(LOG_LEVEL_ERROR,
2472 "CONNECT already confirmed. Unable to tell the client about the problem.");
2475 else if (byte_count)
2478 * Just hang up. We already transmitted the original headers
2479 * and parts of the original content and therefore missed the
2480 * chance to send an error message (without risking data corruption).
2482 * XXX: we could retry with a fancy range request here.
2484 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2485 "Unable to tell the client about the problem.");
2486 mark_server_socket_tainted(csp);
2487 #ifdef FEATURE_HTTPS_FILTERING
2488 close_client_and_server_ssl_connections(csp);
2493 * XXX: Consider handling the cases above the same.
2495 mark_server_socket_tainted(csp);
2499 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2500 if (csp->flags & CSP_FLAG_CHUNKED)
2502 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2504 /* XXX: this is a temporary hack */
2505 log_error(LOG_LEVEL_CONNECT,
2506 "Looks like we reached the end of the last chunk. "
2507 "We better stop reading.");
2508 csp->expected_content_length = byte_count + (unsigned long long)len;
2509 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2513 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2516 * This is guaranteed by allocating with zalloc_or_die()
2517 * and never (intentionally) writing to the last byte.
2519 * csp->receive_buffer_size is the size of the part of the
2520 * buffer we intentionally write to, but we actually
2521 * allocated csp->receive_buffer_size+1 bytes so the assertion
2522 * stays within the allocated range.
2524 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2527 * Add a trailing zero to let be able to use string operations.
2528 * XXX: do we still need this with filter_popups gone?
2530 assert(len <= csp->receive_buffer_size);
2531 csp->receive_buffer[len] = '\0';
2534 * Normally, this would indicate that we've read
2535 * as much as the server has sent us and we can
2536 * close the client connection. However, Microsoft
2537 * in its wisdom has released IIS/5 with a bug that
2538 * prevents it from sending the trailing \r\n in
2539 * a 302 redirect header (and possibly other headers).
2540 * To work around this if we've haven't parsed
2541 * a full header we'll append a trailing \r\n
2542 * and see if this now generates a valid one.
2544 * This hack shouldn't have any impacts. If we've
2545 * already transmitted the header or if this is a
2546 * SSL connection, then we won't bother with this
2547 * hack. So we only work on partially received
2548 * headers. If we append a \r\n and this still
2549 * doesn't generate a valid header, then we won't
2550 * transmit anything to the client.
2555 if (server_body || (http->ssl
2556 #ifdef FEATURE_HTTPS_FILTERING
2562 * If we have been buffering up the document,
2563 * now is the time to apply content modification
2564 * and send the result to the client.
2566 if (buffer_and_filter_content)
2568 p = execute_content_filters(csp);
2570 * If content filtering fails, use the original
2571 * buffer and length.
2572 * (see p != NULL ? p : csp->iob->cur below)
2576 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2578 #ifdef FEATURE_COMPRESSION
2579 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2580 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2582 char *compressed_content = compress_buffer(p,
2583 (size_t *)&csp->content_length, csp->config->compression_level);
2584 if (compressed_content != NULL)
2587 p = compressed_content;
2588 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2593 if (JB_ERR_OK != update_server_headers(csp))
2595 log_error(LOG_LEVEL_FATAL,
2596 "Failed to update server headers. after filtering.");
2599 hdr = list_to_text(csp->headers);
2602 /* FIXME Should handle error properly */
2603 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2606 #ifdef FEATURE_HTTPS_FILTERING
2608 * Sending data with standard or secured connection (HTTP/HTTPS)
2610 if (client_use_ssl(csp))
2612 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2613 (const unsigned char *)hdr, strlen(hdr)) < 0)
2614 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2615 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
2616 csp->content_length) < 0))
2618 log_error(LOG_LEVEL_ERROR, "write modified content to "
2619 "client over TLS/SSL failed");
2622 mark_server_socket_tainted(csp);
2623 close_client_and_server_ssl_connections(csp);
2628 #endif /* def FEATURE_HTTPS_FILTERING */
2630 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2631 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
2632 (size_t)csp->content_length, write_delay))
2634 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2637 mark_server_socket_tainted(csp);
2638 #ifdef FEATURE_HTTPS_FILTERING
2639 close_client_and_server_ssl_connections(csp);
2649 break; /* "game over, man" */
2653 * This is NOT the body, so
2654 * Let's pretend the server just sent us a blank line.
2656 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
2657 len = (int)strlen(csp->receive_buffer);
2660 * Now, let the normal header parsing algorithm below do its
2661 * job. If it fails, we'll exit instead of continuing.
2668 * If we're in the body of the server document, just write it to
2669 * the client, unless we need to buffer the body for later
2670 * content-filtering.
2672 if (server_body || (http->ssl
2673 #ifdef FEATURE_HTTPS_FILTERING
2678 if (buffer_and_filter_content)
2681 * If there is no memory left for buffering the content, or the buffer limit
2682 * has been reached, switch to non-filtering mode, i.e. make & write the
2683 * header, flush the iob and buf, and get out of the way.
2685 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
2690 log_error(LOG_LEVEL_INFO,
2691 "Flushing header and buffers. Stepping back from filtering.");
2693 hdr = list_to_text(csp->headers);
2697 * Memory is too tight to even generate the header.
2698 * Send our static "Out-of-memory" page.
2700 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
2701 rsp = cgi_error_memory();
2702 send_crunch_response(csp, rsp);
2703 mark_server_socket_tainted(csp);
2704 #ifdef FEATURE_HTTPS_FILTERING
2705 close_client_and_server_ssl_connections(csp);
2709 hdrlen = strlen(hdr);
2711 #ifdef FEATURE_HTTPS_FILTERING
2713 * Sending data with standard or secured connection (HTTP/HTTPS)
2715 if (client_use_ssl(csp))
2717 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2718 (const unsigned char *)hdr, hdrlen) < 0)
2719 || ((flushed = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
2721 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2722 (const unsigned char *)csp->receive_buffer, (size_t)len) < 0))
2724 log_error(LOG_LEVEL_CONNECT,
2725 "Flush header and buffers to client failed");
2727 mark_server_socket_tainted(csp);
2728 close_client_and_server_ssl_connections(csp);
2733 #endif /* def FEATURE_HTTPS_FILTERING */
2735 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
2736 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
2737 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
2740 log_error(LOG_LEVEL_CONNECT,
2741 "Flush header and buffers to client failed: %E");
2743 mark_server_socket_tainted(csp);
2744 #ifdef FEATURE_HTTPS_FILTERING
2745 close_client_and_server_ssl_connections(csp);
2752 * Reset the byte_count to the amount of bytes
2753 * we just flushed. len will be added a few lines below,
2754 * hdrlen doesn't matter for LOG_LEVEL_CLF.
2756 byte_count = (unsigned long long)flushed;
2758 buffer_and_filter_content = 0;
2764 #ifdef FEATURE_HTTPS_FILTERING
2766 * Sending data with standard or secured connection (HTTP/HTTPS)
2768 if (client_use_ssl(csp))
2770 ret = ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2771 (const unsigned char *)csp->receive_buffer, (size_t)len);
2774 log_error(LOG_LEVEL_ERROR,
2775 "Sending data to client failed");
2776 mark_server_socket_tainted(csp);
2777 close_client_and_server_ssl_connections(csp);
2782 #endif /* def FEATURE_HTTPS_FILTERING */
2784 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
2785 (size_t)len, write_delay))
2787 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
2788 mark_server_socket_tainted(csp);
2789 #ifdef FEATURE_HTTPS_FILTERING
2790 close_client_and_server_ssl_connections(csp);
2796 byte_count += (unsigned long long)len;
2802 * We're still looking for the end of the server's header.
2803 * Buffer up the data we just read. If that fails, there's
2804 * little we can do but send our static out-of-memory page.
2806 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
2808 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
2809 rsp = cgi_error_memory();
2810 send_crunch_response(csp, rsp);
2811 mark_server_socket_tainted(csp);
2812 #ifdef FEATURE_HTTPS_FILTERING
2813 close_client_and_server_ssl_connections(csp);
2818 /* Convert iob into something sed() can digest */
2819 if (JB_ERR_PARSE == get_server_headers(csp))
2824 * Well, we tried our MS IIS/5 hack and it didn't work.
2825 * The header is incomplete and there isn't anything
2826 * we can do about it.
2828 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
2829 "Applying the MS IIS5 hack didn't help.");
2830 log_error(LOG_LEVEL_CLF,
2831 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2832 #ifdef FEATURE_HTTPS_FILTERING
2834 * Sending data with standard or secured connection (HTTP/HTTPS)
2836 if (client_use_ssl(csp))
2838 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2839 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
2840 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2843 #endif /* def FEATURE_HTTPS_FILTERING */
2845 write_socket_delayed(csp->cfd,
2846 INVALID_SERVER_HEADERS_RESPONSE,
2847 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2849 mark_server_socket_tainted(csp);
2850 #ifdef FEATURE_HTTPS_FILTERING
2851 close_client_and_server_ssl_connections(csp);
2858 * Since we have to wait for more from the server before
2859 * we can parse the headers we just continue here.
2861 log_error(LOG_LEVEL_CONNECT,
2862 "Continuing buffering server headers from socket %d. "
2863 "Bytes most recently read: %d.", csp->cfd, len);
2870 * Account for the content bytes we
2871 * might have gotten with the headers.
2873 assert(csp->iob->eod >= csp->iob->cur);
2874 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2877 /* Did we actually get anything? */
2878 if (NULL == csp->headers->first)
2880 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
2882 log_error(LOG_LEVEL_ERROR,
2883 "No server or forwarder response received on socket %d. "
2884 "Closing client socket %d without sending data.",
2885 csp->server_connection.sfd, csp->cfd);
2886 log_error(LOG_LEVEL_CLF,
2887 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2891 log_error(LOG_LEVEL_ERROR,
2892 "No server or forwarder response received on socket %d.",
2893 csp->server_connection.sfd);
2894 send_crunch_response(csp, error_response(csp, "no-server-data"));
2896 free_http_request(http);
2897 mark_server_socket_tainted(csp);
2898 #ifdef FEATURE_HTTPS_FILTERING
2899 close_client_and_server_ssl_connections(csp);
2904 if (!csp->headers->first->str)
2906 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
2908 assert(csp->headers->first->str);
2910 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
2911 strncmpic(csp->headers->first->str, "ICY", 3))
2914 * It doesn't look like a HTTP (or Shoutcast) response:
2915 * tell the client and log the problem.
2917 if (strlen(csp->headers->first->str) > 30)
2919 csp->headers->first->str[30] = '\0';
2921 log_error(LOG_LEVEL_ERROR,
2922 "Invalid server or forwarder response. Starts with: %s",
2923 csp->headers->first->str);
2924 log_error(LOG_LEVEL_CLF,
2925 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2926 #ifdef FEATURE_HTTPS_FILTERING
2928 * Sending data with standard or secured connection (HTTP/HTTPS)
2930 if (client_use_ssl(csp))
2932 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2933 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
2934 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2937 #endif /* def FEATURE_HTTPS_FILTERING */
2939 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2940 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2942 free_http_request(http);
2943 mark_server_socket_tainted(csp);
2944 #ifdef FEATURE_HTTPS_FILTERING
2945 close_client_and_server_ssl_connections(csp);
2951 * We have now received the entire server header,
2952 * filter it and send the result to the client
2954 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
2956 log_error(LOG_LEVEL_CLF,
2957 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
2958 #ifdef FEATURE_HTTPS_FILTERING
2960 * Sending data with standard or secured connection (HTTP/HTTPS)
2962 if (client_use_ssl(csp))
2964 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2965 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
2966 strlen(INVALID_SERVER_HEADERS_RESPONSE));
2971 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
2972 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
2974 free_http_request(http);
2975 mark_server_socket_tainted(csp);
2976 #ifdef FEATURE_HTTPS_FILTERING
2977 close_client_and_server_ssl_connections(csp);
2981 hdr = list_to_text(csp->headers);
2984 /* FIXME Should handle error properly */
2985 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2988 if ((csp->flags & CSP_FLAG_CHUNKED)
2989 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2990 && ((csp->iob->eod - csp->iob->cur) >= 5)
2991 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2993 log_error(LOG_LEVEL_CONNECT,
2994 "Looks like we got the last chunk together with "
2995 "the server headers. We better stop reading.");
2996 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2997 csp->expected_content_length = byte_count;
2998 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3001 csp->server_connection.response_received = time(NULL);
3003 if (crunch_response_triggered(csp, crunchers_light))
3006 * One of the tags created by a server-header
3007 * tagger triggered a crunch. We already
3008 * delivered the crunch response to the client
3009 * and are done here after cleaning up.
3012 mark_server_socket_tainted(csp);
3013 #ifdef FEATURE_HTTPS_FILTERING
3014 close_client_and_server_ssl_connections(csp);
3019 /* Buffer and pcrs filter this if appropriate. */
3020 buffer_and_filter_content = content_requires_filtering(csp);
3022 if (!buffer_and_filter_content)
3025 * Write the server's (modified) header to
3026 * the client (along with anything else that
3027 * may be in the buffer). Use standard or secured
3030 #ifdef FEATURE_HTTPS_FILTERING
3031 if (client_use_ssl(csp))
3033 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3034 (const unsigned char *)hdr, strlen(hdr)) < 0)
3035 || (len = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3038 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3041 * The write failed, so don't bother mentioning it
3042 * to the client... it probably can't hear us anyway.
3045 mark_server_socket_tainted(csp);
3046 #ifdef FEATURE_HTTPS_FILTERING
3047 close_client_and_server_ssl_connections(csp);
3053 #endif /* def FEATURE_HTTPS_FILTERING */
3055 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3056 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3058 log_error(LOG_LEVEL_ERROR,
3059 "write header to client failed");
3061 * The write failed, so don't bother mentioning it
3062 * to the client... it probably can't hear us anyway.
3065 mark_server_socket_tainted(csp);
3066 #ifdef FEATURE_HTTPS_FILTERING
3067 close_client_and_server_ssl_connections(csp);
3074 /* we're finished with the server's header */
3080 * If this was a MS IIS/5 hack then it means the server
3081 * has already closed the connection. Nothing more to read.
3086 log_error(LOG_LEVEL_ERROR,
3087 "Closed server connection detected. "
3088 "Applying the MS IIS5 hack didn't help.");
3089 log_error(LOG_LEVEL_CLF,
3090 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3091 #ifdef FEATURE_HTTPS_FILTERING
3093 * Sending data with standard or secured connection (HTTP/HTTPS)
3095 if (client_use_ssl(csp))
3097 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3098 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3099 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3102 #endif /* def FEATURE_HTTPS_FILTERING */
3104 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3105 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3107 mark_server_socket_tainted(csp);
3108 #ifdef FEATURE_HTTPS_FILTERING
3109 close_client_and_server_ssl_connections(csp);
3116 mark_server_socket_tainted(csp);
3117 #ifdef FEATURE_HTTPS_FILTERING
3118 close_client_and_server_ssl_connections(csp);
3120 return; /* huh? we should never get here */
3122 #ifdef FEATURE_HTTPS_FILTERING
3123 close_client_and_server_ssl_connections(csp);
3125 if (csp->content_length == 0)
3128 * If Privoxy didn't recalculate the Content-Length,
3129 * byte_count is still correct.
3131 csp->content_length = byte_count;
3134 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3135 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3136 && (csp->expected_content_length != byte_count))
3138 log_error(LOG_LEVEL_CONNECT,
3139 "Received %llu bytes while expecting %llu.",
3140 byte_count, csp->expected_content_length);
3141 mark_server_socket_tainted(csp);
3145 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3146 csp->ip_addr_str, http->ocmd, csp->content_length);
3148 csp->server_connection.timestamp = time(NULL);
3152 /*********************************************************************
3156 * Description : Once a connection from the client has been accepted,
3157 * this function is called (via serve()) to handle the
3158 * main business of the communication. This function
3159 * returns after dealing with a single request. It can
3160 * be called multiple times with the same client socket
3161 * if the client is keeping the connection alive.
3163 * The decision whether or not a client connection will
3164 * be kept alive is up to the caller which also must
3165 * close the client socket when done.
3167 * FIXME: chat is nearly thousand lines long.
3171 * 1 : csp = Current client state (buffers, headers, etc...)
3173 * Returns : Nothing.
3175 *********************************************************************/
3176 static void chat(struct client_state *csp)
3178 const struct forward_spec *fwd;
3179 struct http_request *http;
3180 /* Skeleton for HTTP response, if we should intercept the request */
3181 struct http_response *rsp;
3182 #ifdef FEATURE_HTTPS_FILTERING
3183 int use_ssl_tunnel = 0;
3188 if (receive_client_request(csp) != JB_ERR_OK)
3192 if (parse_client_request(csp) != JB_ERR_OK)
3197 /* decide how to route the HTTP request */
3198 fwd = forward_url(csp, http);
3201 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
3202 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3206 #ifdef FEATURE_HTTPS_FILTERING
3208 * Setting flags to use old solution with SSL tunnel and to disable
3209 * certificates verification.
3211 if (csp->http->ssl && !(csp->action->flags & ACTION_ENABLE_HTTPS_FILTER))
3216 if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3218 csp->dont_verify_certificate = 1;
3223 * build the http request to send to the server
3224 * we have to do one of the following:
3226 * create = use the original HTTP request to create a new
3227 * HTTP request that has either the path component
3228 * without the http://domainspec (w/path) or the
3229 * full orininal URL (w/url)
3230 * Note that the path and/or the HTTP version may
3231 * have been altered by now.
3233 * SSL proxy = Open a socket to the host:port of the server
3234 * and create TLS/SSL connection with server and
3235 * with client. Then behave like mediator between
3236 * client and server over TLS/SSL.
3238 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3239 * with request to a parent proxy. Note that we'll be sending
3240 * forwarding the CFAIL message ourselves if connecting to the parent
3241 * fails, but we won't send a CSUCCEED message if it works,
3242 * since that would result in a double message (ours and the
3243 * parent's). After sending the request to the parent, we
3244 * must parse answer and send it to client. If connection
3245 * with server is established, we do TLS/SSL proxy. Otherwise
3246 * we send parent response to client and close connections.
3248 * here's the matrix:
3251 * +--------+--------+
3253 * 0 | create | SSL |
3254 * | w/path | proxy |
3255 * Forwarding +--------+--------+
3257 * 1 | create | proxy |
3258 * | w/url |+forward|
3259 * +--------+--------+
3263 #ifdef FEATURE_HTTPS_FILTERING
3265 * Presetting SSL client and server flags
3267 if (http->ssl && !use_ssl_tunnel)
3269 http->client_ssl = 1;
3270 http->server_ssl = 1;
3274 http->client_ssl = 0;
3275 http->server_ssl = 0;
3279 if (http->ssl && connect_port_is_forbidden(csp))
3281 const char *acceptable_connect_ports =
3282 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3283 assert(NULL != acceptable_connect_ports);
3284 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3285 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3286 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3287 csp->action->flags |= ACTION_BLOCK;
3289 #ifdef FEATURE_HTTPS_FILTERING
3290 http->client_ssl = 0;
3291 http->server_ssl = 0;
3296 freez(csp->headers->first->str);
3297 build_request_line(csp, fwd, &csp->headers->first->str);
3300 * We have a request. Check if one of the crunchers wants it.
3302 if (crunch_response_triggered(csp, crunchers_all))
3305 * Yes. The client got the crunch response and we're done here.
3310 log_applied_actions(csp->action);
3311 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
3313 if (fwd->forward_host)
3315 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3316 fwd->forward_host, fwd->forward_port, http->hostport);
3320 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3323 /* here we connect to the server, gateway, or the forwarder */
3325 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3326 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3327 && socket_is_still_alive(csp->server_connection.sfd)
3328 && connection_destination_matches(&csp->server_connection, http, fwd))
3330 log_error(LOG_LEVEL_CONNECT,
3331 "Reusing server socket %d connected to %s. Total requests: %u.",
3332 csp->server_connection.sfd, csp->server_connection.host,
3333 csp->server_connection.requests_sent_total);
3337 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3339 #ifdef FEATURE_CONNECTION_SHARING
3340 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3342 remember_connection(&csp->server_connection);
3345 #endif /* def FEATURE_CONNECTION_SHARING */
3347 log_error(LOG_LEVEL_CONNECT,
3348 "Closing server socket %d connected to %s. Total requests: %u.",
3349 csp->server_connection.sfd, csp->server_connection.host,
3350 csp->server_connection.requests_sent_total);
3351 close_socket(csp->server_connection.sfd);
3353 mark_connection_closed(&csp->server_connection);
3355 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3358 * Connecting to destination server
3360 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
3362 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
3364 if (fwd->type != SOCKS_NONE)
3367 rsp = error_response(csp, "forwarding-failed");
3369 else if (errno == EINVAL)
3371 rsp = error_response(csp, "no-such-domain");
3375 rsp = error_response(csp, "connect-failed");
3378 /* Write the answer to the client */
3381 send_crunch_response(csp, rsp);
3385 * Temporary workaround to prevent already-read client
3386 * bodies from being parsed as new requests. For now we
3387 * err on the safe side and throw all the following
3388 * requests under the bus, even if no client body has been
3389 * buffered. A compliant client will repeat the dropped
3390 * requests on an untainted connection.
3392 * The proper fix is to discard the no longer needed
3393 * client body in the buffer (if there is one) and to
3394 * continue parsing the bytes that follow.
3396 drain_and_close_socket(csp->cfd);
3397 csp->cfd = JB_INVALID_SOCKET;
3402 #ifdef FEATURE_HTTPS_FILTERING
3404 * Creating TLS/SSL connections with destination server or parent
3405 * proxy. If forwarding is enabled, we must send client request to
3406 * parent proxy and receive, parse and resend parent proxy answer.
3408 if (http->ssl && !use_ssl_tunnel)
3410 if (fwd->forward_host != NULL)
3412 char server_response[BUFFER_SIZE];
3415 char *hdr = list_to_text(csp->headers);
3416 memset(server_response, 0, sizeof(server_response));
3420 log_error(LOG_LEVEL_FATAL,
3421 "Out of memory parsing client header");
3423 list_remove_all(csp->headers);
3426 * Sending client's CONNECT request to the parent proxy
3428 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
3434 log_error(LOG_LEVEL_CONNECT,
3435 "Sending request headers to: %s failed", http->hostport);
3436 mark_server_socket_tainted(csp);
3440 /* Waiting for parent proxy server response */
3441 len = read_socket(csp->server_connection.sfd, server_response,
3442 sizeof(server_response)-1);
3446 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
3447 "server on socket %d.", csp->server_connection.sfd);
3449 rsp = error_response(csp, "no-server-data");
3452 send_crunch_response(csp, rsp);
3454 mark_server_socket_tainted(csp);
3459 * Test if connection with destination server was established
3460 * successfully by parent proxy. Then we can send response to
3461 * the client and continue or stop.
3463 if (!tunnel_established_successfully(server_response, (unsigned int)len))
3465 log_error(LOG_LEVEL_ERROR, "Forwarder hasn't established "
3466 "connection with destination server.");
3468 write_socket(csp->cfd, server_response, (size_t)len);
3469 mark_server_socket_tainted(csp);
3474 * Parent proxy has established connection with destination server.
3475 * Now we must create TLS/SSL connection with parent proxy.
3477 ret = create_server_ssl_connection(csp);
3480 * If TLS/SSL connection wasn't created and invalid certificate
3481 * wasn't detected, we can interrupt this fuction. Otherwise, we
3482 * must inform the client about invalid server certificate.
3485 && (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3486 || csp->server_cert_verification_result == SSL_CERT_VALID))
3488 rsp = error_response(csp, "connect-failed");
3491 send_crunch_response(csp, rsp);
3497 * TLS/SSL connection with parent proxy is established, we can
3498 * inform client about success.
3500 ret = write_socket(csp->cfd, server_response, (size_t)len);
3503 log_error(LOG_LEVEL_ERROR,
3504 "Sending parent proxy response to client failed");
3505 mark_server_socket_tainted(csp);
3508 }/* -END- if (fwd->forward_host != NULL) */
3512 * Parent proxy is not used, we can just create TLS/SSL connection
3513 * with destination server
3515 int ret = create_server_ssl_connection(csp);
3517 * If TLS/SSL connection wasn't created and invalid certificate
3518 * wasn't detected, we can interrupt this function. Otherwise, we
3519 * must inform client about invalid server certificate.
3522 && (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
3523 || csp->server_cert_verification_result == SSL_CERT_VALID))
3525 rsp = error_response(csp, "connect-failed");
3528 send_crunch_response(csp, rsp);
3533 }/* -END- if (http->ssl) */
3534 #endif /* def FEATURE_HTTPS_FILTERING */
3536 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3537 save_connection_destination(csp->server_connection.sfd,
3538 http, fwd, &csp->server_connection);
3539 csp->server_connection.keep_alive_timeout =
3540 (unsigned)csp->config->keep_alive_timeout;
3542 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3544 csp->server_connection.requests_sent_total++;
3546 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
3548 /* Client headers have been sent optimistically */
3549 assert(csp->headers->last == NULL);
3551 else if (http->ssl == 0 || (fwd->forward_host
3552 #ifdef FEATURE_HTTPS_FILTERING
3557 if (send_http_request(csp))
3559 rsp = error_response(csp, "connect-failed");
3562 send_crunch_response(csp, rsp);
3570 * Using old solution with SSL tunnel or new solution with SSL proxy
3572 list_remove_all(csp->headers);
3573 #ifdef FEATURE_HTTPS_FILTERING
3578 * We're running an SSL tunnel and we're not forwarding,
3579 * so just ditch the client headers, send the "connect succeeded"
3580 * message to the client, flush the rest, and get out of the way.
3582 if (write_socket_delayed(csp->cfd, CSUCCEED,
3583 strlen(CSUCCEED), get_write_delay(csp)))
3588 #ifdef FEATURE_HTTPS_FILTERING
3593 * Creating an SSL proxy. If forwarding is disabled, we must send
3594 * CSUCCEED mesage to client. Then TLS/SSL connection with client
3598 if (fwd->forward_host == NULL)
3600 if (write_socket_delayed(csp->cfd, CSUCCEED,
3601 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3603 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3604 close_client_and_server_ssl_connections(csp);
3609 ret = create_client_ssl_connection(csp);
3612 log_error(LOG_LEVEL_ERROR,
3613 "Can't open secure connection with client");
3614 close_client_and_server_ssl_connections(csp);
3619 * If server certificate is invalid, we must inform client and then
3620 * close connection with client.
3622 if (csp->server_cert_verification_result != SSL_CERT_VALID)
3624 ssl_send_certificate_error(csp);
3625 close_client_and_server_ssl_connections(csp);
3629 #endif /* def FEATURE_HTTPS_FILTERING */
3630 clear_iob(csp->client_iob);
3631 }/* -END- else ... if (http->ssl == 1) */
3633 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
3635 /* XXX: should the time start earlier for optimistically sent data? */
3636 csp->server_connection.request_sent = time(NULL);
3638 handle_established_connection(csp);
3639 freez(csp->receive_buffer);
3644 /*********************************************************************
3646 * Function : fuzz_server_response
3648 * Description : Treat the input as a whole server response.
3651 * 1 : csp = Current client state (buffers, headers, etc...)
3652 * 2 : fuzz_input_file = File to read the input from.
3656 *********************************************************************/
3657 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
3659 static struct forward_spec fwd; /* Zero'd due to being static */
3662 if (strcmp(fuzz_input_file, "-") == 0)
3664 /* XXX: Doesn'T work yet. */
3665 csp->server_connection.sfd = 0;
3669 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
3670 if (csp->server_connection.sfd == -1)
3672 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
3677 csp->content_type |= CT_GIF;
3678 csp->action->flags |= ACTION_DEANIMATE;
3679 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
3681 csp->http->path = strdup_or_die("/");
3682 csp->http->host = strdup_or_die("fuzz.example.org");
3683 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
3684 /* Prevent client socket monitoring */
3685 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3686 csp->flags |= CSP_FLAG_CHUNKED;
3688 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
3689 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3691 csp->content_type |= CT_DECLARED|CT_GIF;
3693 csp->config->socket_timeout = 0;
3695 cgi_init_error_messages();
3697 handle_established_connection(csp);
3698 freez(csp->receive_buffer);
3705 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3706 /*********************************************************************
3708 * Function : prepare_csp_for_next_request
3710 * Description : Put the csp in a mostly vergin state.
3713 * 1 : csp = Current client state (buffers, headers, etc...)
3717 *********************************************************************/
3718 static void prepare_csp_for_next_request(struct client_state *csp)
3720 csp->content_type = 0;
3721 csp->content_length = 0;
3722 csp->expected_content_length = 0;
3723 csp->expected_client_content_length = 0;
3724 list_remove_all(csp->headers);
3725 clear_iob(csp->iob);
3726 freez(csp->error_message);
3727 free_http_request(csp->http);
3728 destroy_list(csp->headers);
3729 destroy_list(csp->tags);
3730 #ifdef FEATURE_CLIENT_TAGS
3731 destroy_list(csp->client_tags);
3732 freez(csp->client_address);
3734 free_current_action(csp->action);
3735 if (NULL != csp->fwd)
3737 unload_forward_spec(csp->fwd);
3740 /* XXX: Store per-connection flags someplace else. */
3741 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
3742 #ifdef FEATURE_TOGGLE
3743 if (global_toggle_state)
3744 #endif /* def FEATURE_TOGGLE */
3746 csp->flags |= CSP_FLAG_TOGGLED_ON;
3749 if (csp->client_iob->eod > csp->client_iob->cur)
3751 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
3752 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
3754 assert(bytes_to_shift > 0);
3755 assert(data_length > 0);
3757 log_error(LOG_LEVEL_CONNECT, "Shifting %d pipelined bytes by %d bytes",
3758 data_length, bytes_to_shift);
3759 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
3760 csp->client_iob->cur = csp->client_iob->buf;
3761 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
3762 csp->client_iob->eod = csp->client_iob->buf + data_length;
3763 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
3765 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
3770 * We mainly care about resetting client_iob->cur so we don't
3771 * waste buffer space at the beginning and don't mess up the
3772 * request restoration done by cgi_show_request().
3774 * Freeing the buffer itself isn't technically necessary,
3775 * but makes debugging more convenient.
3777 clear_iob(csp->client_iob);
3780 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3783 /*********************************************************************
3787 * Description : This is little more than chat. We only "serve" to
3788 * to close (or remember) any socket that chat may have
3792 * 1 : csp = Current client state (buffers, headers, etc...)
3796 *********************************************************************/
3797 static void serve(struct client_state *csp)
3799 int config_file_change_detected = 0; /* Only used for debugging */
3800 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3801 #ifdef FEATURE_CONNECTION_SHARING
3802 static int monitor_thread_running = 0;
3803 #endif /* def FEATURE_CONNECTION_SHARING */
3804 int continue_chatting = 0;
3806 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
3807 csp->ip_addr_str, csp->cfd);
3811 unsigned int latency;
3816 * If the request has been crunched,
3817 * the calculated latency is zero.
3819 latency = (unsigned)(csp->server_connection.response_received -
3820 csp->server_connection.request_sent) / 2;
3822 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3823 && (csp->flags & CSP_FLAG_CRUNCHED)
3824 && (csp->expected_client_content_length != 0))
3826 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
3827 log_error(LOG_LEVEL_CONNECT,
3828 "Tainting client socket %d due to unread data.", csp->cfd);
3831 continue_chatting = (csp->config->feature_flags
3832 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
3833 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3834 && (csp->cfd != JB_INVALID_SOCKET)
3835 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3836 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
3837 || (csp->flags & CSP_FLAG_CHUNKED));
3839 if (!(csp->flags & CSP_FLAG_CRUNCHED)
3840 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
3842 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
3844 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
3846 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
3847 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
3848 || !socket_is_still_alive(csp->server_connection.sfd)
3849 || !(latency < csp->server_connection.keep_alive_timeout))
3851 log_error(LOG_LEVEL_CONNECT,
3852 "Closing server socket %d connected to %s. "
3853 "Keep-alive %u. Tainted: %u. Socket alive %u. Timeout: %u.",
3854 csp->server_connection.sfd, csp->server_connection.host,
3855 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3856 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3857 socket_is_still_alive(csp->server_connection.sfd),
3858 csp->server_connection.keep_alive_timeout);
3859 #ifdef FEATURE_CONNECTION_SHARING
3860 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3862 forget_connection(csp->server_connection.sfd);
3864 #endif /* def FEATURE_CONNECTION_SHARING */
3865 close_socket(csp->server_connection.sfd);
3866 mark_connection_closed(&csp->server_connection);
3870 if (continue_chatting && any_loaded_file_changed(csp))
3872 continue_chatting = 0;
3873 config_file_change_detected = 1;
3876 if (continue_chatting)
3878 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
3879 && socket_is_still_alive(csp->cfd))
3881 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
3882 "pipelined on socket %d and the socket is still alive.",
3883 csp->requests_received_total+1, csp->cfd);
3884 prepare_csp_for_next_request(csp);
3888 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
3890 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3892 log_error(LOG_LEVEL_CONNECT,
3893 "Waiting for the next client request on socket %d. "
3894 "Keeping the server socket %d to %s open.",
3895 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3899 log_error(LOG_LEVEL_CONNECT,
3900 "Waiting for the next client request on socket %d. "
3901 "No server socket to keep open.", csp->cfd);
3905 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
3906 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
3907 && socket_is_still_alive(csp->cfd))
3909 log_error(LOG_LEVEL_CONNECT,
3910 "Client request %u arrived in time on socket %d.",
3911 csp->requests_received_total+1, csp->cfd);
3912 prepare_csp_for_next_request(csp);
3916 #ifdef FEATURE_CONNECTION_SHARING
3917 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3918 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
3919 && (socket_is_still_alive(csp->server_connection.sfd)))
3921 time_t time_open = time(NULL) - csp->server_connection.timestamp;
3923 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
3928 remember_connection(&csp->server_connection);
3929 csp->server_connection.sfd = JB_INVALID_SOCKET;
3930 drain_and_close_socket(csp->cfd);
3931 csp->cfd = JB_INVALID_SOCKET;
3932 privoxy_mutex_lock(&connection_reuse_mutex);
3933 if (!monitor_thread_running)
3935 monitor_thread_running = 1;
3936 privoxy_mutex_unlock(&connection_reuse_mutex);
3937 wait_for_alive_connections();
3938 privoxy_mutex_lock(&connection_reuse_mutex);
3939 monitor_thread_running = 0;
3941 privoxy_mutex_unlock(&connection_reuse_mutex);
3943 #endif /* def FEATURE_CONNECTION_SHARING */
3947 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3949 log_error(LOG_LEVEL_CONNECT,
3950 "Closing server socket %d connected to %s. Keep-alive: %u. "
3951 "Tainted: %u. Socket alive: %u. Timeout: %u. "
3952 "Configuration file change detected: %u",
3953 csp->server_connection.sfd, csp->server_connection.host,
3954 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
3955 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
3956 socket_is_still_alive(csp->server_connection.sfd),
3957 csp->server_connection.keep_alive_timeout,
3958 config_file_change_detected);
3960 } while (continue_chatting);
3964 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3966 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3968 #ifdef FEATURE_CONNECTION_SHARING
3969 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3971 forget_connection(csp->server_connection.sfd);
3973 #endif /* def FEATURE_CONNECTION_SHARING */
3974 close_socket(csp->server_connection.sfd);
3977 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3978 mark_connection_closed(&csp->server_connection);
3981 if (csp->cfd != JB_INVALID_SOCKET)
3983 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
3984 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
3985 "Configuration file change detected: %u. Requests received: %u.",
3986 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
3987 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
3988 config_file_change_detected, csp->requests_received_total);
3989 drain_and_close_socket(csp->cfd);
3992 free_csp_resources(csp);
3994 csp->flags &= ~CSP_FLAG_ACTIVE;
4000 /*********************************************************************
4002 * Function : server_thread
4004 * Description : We only exist to call `serve' in a threaded environment.
4007 * 1 : data = Current client state (buffers, headers, etc...)
4009 * Returns : Always 0.
4011 *********************************************************************/
4012 static int32 server_thread(void *data)
4014 serve((struct client_state *) data);
4021 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4022 /*********************************************************************
4026 * Description : Print usage info & exit.
4028 * Parameters : Pointer to argv[0] for identifying ourselves
4032 *********************************************************************/
4033 static void usage(const char *name)
4035 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
4036 "Usage: %s [--config-test] "
4039 #endif /* defined(unix) */
4042 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
4043 #endif /* defined(unix) */
4044 "[--version] [configfile]\n",
4048 show_fuzz_usage(name);
4051 printf("Aborting\n");
4056 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
4059 #ifdef MUTEX_LOCKS_AVAILABLE
4060 /*********************************************************************
4062 * Function : privoxy_mutex_lock
4064 * Description : Locks a mutex.
4067 * 1 : mutex = The mutex to lock.
4069 * Returns : Void. May exit in case of errors.
4071 *********************************************************************/
4072 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
4074 #ifdef FEATURE_PTHREAD
4075 int err = pthread_mutex_lock(mutex);
4078 if (mutex != &log_mutex)
4080 log_error(LOG_LEVEL_FATAL,
4081 "Mutex locking failed: %s.\n", strerror(err));
4086 EnterCriticalSection(mutex);
4087 #endif /* def FEATURE_PTHREAD */
4091 /*********************************************************************
4093 * Function : privoxy_mutex_unlock
4095 * Description : Unlocks a mutex.
4098 * 1 : mutex = The mutex to unlock.
4100 * Returns : Void. May exit in case of errors.
4102 *********************************************************************/
4103 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
4105 #ifdef FEATURE_PTHREAD
4106 int err = pthread_mutex_unlock(mutex);
4109 if (mutex != &log_mutex)
4111 log_error(LOG_LEVEL_FATAL,
4112 "Mutex unlocking failed: %s.\n", strerror(err));
4117 LeaveCriticalSection(mutex);
4118 #endif /* def FEATURE_PTHREAD */
4122 /*********************************************************************
4124 * Function : privoxy_mutex_init
4126 * Description : Prepares a mutex.
4129 * 1 : mutex = The mutex to initialize.
4131 * Returns : Void. May exit in case of errors.
4133 *********************************************************************/
4134 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
4136 #ifdef FEATURE_PTHREAD
4137 int err = pthread_mutex_init(mutex, 0);
4140 printf("Fatal error. Mutex initialization failed: %s.\n",
4145 InitializeCriticalSection(mutex);
4146 #endif /* def FEATURE_PTHREAD */
4148 #endif /* def MUTEX_LOCKS_AVAILABLE */
4150 /*********************************************************************
4152 * Function : initialize_mutexes
4154 * Description : Prepares mutexes if mutex support is available.
4158 * Returns : Void, exits in case of errors.
4160 *********************************************************************/
4161 static void initialize_mutexes(void)
4163 #ifdef MUTEX_LOCKS_AVAILABLE
4165 * Prepare global mutex semaphores
4168 #ifdef LIMIT_MUTEX_NUMBER
4170 for (i = 0; i < 32; i++)
4173 for (i = 0; i < 65536; i++)
4174 #endif /* LIMIT_MUTEX_NUMBER */
4176 privoxy_mutex_init(&(certificates_mutexes[i]));
4178 privoxy_mutex_init(&rng_mutex);
4180 privoxy_mutex_init(&log_mutex);
4181 privoxy_mutex_init(&log_init_mutex);
4182 privoxy_mutex_init(&connection_reuse_mutex);
4183 #ifdef FEATURE_EXTERNAL_FILTERS
4184 privoxy_mutex_init(&external_filter_mutex);
4186 #ifdef FEATURE_CLIENT_TAGS
4187 privoxy_mutex_init(&client_tags_mutex);
4191 * XXX: The assumptions below are a bit naive
4192 * and can cause locks that aren't necessary.
4194 * For example older FreeBSD versions (< 6.x?)
4195 * have no gethostbyname_r, but gethostbyname is
4198 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
4199 privoxy_mutex_init(&resolver_mutex);
4200 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
4202 * XXX: should we use a single mutex for
4203 * localtime() and gmtime() as well?
4205 #ifndef HAVE_GMTIME_R
4206 privoxy_mutex_init(&gmtime_mutex);
4207 #endif /* ndef HAVE_GMTIME_R */
4209 #ifndef HAVE_LOCALTIME_R
4210 privoxy_mutex_init(&localtime_mutex);
4211 #endif /* ndef HAVE_GMTIME_R */
4213 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
4214 privoxy_mutex_init(&rand_mutex);
4215 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
4217 #endif /* def MUTEX_LOCKS_AVAILABLE */
4220 /*********************************************************************
4224 * Description : Load the config file and start the listen loop.
4225 * This function is a lot more *sane* with the `load_config'
4226 * and `listen_loop' functions; although it stills does
4227 * a *little* too much for my taste.
4230 * 1 : argc = Number of parameters (including $0).
4231 * 2 : argv = Array of (char *)'s to the parameters.
4233 * Returns : 1 if : can't open config file, unrecognized directive,
4234 * stats requested in multi-thread mode, can't open the
4235 * log file, can't open the jar file, listen port is invalid,
4236 * any load fails, and can't bind port.
4238 * Else main never returns, the process must be signaled
4239 * to terminate execution. Or, on Windows, use the
4240 * "File", "Exit" menu option.
4242 *********************************************************************/
4244 int real_main(int argc, char **argv)
4246 int main(int argc, char **argv)
4250 int do_config_test = 0;
4251 #ifndef HAVE_ARC4RANDOM
4252 unsigned int random_seed;
4255 struct passwd *pw = NULL;
4256 struct group *grp = NULL;
4258 char *pre_chroot_nslookup_to_load_resolver = NULL;
4261 char *fuzz_input_type = NULL;
4262 char *fuzz_input_file = NULL;
4269 #if !defined(_WIN32)
4276 /* Prepare mutexes if supported and necessary. */
4277 initialize_mutexes();
4279 /* Enable logging until further notice. */
4283 * Parse the command line arguments
4285 * XXX: simply printing usage information in case of
4286 * invalid arguments isn't particularly user friendly.
4288 while (++argc_pos < argc)
4291 /* Check to see if the service must be installed or uninstalled */
4292 if (strncmp(argv[argc_pos], "--install", 9) == 0)
4294 const char *pName = argv[argc_pos] + 9;
4297 exit((install_service(pName)) ? 0 : 1);
4299 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
4301 const char *pName = argv[argc_pos] + 11;
4304 exit((uninstall_service(pName)) ? 0 : 1);
4306 else if (strcmp(argv[argc_pos], "--service") == 0)
4308 bRunAsService = TRUE;
4309 w32_set_service_cwd();
4310 atexit(w32_service_exit_notify);
4313 #endif /* defined(_WIN32) */
4316 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
4318 if (strcmp(argv[argc_pos], "--help") == 0)
4323 else if (strcmp(argv[argc_pos], "--version") == 0)
4325 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
4331 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
4333 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
4337 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
4339 if (++argc_pos == argc) usage(argv[0]);
4340 pidfile = strdup_or_die(argv[argc_pos]);
4343 else if (strcmp(argv[argc_pos], "--user") == 0)
4348 if (++argc_pos == argc) usage(argv[argc_pos]);
4350 user_arg = strdup_or_die(argv[argc_pos]);
4351 group_name = strchr(user_arg, '.');
4352 if (NULL != group_name)
4354 /* Nul-terminate the user name */
4357 /* Skip the former delimiter to actually reach the group name */
4360 grp = getgrnam(group_name);
4363 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
4366 pw = getpwnam(user_arg);
4369 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
4375 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
4377 if (++argc_pos == argc) usage(argv[0]);
4378 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
4381 else if (strcmp(argv[argc_pos], "--chroot") == 0)
4385 #endif /* defined(unix) */
4387 else if (strcmp(argv[argc_pos], "--config-test") == 0)
4392 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
4395 if (argc < argc_pos + 2) usage(argv[0]);
4396 fuzz_input_type = argv[argc_pos];
4398 fuzz_input_file = argv[argc_pos];
4400 else if (strcmp(argv[argc_pos], "--stfu") == 0)
4402 set_debug_level(LOG_LEVEL_STFU);
4405 else if (argc_pos + 1 != argc)
4408 * This is neither the last command line
4409 * option, nor was it recognized before,
4410 * therefore it must be invalid.
4416 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
4418 configfile = argv[argc_pos];
4421 } /* -END- while (more arguments) */
4423 show_version(Argv[0]);
4426 if (*configfile != '/')
4428 char cwd[BUFFER_SIZE];
4430 size_t abs_file_size;
4432 /* make config-filename absolute here */
4433 if (NULL == getcwd(cwd, sizeof(cwd)))
4435 perror("failed to get current working directory");
4439 basedir = strdup_or_die(cwd);
4441 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
4442 abs_file = malloc_or_die(abs_file_size);
4443 strlcpy(abs_file, basedir, abs_file_size);
4444 strlcat(abs_file, "/", abs_file_size);
4445 strlcat(abs_file, configfile, abs_file_size);
4446 configfile = abs_file;
4448 #endif /* defined unix */
4452 clients->next = NULL;
4454 /* XXX: factor out initialising after the next stable release. */
4459 #ifndef HAVE_ARC4RANDOM
4460 random_seed = (unsigned int)time(NULL);
4462 srandom(random_seed);
4465 #endif /* ifdef HAVE_RANDOM */
4466 #endif /* ifndef HAVE_ARC4RANDOM */
4469 * Unix signal handling
4471 * Catch the abort, interrupt and terminate signals for a graceful exit
4472 * Catch the hangup signal so the errlog can be reopened.
4474 * Ignore the broken pipe signal as connection failures
4475 * are handled when and where they occur without relying
4478 #if !defined(_WIN32) && !defined(__OS2__)
4481 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
4483 for (idx = 0; idx < SZ(catched_signals); idx++)
4485 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
4486 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
4488 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
4489 #endif /* ifdef sun */
4491 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
4495 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
4497 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
4501 #else /* ifdef _WIN32 */
4502 # ifdef _WIN_CONSOLE
4504 * We *are* in a windows console app.
4505 * Print a verbose messages about FAQ's and such
4507 printf("%s", win32_blurb);
4508 # endif /* def _WIN_CONSOLE */
4509 #endif /* def _WIN32 */
4512 if (fuzz_input_type != NULL)
4514 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
4516 log_error(LOG_LEVEL_FATAL,
4517 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
4518 "Various data structures are static which is unsafe when using threads.");
4523 exit(NULL == load_config());
4526 /* Initialize the CGI subsystem */
4527 cgi_init_error_messages();
4530 * If running on unix and without the --no-daemon
4531 * option, become a daemon. I.e. fork, detach
4532 * from tty and get process group leadership
4541 if (pid < 0) /* error */
4546 else if (pid != 0) /* parent */
4551 * must check for errors
4552 * child died due to missing files aso
4555 wpid = waitpid(pid, &status, WNOHANG);
4567 * stderr (fd 2) will be closed later on,
4568 * when the config file has been parsed.
4574 * Reserve fd 0 and 1 to prevent abort() and friends
4575 * from sending stuff to the clients or servers.
4577 fd = open("/dev/null", O_RDONLY);
4580 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4584 if (dup2(fd, 0) == -1)
4586 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
4590 fd = open("/dev/null", O_WRONLY);
4593 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
4597 if (dup2(fd, 1) == -1)
4599 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
4604 #ifdef FEATURE_EXTERNAL_FILTERS
4605 for (fd = 0; fd < 3; fd++)
4607 mark_socket_for_close_on_execute(fd);
4613 } /* -END- if (daemon_mode) */
4616 * As soon as we have written the PID file, we can switch
4617 * to the user and group ID indicated by the --user option
4619 if (pidfile != NULL)
4621 write_pid_file(pidfile);
4625 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
4627 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
4631 if (setgroups(1, &grp->gr_gid))
4633 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
4636 else if (initgroups(pw->pw_name, pw->pw_gid))
4638 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
4644 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
4646 /* Read the time zone file from /etc before doing chroot. */
4648 if (NULL != pre_chroot_nslookup_to_load_resolver
4649 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
4651 /* Initialize resolver library. */
4652 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
4654 if (chroot(pw->pw_dir) < 0)
4656 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
4660 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
4663 if (setuid(pw->pw_uid))
4665 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
4669 char putenv_dummy[64];
4671 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
4672 if (putenv(putenv_dummy) != 0)
4674 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
4677 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
4678 if (putenv(putenv_dummy) != 0)
4680 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
4686 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
4689 #endif /* defined unix */
4692 /* This will be FALSE unless the command line specified --service
4696 /* Yup, so now we must attempt to establish a connection
4697 * with the service dispatcher. This will only work if this
4698 * process was launched by the service control manager to
4699 * actually run as a service. If this isn't the case, i've
4700 * known it take around 30 seconds or so for the call to return.
4703 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
4704 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
4706 /* Service has run, and at this point is now being stopped, so just return */
4711 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
4713 /* An error occurred. Usually it's because --service was wrongly specified
4714 * and we were unable to connect to the Service Control Dispatcher because
4715 * it wasn't expecting us and is therefore not listening.
4717 * For now, just continue below to call the listen_loop function.
4720 #endif /* def _WIN32 */
4730 /*********************************************************************
4732 * Function : bind_port_helper
4734 * Description : Bind the listen port. Handles logging, and aborts
4738 * 1 : haddr = Host address to bind to. Use NULL to bind to
4740 * 2 : hport = Specifies port to bind to.
4741 * 3 : backlog = Listen backlog.
4743 * Returns : Port that was opened.
4745 *********************************************************************/
4746 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
4751 result = bind_port(haddr, hport, backlog, &bfd);
4755 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
4759 log_error(LOG_LEVEL_FATAL,
4760 "can't bind to %s:%d: There may be another Privoxy "
4761 "or some other proxy running on port %d",
4762 bind_address, hport, hport);
4765 log_error(LOG_LEVEL_FATAL,
4766 "can't bind to %s:%d: The hostname is not resolvable",
4767 bind_address, hport);
4770 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
4771 bind_address, hport);
4774 /* shouldn't get here */
4775 return JB_INVALID_SOCKET;
4780 if (bfd >= FD_SETSIZE)
4782 log_error(LOG_LEVEL_FATAL,
4783 "Bind socket number too high to use select(): %d >= %d",
4791 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
4796 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
4804 /*********************************************************************
4806 * Function : bind_ports_helper
4808 * Description : Bind the listen ports. Handles logging, and aborts
4812 * 1 : config = Privoxy configuration. Specifies ports
4814 * 2 : sockets = Preallocated array of opened sockets
4815 * corresponding to specification in config.
4816 * All non-opened sockets will be set to
4817 * JB_INVALID_SOCKET.
4819 * Returns : Nothing. Inspect sockets argument.
4821 *********************************************************************/
4822 static void bind_ports_helper(struct configuration_spec * config,
4823 jb_socket sockets[])
4827 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4829 if (config->hport[i])
4831 sockets[i] = bind_port_helper(config->haddr[i],
4832 config->hport[i], config->listen_backlog);
4833 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
4834 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
4836 struct accept_filter_arg af_options;
4837 bzero(&af_options, sizeof(af_options));
4838 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
4839 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
4840 sizeof(af_options)))
4842 log_error(LOG_LEVEL_ERROR,
4843 "Enabling accept filter for socket %d failed: %E", sockets[i]);
4850 sockets[i] = JB_INVALID_SOCKET;
4853 config->need_bind = 0;
4857 /*********************************************************************
4859 * Function : close_ports_helper
4861 * Description : Close listenings ports.
4864 * 1 : sockets = Array of opened and non-opened sockets to
4865 * close. All sockets will be set to
4866 * JB_INVALID_SOCKET.
4868 * Returns : Nothing.
4870 *********************************************************************/
4871 static void close_ports_helper(jb_socket sockets[])
4875 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
4877 if (JB_INVALID_SOCKET != sockets[i])
4879 close_socket(sockets[i]);
4881 sockets[i] = JB_INVALID_SOCKET;
4887 /* Without this simple workaround we get this compiler warning from _beginthread
4888 * warning C4028: formal parameter 1 different from declaration
4890 void w32_service_listen_loop(void *p)
4894 #endif /* def _WIN32 */
4897 /*********************************************************************
4899 * Function : listen_loop
4901 * Description : bind the listen port and enter a "FOREVER" listening loop.
4907 *********************************************************************/
4908 static void listen_loop(void)
4910 struct client_states *csp_list = NULL;
4911 struct client_state *csp = NULL;
4912 jb_socket bfds[MAX_LISTENING_SOCKETS];
4913 struct configuration_spec *config;
4914 unsigned int active_threads = 0;
4915 #if defined(FEATURE_PTHREAD)
4916 pthread_attr_t attrs;
4918 pthread_attr_init(&attrs);
4919 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
4922 config = load_config();
4924 #ifdef FEATURE_CONNECTION_SHARING
4926 * XXX: Should be relocated once it no
4927 * longer needs to emit log messages.
4929 initialize_reusable_connections();
4930 #endif /* def FEATURE_CONNECTION_SHARING */
4932 bind_ports_helper(config, bfds);
4934 #ifdef FEATURE_GRACEFUL_TERMINATION
4935 while (!g_terminate)
4940 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) && !defined(__OS2__)
4941 while (waitpid(-1, NULL, WNOHANG) > 0)
4943 /* zombie children */
4945 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
4948 * Free data that was used by died threads
4950 active_threads = sweep();
4954 * Re-open the errlog after HUP signal
4956 if (received_hup_signal)
4958 if (NULL != config->logfile)
4960 init_error_log(Argv[0], config->logfile);
4962 received_hup_signal = 0;
4966 csp_list = zalloc_or_die(sizeof(*csp_list));
4967 csp = &csp_list->csp;
4969 log_error(LOG_LEVEL_CONNECT,
4970 "Waiting for the next client connection. Currently active threads: %d",
4974 * This config may be outdated, but for accept_connection()
4975 * it's fresh enough.
4977 csp->config = config;
4979 if (!accept_connection(csp, bfds))
4981 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
4986 csp->flags |= CSP_FLAG_ACTIVE;
4987 csp->server_connection.sfd = JB_INVALID_SOCKET;
4989 csp->config = config = load_config();
4991 if (config->need_bind)
4994 * Since we were listening to the "old port", we will not see
4995 * a "listen" param change until the next request. So, at
4996 * least 1 more request must be made for us to find the new
4997 * setting. I am simply closing the old socket and binding the
5000 * Which-ever is correct, we will serve 1 more page via the
5001 * old settings. This should probably be a "show-status"
5002 * request. This should not be a so common of an operation
5003 * that this will hurt people's feelings.
5006 close_ports_helper(bfds);
5008 bind_ports_helper(config, bfds);
5011 #ifdef FEATURE_TOGGLE
5012 if (global_toggle_state)
5013 #endif /* def FEATURE_TOGGLE */
5015 csp->flags |= CSP_FLAG_TOGGLED_ON;
5018 if (run_loader(csp))
5020 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
5021 /* Never get here - LOG_LEVEL_FATAL causes program exit */
5025 if (block_acl(NULL,csp))
5027 log_error(LOG_LEVEL_CONNECT,
5028 "Connection from %s on %s (socket %d) dropped due to ACL",
5029 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
5030 close_socket(csp->cfd);
5031 freez(csp->ip_addr_str);
5032 freez(csp->listen_addr_str);
5036 #endif /* def FEATURE_ACL */
5038 if ((0 != config->max_client_connections)
5039 && (active_threads >= config->max_client_connections))
5041 log_error(LOG_LEVEL_CONNECT,
5042 "Rejecting connection from %s. Maximum number of connections reached.",
5044 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5045 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5046 close_socket(csp->cfd);
5047 freez(csp->ip_addr_str);
5048 freez(csp->listen_addr_str);
5053 /* add it to the list of clients */
5054 csp_list->next = clients->next;
5055 clients->next = csp_list;
5057 if (config->multi_threaded)
5061 /* this is a switch () statement in the C preprocessor - ugh */
5062 #undef SELECTED_ONE_OPTION
5064 /* Use Pthreads in preference to native code */
5065 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
5066 #define SELECTED_ONE_OPTION
5068 pthread_t the_thread;
5070 errno = pthread_create(&the_thread, &attrs,
5071 (void * (*)(void *))serve, csp);
5072 child_id = errno ? -1 : 0;
5076 #if defined(_WIN32) && !defined(_CYGWIN) && !defined(SELECTED_ONE_OPTION)
5077 #define SELECTED_ONE_OPTION
5078 child_id = _beginthread(
5079 (void (*)(void *))serve,
5084 #if defined(__OS2__) && !defined(SELECTED_ONE_OPTION)
5085 #define SELECTED_ONE_OPTION
5086 child_id = _beginthread(
5087 (void(* _Optlink)(void*))serve,
5093 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
5094 #define SELECTED_ONE_OPTION
5096 thread_id tid = spawn_thread
5097 (server_thread, "server", B_NORMAL_PRIORITY, csp);
5099 if ((tid >= 0) && (resume_thread(tid) == B_OK))
5101 child_id = (int) tid;
5110 #if !defined(SELECTED_ONE_OPTION)
5113 /* This block is only needed when using fork().
5114 * When using threads, the server thread was
5115 * created and run by the call to _beginthread().
5117 if (child_id == 0) /* child */
5120 #ifdef FEATURE_TOGGLE
5121 int inherited_toggle_state = global_toggle_state;
5122 #endif /* def FEATURE_TOGGLE */
5127 * If we've been toggled or we've blocked the request, tell Mom
5130 #ifdef FEATURE_TOGGLE
5131 if (inherited_toggle_state != global_toggle_state)
5133 rc |= RC_FLAG_TOGGLED;
5135 #endif /* def FEATURE_TOGGLE */
5137 #ifdef FEATURE_STATISTICS
5138 if (csp->flags & CSP_FLAG_REJECTED)
5140 rc |= RC_FLAG_BLOCKED;
5142 #endif /* ndef FEATURE_STATISTICS */
5146 else if (child_id > 0) /* parent */
5148 /* in a fork()'d environment, the parent's
5149 * copy of the client socket and the CSP
5153 #if !defined(_WIN32) && !defined(__CYGWIN__)
5155 wait(&child_status);
5158 * Evaluate child's return code: If the child has
5159 * - been toggled, toggle ourselves
5160 * - blocked its request, bump up the stats counter
5163 #ifdef FEATURE_TOGGLE
5164 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
5166 global_toggle_state = !global_toggle_state;
5168 #endif /* def FEATURE_TOGGLE */
5170 #ifdef FEATURE_STATISTICS
5172 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
5176 #endif /* def FEATURE_STATISTICS */
5178 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
5179 close_socket(csp->cfd);
5180 csp->flags &= ~CSP_FLAG_ACTIVE;
5184 #undef SELECTED_ONE_OPTION
5185 /* end of cpp switch () */
5190 * Spawning the child failed, assume it's because
5191 * there are too many children running already.
5192 * XXX: If you assume ...
5194 log_error(LOG_LEVEL_ERROR,
5195 "Unable to take any additional connections: %E. Active threads: %d",
5197 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
5198 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
5199 close_socket(csp->cfd);
5200 csp->flags &= ~CSP_FLAG_ACTIVE;
5209 #if defined(FEATURE_PTHREAD)
5210 pthread_attr_destroy(&attrs);
5213 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
5215 #ifdef FEATURE_HTTPS_FILTERING
5216 /* Clean up. Aim: free all memory (no leaks) */
5217 if (rng_seeded == 1)
5219 mbedtls_ctr_drbg_free(&ctr_drbg);
5220 mbedtls_entropy_free(&entropy);
5224 #ifdef FEATURE_GRACEFUL_TERMINATION
5226 log_error(LOG_LEVEL_ERROR, "Graceful termination requested");
5228 unload_current_config_file();
5229 unload_current_actions_file();
5230 unload_current_re_filterfile();
5231 #ifdef FEATURE_TRUST
5232 unload_current_trust_file();
5235 if (config->multi_threaded)
5242 } while ((clients->next != NULL) && (--i > 0));
5246 log_error(LOG_LEVEL_ERROR, "Graceful termination failed - still some live clients after 1 minute wait.");
5256 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
5257 /* Cleanup - remove taskbar icon etc. */
5262 #endif /* FEATURE_GRACEFUL_TERMINATION */