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-2022 the
9 * Privoxy team. https://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
66 # include <sys/wait.h>
67 # include <sys/time.h>
68 # include <sys/stat.h>
69 # include <sys/ioctl.h>
72 #include <sys/termios.h>
83 # include <socket.h> /* BeOS has select() for sockets only. */
84 # include <OS.h> /* declarations for threads and stuff. */
92 #endif /* def __GLIBC__ */
97 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
98 #endif /* HAVE_POLL */
105 #ifdef FEATURE_HTTPS_INSPECTION
111 #include "miscutil.h"
113 #include "jbsockets.h"
118 #include "urlmatch.h"
119 #ifdef FEATURE_CLIENT_TAGS
120 #include "client-tags.h"
124 struct client_states clients[1];
125 struct file_list files[1];
127 #ifdef FEATURE_STATISTICS
128 int urls_read = 0; /* total nr of urls read inc rejected */
129 int urls_rejected = 0; /* total nr of urls rejected */
130 #ifdef MUTEX_LOCKS_AVAILABLE
131 unsigned long long number_of_requests_received = 0;
132 unsigned long long number_of_requests_blocked = 0;
134 #endif /* def FEATURE_STATISTICS */
136 #ifdef FEATURE_GRACEFUL_TERMINATION
141 static void sig_handler(int the_signal);
143 static int client_protocol_is_unsupported(struct client_state *csp, char *req);
144 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
145 static jb_err get_server_headers(struct client_state *csp);
146 static const char *crunch_reason(const struct http_response *rsp);
147 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
148 static char *get_request_line(struct client_state *csp);
149 static jb_err receive_client_request(struct client_state *csp);
150 static jb_err parse_client_request(struct client_state *csp);
151 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
152 static jb_err change_request_destination(struct client_state *csp);
153 static void handle_established_connection(struct client_state *csp);
154 static void chat(struct client_state *csp);
155 static void serve(struct client_state *csp);
156 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
157 static void usage(const char *myname);
159 static void initialize_mutexes(void);
160 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
161 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
162 static void close_ports_helper(jb_socket sockets[]);
163 static void listen_loop(void);
164 static void serve(struct client_state *csp);
167 static int32 server_thread(void *data);
168 #endif /* def __BEOS__ */
171 #define sleep(N) Sleep(((N) * 1000))
175 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
176 void show_fuzz_usage(const char *name);
179 #ifdef MUTEX_LOCKS_AVAILABLE
181 * XXX: Does the locking stuff really belong in this file?
183 privoxy_mutex_t log_mutex;
184 privoxy_mutex_t log_init_mutex;
185 privoxy_mutex_t connection_reuse_mutex;
187 #ifdef FEATURE_HTTPS_INSPECTION
188 privoxy_mutex_t certificate_mutex;
189 privoxy_mutex_t ssl_init_mutex;
192 #ifdef FEATURE_EXTERNAL_FILTERS
193 privoxy_mutex_t external_filter_mutex;
195 #ifdef FEATURE_CLIENT_TAGS
196 privoxy_mutex_t client_tags_mutex;
198 #ifdef FEATURE_STATISTICS
199 privoxy_mutex_t block_statistics_mutex;
201 #ifdef FEATURE_EXTENDED_STATISTICS
202 privoxy_mutex_t filter_statistics_mutex;
203 privoxy_mutex_t block_reason_statistics_mutex;
206 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
207 privoxy_mutex_t resolver_mutex;
208 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
210 #ifndef HAVE_GMTIME_R
211 privoxy_mutex_t gmtime_mutex;
212 #endif /* ndef HAVE_GMTIME_R */
214 #ifndef HAVE_LOCALTIME_R
215 privoxy_mutex_t localtime_mutex;
216 #endif /* ndef HAVE_GMTIME_R */
218 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
219 privoxy_mutex_t rand_mutex;
220 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
222 #endif /* def MUTEX_LOCKS_AVAILABLE */
225 const char *basedir = NULL;
226 const char *pidfile = NULL;
227 static int received_hup_signal = 0;
228 #endif /* defined unix */
230 /* HTTP snipplets. */
231 static const char CSUCCEED[] =
232 "HTTP/1.1 200 Connection established\r\n\r\n";
234 static const char CHEADER[] =
235 "HTTP/1.1 400 Invalid header received from client\r\n"
236 "Content-Type: text/plain\r\n"
237 "Connection: close\r\n\r\n"
238 "Invalid header received from client.\n";
240 static const char FTP_RESPONSE[] =
241 "HTTP/1.1 400 Invalid request received from client\r\n"
242 "Content-Type: text/plain\r\n"
243 "Connection: close\r\n\r\n"
244 "Invalid request. Privoxy doesn't support FTP.\n";
246 static const char GOPHER_RESPONSE[] =
247 "HTTP/1.1 400 Invalid request received from client\r\n"
248 "Content-Type: text/plain\r\n"
249 "Connection: close\r\n\r\n"
250 "Invalid request. Privoxy doesn't support gopher.\n";
252 /* XXX: should be a template */
253 static const char MISSING_DESTINATION_RESPONSE[] =
254 "HTTP/1.1 400 Bad request received from client\r\n"
255 "Content-Type: text/plain\r\n"
256 "Connection: close\r\n\r\n"
257 "Bad request. Privoxy was unable to extract the destination.\n";
259 /* XXX: should be a template */
260 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
261 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
262 "Content-Type: text/plain\r\n"
263 "Connection: close\r\n\r\n"
264 "Bad response. The server or forwarder response doesn't look like HTTP.\n";
266 /* XXX: should be a template */
267 static const char MESSED_UP_REQUEST_RESPONSE[] =
268 "HTTP/1.1 400 Malformed request after rewriting\r\n"
269 "Content-Type: text/plain\r\n"
270 "Connection: close\r\n\r\n"
271 "Bad request. Messed up with header filters.\n";
273 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
274 "HTTP/1.1 503 Too many open connections\r\n"
275 "Content-Type: text/plain\r\n"
276 "Connection: close\r\n\r\n"
277 "Maximum number of open connections reached.\n";
279 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
280 "HTTP/1.1 504 Connection timeout\r\n"
281 "Content-Type: text/plain\r\n"
282 "Connection: close\r\n\r\n"
283 "The connection timed out because the client request didn't arrive in time.\n";
285 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
286 "HTTP/1.1 400 Failed reading client body\r\n"
287 "Content-Type: text/plain\r\n"
288 "Connection: close\r\n\r\n"
289 "Failed parsing or buffering the chunk-encoded client body.\n";
291 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
292 "HTTP/1.1 417 Expecting too much\r\n"
293 "Content-Type: text/plain\r\n"
294 "Connection: close\r\n\r\n"
295 "Privoxy detected an unsupported Expect header value.\n";
297 /* A function to crunch a response */
298 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
300 /* Crunch function flags */
301 #define CF_NO_FLAGS 0
302 /* Cruncher applies to forced requests as well */
303 #define CF_IGNORE_FORCE 1
304 /* Crunched requests are counted for the block statistics */
305 #define CF_COUNT_AS_REJECT 2
307 /* A crunch function and its flags */
310 const crunch_func_ptr cruncher;
314 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
316 /* Complete list of cruncher functions */
317 static const struct cruncher crunchers_all[] = {
318 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
319 { block_url, CF_COUNT_AS_REJECT },
321 { trust_url, CF_COUNT_AS_REJECT },
322 #endif /* def FEATURE_TRUST */
323 { redirect_url, CF_NO_FLAGS },
324 { dispatch_cgi, CF_IGNORE_FORCE},
328 /* Light version, used after tags are applied */
329 static const struct cruncher crunchers_light[] = {
330 { block_url, CF_COUNT_AS_REJECT },
331 { redirect_url, CF_NO_FLAGS },
337 * XXX: Don't we really mean
344 /*********************************************************************
346 * Function : sig_handler
348 * Description : Signal handler for different signals.
349 * Exit gracefully on TERM and INT
350 * or set a flag that will cause the errlog
351 * to be reopened by the main thread on HUP.
354 * 1 : the_signal = the signal cause this function to call
358 *********************************************************************/
359 static void sig_handler(int the_signal)
365 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
377 received_hup_signal = 1;
383 * We shouldn't be here, unless we catch signals
384 * in main() that we can't handle here!
386 log_error(LOG_LEVEL_FATAL,
387 "sig_handler: exiting on unexpected signal %d", the_signal);
395 /*********************************************************************
397 * Function : get_write_delay
399 * Description : Parse the delay-response parameter.
402 * 1 : csp = Current client state (buffers, headers, etc...)
404 * Returns : Number of milliseconds to delay writes.
406 *********************************************************************/
407 static unsigned int get_write_delay(const struct client_state *csp)
413 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
417 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
419 delay = (unsigned)strtol(newval, &endptr, 0);
422 log_error(LOG_LEVEL_FATAL,
423 "Invalid delay-response{} parameter: '%s'", newval);
431 /*********************************************************************
433 * Function : client_protocol_is_unsupported
435 * Description : Checks if the client used a known unsupported
436 * protocol and deals with it by sending an error
440 * 1 : csp = Current client state (buffers, headers, etc...)
441 * 2 : req = the first request line send by the client
443 * Returns : TRUE if an error response has been generated, or
444 * FALSE if the request doesn't look invalid.
446 *********************************************************************/
447 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
450 * If it's a FTP or gopher request, we don't support it.
452 * These checks are better than nothing, but they might
453 * not work in all configurations and some clients might
454 * have problems digesting the answer.
456 * They should, however, never cause more problems than
457 * Privoxy's old behaviour (returning the misleading HTML
460 * "Could not resolve http://(ftp|gopher)://example.org").
462 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
464 const char *response = NULL;
465 const char *protocol = NULL;
467 if (!strncmpic(req, "GET ftp://", 10))
469 response = FTP_RESPONSE;
474 response = GOPHER_RESPONSE;
477 log_error(LOG_LEVEL_ERROR,
478 "%s tried to use Privoxy as %s proxy: %s",
479 csp->ip_addr_str, protocol, req);
480 log_error(LOG_LEVEL_CLF,
481 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
484 #ifdef FEATURE_HTTPS_INSPECTION
485 if (client_use_ssl(csp))
487 ssl_send_data_delayed(&(csp->ssl_client_attr),
488 (const unsigned char *)response, strlen(response),
489 get_write_delay(csp));
494 write_socket_delayed(csp->cfd, response, strlen(response),
495 get_write_delay(csp));
505 /*********************************************************************
507 * Function : client_has_unsupported_expectations
509 * Description : Checks if the client used an unsupported expectation
510 * in which case an error message is delivered.
513 * 1 : csp = Current client state (buffers, headers, etc...)
515 * Returns : TRUE if an error response has been generated, or
516 * FALSE if the request doesn't look invalid.
518 *********************************************************************/
519 static int client_has_unsupported_expectations(const struct client_state *csp)
521 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
523 log_error(LOG_LEVEL_ERROR,
524 "Rejecting request from client %s with unsupported Expect header value",
526 log_error(LOG_LEVEL_CLF,
527 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
528 write_socket_delayed(csp->cfd,
529 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
530 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
531 get_write_delay(csp));
541 /*********************************************************************
543 * Function : get_request_destination_elsewhere
545 * Description : If the client's request was redirected into
546 * Privoxy without the client's knowledge,
547 * the request line lacks the destination host.
549 * This function tries to get it elsewhere,
550 * provided accept-intercepted-requests is enabled.
552 * "Elsewhere" currently only means "Host: header",
553 * but in the future we may ask the redirecting
554 * packet filter to look the destination up.
556 * If the destination stays unknown, an error
557 * response is send to the client and headers
558 * are freed so that chat() can return directly.
561 * 1 : csp = Current client state (buffers, headers, etc...)
562 * 2 : headers = a header list
564 * Returns : JB_ERR_OK if the destination is now known, or
565 * JB_ERR_PARSE if it isn't.
567 *********************************************************************/
568 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
570 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
572 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
573 " Privoxy isn't configured to accept intercepted requests.",
574 csp->ip_addr_str, csp->http->cmd);
575 /* XXX: Use correct size */
576 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
577 csp->ip_addr_str, csp->http->cmd);
579 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
580 get_write_delay(csp));
581 destroy_list(headers);
585 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
587 /* Split the domain we just got for pattern matching */
588 init_domain_components(csp->http);
594 /* We can't work without destination. Go spread the news.*/
596 /* XXX: Use correct size */
597 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
598 csp->ip_addr_str, csp->http->cmd);
599 log_error(LOG_LEVEL_ERROR,
600 "Privoxy was unable to get the destination for %s's request: %s",
601 csp->ip_addr_str, csp->http->cmd);
603 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
604 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
605 destroy_list(headers);
610 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
611 * to get the destination IP address, use it as host directly
612 * or do a reverse DNS lookup first.
617 /*********************************************************************
619 * Function : get_server_headers
621 * Description : Parses server headers in iob and fills them
622 * into csp->headers so that they can later be
626 * 1 : csp = Current client state (buffers, headers, etc...)
628 * Returns : JB_ERR_OK if everything went fine, or
629 * JB_ERR_PARSE if the headers were incomplete.
631 *********************************************************************/
632 static jb_err get_server_headers(struct client_state *csp)
634 int continue_hack_in_da_house = 0;
637 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
642 * continue hack in da house. Ignore the ending of
643 * this head and continue enlisting header lines.
644 * The reason is described below.
646 enlist(csp->headers, "");
647 continue_hack_in_da_house = 0;
650 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
653 * It's a bodyless continue response, don't
654 * stop header parsing after reaching its end.
656 * As a result Privoxy will concatenate the
657 * next response's head and parse and deliver
658 * the headers as if they belonged to one request.
660 * The client will separate them because of the
661 * empty line between them.
663 * XXX: What we're doing here is clearly against
664 * the intended purpose of the continue header,
665 * and under some conditions (HTTP/1.0 client request)
666 * it's a standard violation.
668 * Anyway, "sort of against the spec" is preferable
669 * to "always getting confused by Continue responses"
670 * (Privoxy's behaviour before this hack was added)
672 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
673 continue_hack_in_da_house = 1;
675 else if (*header == '\0')
678 * If the header is empty, but the Continue hack
679 * isn't active, we can assume that we reached the
680 * end of the buffer before we hit the end of the
683 * Inform the caller an let it decide how to handle it.
688 if (JB_ERR_MEMORY == enlist(csp->headers, header))
691 * XXX: Should we quit the request and return a
692 * out of memory error page instead?
694 log_error(LOG_LEVEL_ERROR,
695 "Out of memory while enlisting server headers. %s lost.",
705 /*********************************************************************
707 * Function : crunch_reason
709 * Description : Translates the crunch reason code into a string.
712 * 1 : rsp = a http_response
714 * Returns : A string with the crunch reason or an error description.
716 *********************************************************************/
717 static const char *crunch_reason(const struct http_response *rsp)
719 char * reason = NULL;
724 return "Internal error while searching for crunch reason";
727 switch (rsp->crunch_reason)
730 reason = "Unsupported HTTP feature";
736 reason = "Untrusted";
739 reason = "Redirected";
745 reason = "DNS failure";
747 case FORWARDING_FAILED:
748 reason = "Forwarding failed";
751 reason = "Connection failure";
754 reason = "Out of memory (may mask other reasons)";
756 case CONNECTION_TIMEOUT:
757 reason = "Connection timeout";
760 reason = "No server data received";
763 reason = "No reason recorded";
771 /*********************************************************************
773 * Function : log_applied_actions
775 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
779 * 1 : actions = Current action spec to log
783 *********************************************************************/
784 static void log_applied_actions(const struct current_action_spec *actions)
787 * The conversion to text requires lots of memory allocations so
788 * we only do the conversion if the user is actually interested.
790 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
792 char *actions_as_text = actions_to_line_of_text(actions);
793 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
794 freez(actions_as_text);
799 /*********************************************************************
801 * Function : send_crunch_response
803 * Description : Delivers already prepared response for
804 * intercepted requests, logs the interception
805 * and frees the response.
808 * 1 : csp = Current client state (buffers, headers, etc...)
809 * 2 : rsp = Fully prepared response. Will be freed on exit.
813 *********************************************************************/
814 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
816 const struct http_request *http = csp->http;
820 assert(rsp->head != NULL);
824 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
828 * Extract the status code from the actual head
829 * that will be send to the client. It is the only
830 * way to get it right for all requests, including
831 * the fixed ones for out-of-memory problems.
833 * A head starts like this: 'HTTP/1.1 200...'
837 status_code[0] = rsp->head[9];
838 status_code[1] = rsp->head[10];
839 status_code[2] = rsp->head[11];
840 status_code[3] = '\0';
842 /* Log that the request was crunched and why. */
843 log_applied_actions(csp->action);
844 #ifdef FEATURE_HTTPS_INSPECTION
845 if (client_use_ssl(csp))
847 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
848 http->hostport, http->path);
849 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
850 csp->ip_addr_str, http->gpc, http->hostport, http->path,
851 http->version, status_code, rsp->content_length);
856 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
857 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
858 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
860 /* Write the answer to the client */
861 #ifdef FEATURE_HTTPS_INSPECTION
862 if (client_use_ssl(csp))
864 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
865 (const unsigned char *)rsp->head, rsp->head_length,
866 get_write_delay(csp)) < 0)
867 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
868 (const unsigned char *)rsp->body, rsp->content_length,
869 get_write_delay(csp)) < 0))
871 /* There is nothing we can do about it. */
872 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
873 "for https://%s%s through client socket %d using TLS/SSL",
874 http->hostport, http->url, csp->cfd);
880 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
881 get_write_delay(csp))
882 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
883 get_write_delay(csp)))
885 /* There is nothing we can do about it. */
886 log_error(LOG_LEVEL_CONNECT,
887 "Couldn't deliver the error message for %s through client socket %d: %E",
888 http->url, csp->cfd);
892 /* Clean up and return */
893 if (cgi_error_memory() != rsp)
895 free_http_response(rsp);
901 /*********************************************************************
903 * Function : crunch_response_triggered
905 * Description : Checks if the request has to be crunched,
906 * and delivers the crunch response if necessary.
909 * 1 : csp = Current client state (buffers, headers, etc...)
910 * 2 : crunchers = list of cruncher functions to run
912 * Returns : TRUE if the request was answered with a crunch response
915 *********************************************************************/
916 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
918 struct http_response *rsp = NULL;
919 const struct cruncher *c;
922 * If CGI request crunching is disabled,
923 * check the CGI dispatcher out of order to
924 * prevent unintentional blocks or redirects.
926 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
927 && (NULL != (rsp = dispatch_cgi(csp))))
929 /* Deliver, log and free the interception response. */
930 send_crunch_response(csp, rsp);
931 csp->flags |= CSP_FLAG_CRUNCHED;
935 for (c = crunchers; c->cruncher != NULL; c++)
938 * Check the cruncher if either Privoxy is toggled
939 * on and the request isn't forced, or if the cruncher
940 * applies to forced requests as well.
942 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
943 !(csp->flags & CSP_FLAG_FORCED)) ||
944 (c->flags & CF_IGNORE_FORCE))
946 rsp = c->cruncher(csp);
949 /* Deliver, log and free the interception response. */
950 send_crunch_response(csp, rsp);
951 csp->flags |= CSP_FLAG_CRUNCHED;
952 #ifdef FEATURE_STATISTICS
953 if (c->flags & CF_COUNT_AS_REJECT)
955 #ifdef MUTEX_LOCKS_AVAILABLE
956 privoxy_mutex_lock(&block_statistics_mutex);
957 number_of_requests_blocked++;
958 privoxy_mutex_unlock(&block_statistics_mutex);
960 csp->flags |= CSP_FLAG_REJECTED;
962 #endif /* def FEATURE_STATISTICS */
973 /*********************************************************************
975 * Function : build_request_line
977 * Description : Builds the HTTP request line.
979 * If a HTTP forwarder is used it expects the whole URL,
980 * web servers only get the path.
983 * 1 : csp = Current client state (buffers, headers, etc...)
984 * 2 : fwd = The forwarding spec used for the request.
986 * 3 : request_line = The old request line which will be replaced.
988 * Returns : Nothing. Terminates in case of memory problems.
990 *********************************************************************/
991 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
993 struct http_request *http = csp->http;
996 * Downgrade http version from 1.1 to 1.0
997 * if +downgrade action applies.
999 if ((csp->action->flags & ACTION_DOWNGRADE)
1000 && (!strcmpic(http->version, "HTTP/1.1")))
1002 freez(http->version);
1003 http->version = strdup_or_die("HTTP/1.0");
1007 * Rebuild the request line.
1009 freez(*request_line);
1010 #ifdef FEATURE_HTTPS_INSPECTION
1011 if (fwd != NULL && fwd->forward_host &&
1012 fwd->type != FORWARD_WEBSERVER && client_use_ssl(csp))
1014 *request_line = strdup("CONNECT ");
1019 *request_line = strdup(http->gpc);
1020 string_append(request_line, " ");
1023 if (fwd != NULL && fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1025 #ifdef FEATURE_HTTPS_INSPECTION
1026 if (client_use_ssl(csp))
1028 char port_string[10];
1030 string_append(request_line, http->host);
1031 snprintf(port_string, sizeof(port_string), ":%d", http->port);
1032 string_append(request_line, port_string);
1037 string_append(request_line, http->url);
1042 string_append(request_line, http->path);
1044 string_append(request_line, " ");
1045 string_append(request_line, http->version);
1047 if (*request_line == NULL)
1049 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1051 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1055 /*********************************************************************
1057 * Function : change_request_destination
1059 * Description : Parse a (rewritten) request line and regenerate
1060 * the http request data.
1063 * 1 : csp = Current client state (buffers, headers, etc...)
1065 * Returns : Forwards the parse_http_request() return code.
1066 * Terminates in case of memory problems.
1068 *********************************************************************/
1069 static jb_err change_request_destination(struct client_state *csp)
1071 struct http_request *http = csp->http;
1074 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1075 csp->headers->first->str);
1076 free_http_request(http);
1077 err = parse_http_request(csp->headers->first->str, http);
1078 if (JB_ERR_OK != err)
1080 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1081 jb_err_to_string(err));
1083 if (http->ssl && strcmpic(csp->http->gpc, "CONNECT"))
1086 * A client header filter changed the request URL from
1087 * http:// to https:// which we currently don't support.
1089 log_error(LOG_LEVEL_ERROR, "Changing the request destination from http "
1090 "to https behind the client's back currently isn't supported.");
1091 return JB_ERR_PARSE;
1098 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1099 /*********************************************************************
1101 * Function : server_response_is_complete
1103 * Description : Determines whether we should stop reading
1104 * from the server socket.
1107 * 1 : csp = Current client state (buffers, headers, etc...)
1108 * 2 : content_length = Length of content received so far.
1110 * Returns : TRUE if the response is complete,
1113 *********************************************************************/
1114 static int server_response_is_complete(struct client_state *csp,
1115 unsigned long long content_length)
1117 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1119 if (!strcmpic(csp->http->gpc, "HEAD"))
1122 * "HEAD" implies no body, we are thus expecting
1123 * no content. XXX: incomplete "list" of methods?
1125 csp->expected_content_length = 0;
1126 content_length_known = TRUE;
1127 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1130 if (csp->http->status == 204 || csp->http->status == 304)
1133 * Expect no body. XXX: incomplete "list" of status codes?
1135 csp->expected_content_length = 0;
1136 content_length_known = TRUE;
1137 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1140 return (content_length_known && ((0 == csp->expected_content_length)
1141 || (csp->expected_content_length <= content_length)));
1145 #ifdef FEATURE_CONNECTION_SHARING
1146 /*********************************************************************
1148 * Function : wait_for_alive_connections
1150 * Description : Waits for alive connections to timeout.
1156 *********************************************************************/
1157 static void wait_for_alive_connections(void)
1159 int connections_alive = close_unusable_connections();
1161 while (0 < connections_alive)
1163 log_error(LOG_LEVEL_CONNECT,
1164 "Waiting for %d connections to timeout.",
1167 connections_alive = close_unusable_connections();
1170 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1173 #endif /* def FEATURE_CONNECTION_SHARING */
1176 /*********************************************************************
1178 * Function : save_connection_destination
1180 * Description : Remembers a connection for reuse later on.
1183 * 1 : sfd = Open socket to remember.
1184 * 2 : http = The destination for the connection.
1185 * 3 : fwd = The forwarder settings used.
1186 * 4 : server_connection = storage.
1190 *********************************************************************/
1191 static void save_connection_destination(jb_socket sfd,
1192 const struct http_request *http,
1193 const struct forward_spec *fwd,
1194 struct reusable_connection *server_connection)
1196 assert(sfd != JB_INVALID_SOCKET);
1197 assert(NULL != http->host);
1199 server_connection->sfd = sfd;
1200 server_connection->host = strdup_or_die(http->host);
1201 server_connection->port = http->port;
1203 assert(NULL != fwd);
1204 assert(server_connection->gateway_host == NULL);
1205 assert(server_connection->gateway_port == 0);
1206 assert(server_connection->forwarder_type == 0);
1207 assert(server_connection->forward_host == NULL);
1208 assert(server_connection->forward_port == 0);
1210 server_connection->forwarder_type = fwd->type;
1211 if (NULL != fwd->gateway_host)
1213 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1217 server_connection->gateway_host = NULL;
1219 server_connection->gateway_port = fwd->gateway_port;
1220 if (NULL != fwd->auth_username)
1222 server_connection->auth_username = strdup_or_die(fwd->auth_username);
1226 server_connection->auth_username = NULL;
1228 if (NULL != fwd->auth_password)
1230 server_connection->auth_password = strdup_or_die(fwd->auth_password);
1234 server_connection->auth_password = NULL;
1237 if (NULL != fwd->forward_host)
1239 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1243 server_connection->forward_host = NULL;
1245 server_connection->forward_port = fwd->forward_port;
1247 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1250 /*********************************************************************
1252 * Function : verify_request_length
1254 * Description : Checks if we already got the whole client requests
1255 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1258 * Data that doesn't belong to the current request is
1259 * either thrown away to let the client retry on a clean
1260 * socket, or stashed to be dealt with after the current
1261 * request is served.
1264 * 1 : csp = Current client state (buffers, headers, etc...)
1268 *********************************************************************/
1269 static void verify_request_length(struct client_state *csp)
1271 unsigned long long buffered_request_bytes =
1272 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1274 if ((csp->expected_client_content_length != 0)
1275 && (buffered_request_bytes != 0))
1277 if (csp->expected_client_content_length >= buffered_request_bytes)
1279 csp->expected_client_content_length -= buffered_request_bytes;
1280 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1281 "to account for the %llu ones we already got.",
1282 csp->expected_client_content_length, buffered_request_bytes);
1286 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1287 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1288 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1289 "Marking the server socket tainted after throwing %llu bytes away.",
1290 buffered_request_bytes - csp->expected_client_content_length);
1291 csp->expected_client_content_length = 0;
1292 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1295 if (csp->expected_client_content_length == 0)
1297 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1301 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1302 && ((csp->client_iob->cur < csp->client_iob->eod)
1303 || (csp->expected_client_content_length != 0)))
1305 if (strcmpic(csp->http->gpc, "GET")
1306 && strcmpic(csp->http->gpc, "HEAD")
1307 && strcmpic(csp->http->gpc, "TRACE")
1308 && strcmpic(csp->http->gpc, "OPTIONS")
1309 && strcmpic(csp->http->gpc, "DELETE"))
1311 /* XXX: this is an incomplete hack */
1312 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1313 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1317 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1319 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1321 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1322 log_error(LOG_LEVEL_CONNECT,
1323 "Possible pipeline attempt detected. The connection will not "
1324 "be kept alive and we will only serve the first request.");
1325 /* Nuke the pipelined requests from orbit, just to be sure. */
1326 clear_iob(csp->client_iob);
1331 * Keep the pipelined data around for now, we'll deal with
1332 * it once we're done serving the current request.
1334 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1335 assert(csp->client_iob->eod >= csp->client_iob->cur);
1336 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1337 "%d bytes of pipelined data received.",
1338 (int)(csp->client_iob->eod - csp->client_iob->cur));
1344 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1345 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1350 /*********************************************************************
1352 * Function : mark_server_socket_tainted
1354 * Description : Makes sure we don't reuse a server socket
1355 * (if we didn't read everything the server sent
1356 * us reusing the socket would lead to garbage).
1359 * 1 : csp = Current client state (buffers, headers, etc...)
1363 *********************************************************************/
1364 static void mark_server_socket_tainted(struct client_state *csp)
1367 * For consistency we always mark the server socket
1368 * tainted, however, to reduce the log noise we only
1369 * emit a log message if the server socket could have
1370 * actually been reused.
1372 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1373 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1375 log_error(LOG_LEVEL_CONNECT,
1376 "Marking the server socket %d tainted.",
1377 csp->server_connection.sfd);
1379 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1382 /*********************************************************************
1384 * Function : get_request_line
1386 * Description : Read the client request line.
1389 * 1 : csp = Current client state (buffers, headers, etc...)
1391 * Returns : Pointer to request line or NULL in case of errors.
1393 *********************************************************************/
1394 static char *get_request_line(struct client_state *csp)
1396 char buf[BUFFER_SIZE];
1397 char *request_line = NULL;
1400 memset(buf, 0, sizeof(buf));
1402 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1405 * If there are multiple pipelined requests waiting,
1406 * the flag will be set again once the next request
1409 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1411 request_line = get_header(csp->client_iob);
1412 if ((NULL != request_line) && ('\0' != *request_line))
1414 return request_line;
1418 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1419 "received yet. Continuing reading from %d.", csp->cfd);
1427 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1429 !data_is_available(csp->cfd, csp->config->socket_timeout)
1432 if (socket_is_still_alive(csp->cfd))
1434 log_error(LOG_LEVEL_CONNECT,
1435 "No request line on socket %d received in time. Timeout: %d.",
1436 csp->cfd, csp->config->socket_timeout);
1437 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1438 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1439 get_write_delay(csp));
1443 log_error(LOG_LEVEL_CONNECT,
1444 "The client side of the connection on socket %d got "
1445 "closed without sending a complete request line.", csp->cfd);
1450 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1452 if (len <= 0) return NULL;
1455 * If there is no memory left for buffering the
1456 * request, there is nothing we can do but hang up
1458 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1463 request_line = get_header(csp->client_iob);
1465 } while ((NULL != request_line) && ('\0' == *request_line));
1467 return request_line;
1473 CHUNK_STATUS_MISSING_DATA,
1474 CHUNK_STATUS_BODY_COMPLETE,
1475 CHUNK_STATUS_PARSE_ERROR
1479 /*********************************************************************
1481 * Function : chunked_body_is_complete
1483 * Description : Figures out whether or not a chunked body is complete.
1485 * Currently it always starts at the beginning of the
1486 * buffer which is somewhat wasteful and prevents Privoxy
1487 * from starting to forward the correctly parsed chunks
1488 * as soon as theoretically possible.
1490 * Should be modified to work with a common buffer,
1491 * and allow the caller to skip already parsed chunks.
1493 * This would allow the function to be used for unbuffered
1494 * response bodies as well.
1497 * 1 : iob = Buffer with the body to check.
1498 * 2 : length = Length of complete body
1500 * Returns : Enum with the result of the check.
1502 *********************************************************************/
1503 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1505 unsigned int chunksize;
1511 * We need at least a single digit, followed by "\r\n",
1512 * followed by an unknown amount of data, followed by "\r\n".
1514 if (p + 5 > iob->eod)
1516 return CHUNK_STATUS_MISSING_DATA;
1518 if (sscanf(p, "%x", &chunksize) != 1)
1520 return CHUNK_STATUS_PARSE_ERROR;
1524 * We want at least a single digit, followed by "\r\n",
1525 * followed by the specified amount of data, followed by "\r\n".
1527 if (p + chunksize + 5 > iob->eod)
1529 return CHUNK_STATUS_MISSING_DATA;
1532 /* Skip chunk-size. */
1533 p = strstr(p, "\r\n");
1536 return CHUNK_STATUS_PARSE_ERROR;
1538 /* Move beyond the chunkdata. */
1541 /* Make sure we're still within the buffer and have two bytes left */
1542 if (p + 2 > iob->eod)
1544 return CHUNK_STATUS_MISSING_DATA;
1547 /* There should be another "\r\n" to skip */
1548 if (memcmp(p, "\r\n", 2))
1550 return CHUNK_STATUS_PARSE_ERROR;
1553 } while (chunksize > 0U);
1555 *length = (size_t)(p - iob->cur);
1556 assert(*length <= (size_t)(iob->eod - iob->cur));
1557 assert(p <= iob->eod);
1559 return CHUNK_STATUS_BODY_COMPLETE;
1564 /*********************************************************************
1566 * Function : receive_chunked_client_request_body
1568 * Description : Read the chunk-encoded client request body.
1569 * Failures are dealt with.
1572 * 1 : csp = Current client state (buffers, headers, etc...)
1574 * Returns : JB_ERR_OK or JB_ERR_PARSE
1576 *********************************************************************/
1577 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1580 enum chunk_status status;
1582 while (CHUNK_STATUS_MISSING_DATA ==
1583 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1585 char buf[BUFFER_SIZE];
1588 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1590 log_error(LOG_LEVEL_ERROR,
1591 "Timeout while waiting for the client body.");
1594 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1597 log_error(LOG_LEVEL_ERROR,
1598 "Reading the client body failed: %E");
1601 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1606 if (status != CHUNK_STATUS_BODY_COMPLETE)
1608 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1609 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1610 log_error(LOG_LEVEL_CLF,
1611 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1612 return JB_ERR_PARSE;
1614 log_error(LOG_LEVEL_CONNECT,
1615 "Chunked client body completely read. Length: %lu", body_length);
1616 csp->expected_client_content_length = body_length;
1624 /*********************************************************************
1626 * Function : fuzz_chunked_transfer_encoding
1628 * Description : Treat the fuzzed input as chunked transfer encoding
1629 * to check and dechunk.
1632 * 1 : csp = Used to store the data.
1633 * 2 : fuzz_input_file = File to read the input from.
1635 * Returns : Result of dechunking
1637 *********************************************************************/
1638 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1641 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1642 enum chunk_status status;
1644 status = chunked_body_is_complete(csp->iob, &length);
1645 if (CHUNK_STATUS_BODY_COMPLETE != status)
1647 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1650 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1655 /*********************************************************************
1657 * Function : fuzz_client_request
1659 * Description : Try to get a client request from the fuzzed input.
1662 * 1 : csp = Current client state (buffers, headers, etc...)
1663 * 2 : fuzz_input_file = File to read the input from.
1665 * Returns : Result of fuzzing.
1667 *********************************************************************/
1668 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1673 csp->ip_addr_str = "fuzzer";
1675 if (strcmp(fuzz_input_file, "-") != 0)
1677 log_error(LOG_LEVEL_FATAL,
1678 "Fuzzed client requests can currently only be read from stdin (-).");
1680 err = receive_client_request(csp);
1681 if (err != JB_ERR_OK)
1685 err = parse_client_request(csp);
1686 if (err != JB_ERR_OK)
1694 #endif /* def FUZZ */
1697 #ifdef FEATURE_FORCE_LOAD
1698 /*********************************************************************
1700 * Function : force_required
1702 * Description : Checks a request line to see if it contains
1703 * the FORCE_PREFIX. If it does, it is removed
1704 * unless enforcing requests has beend disabled.
1707 * 1 : request_line = HTTP request line
1709 * Returns : TRUE if force is required, FALSE otherwise.
1711 *********************************************************************/
1712 static int force_required(const struct client_state *csp, char *request_line)
1716 p = strstr(request_line, "http://");
1720 p += strlen("http://");
1724 /* Intercepted request usually don't specify the protocol. */
1728 /* Go to the beginning of the path */
1733 * If the path is missing the request line is invalid and we
1734 * are done here. The client-visible rejection happens later on.
1739 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1741 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1743 /* XXX: Should clean more carefully */
1744 strclean(request_line, FORCE_PREFIX);
1745 log_error(LOG_LEVEL_FORCE,
1746 "Enforcing request: \"%s\".", request_line);
1750 log_error(LOG_LEVEL_FORCE,
1751 "Ignored force prefix in request: \"%s\".", request_line);
1757 #endif /* def FEATURE_FORCE_LOAD */
1760 /*********************************************************************
1762 * Function : receive_client_request
1764 * Description : Read the client's request (more precisely the
1765 * client headers) and answer it if necessary.
1768 * 1 : csp = Current client state (buffers, headers, etc...)
1770 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1772 *********************************************************************/
1773 static jb_err receive_client_request(struct client_state *csp)
1775 char buf[BUFFER_SIZE];
1778 struct http_request *http;
1782 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1783 struct list header_list;
1784 struct list *headers = &header_list;
1786 /* We don't care if the arriving data is a valid HTTP request or not. */
1787 csp->requests_received_total++;
1791 memset(buf, 0, sizeof(buf));
1793 req = get_request_line(csp);
1796 mark_server_socket_tainted(csp);
1797 return JB_ERR_PARSE;
1799 assert(*req != '\0');
1801 if (client_protocol_is_unsupported(csp, req))
1803 return JB_ERR_PARSE;
1806 #ifdef FEATURE_FORCE_LOAD
1807 if (force_required(csp, req))
1809 csp->flags |= CSP_FLAG_FORCED;
1811 #endif /* def FEATURE_FORCE_LOAD */
1813 err = parse_http_request(req, http);
1815 if (JB_ERR_OK != err)
1817 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1818 get_write_delay(csp));
1819 /* XXX: Use correct size */
1820 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1821 log_error(LOG_LEVEL_ERROR,
1822 "Couldn't parse request line received from %s: %s",
1823 csp->ip_addr_str, jb_err_to_string(err));
1825 free_http_request(http);
1826 return JB_ERR_PARSE;
1828 if (http->ssl && strcmpic(http->gpc, "CONNECT"))
1830 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1831 get_write_delay(csp));
1832 /* XXX: Use correct size */
1833 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0",
1835 log_error(LOG_LEVEL_ERROR, "Client %s tried to send a https "
1836 "URL without sending a CONNECT request first",
1838 free_http_request(http);
1839 return JB_ERR_PARSE;
1842 /* grab the rest of the client's headers */
1846 p = get_header(csp->client_iob);
1850 /* There are no additional headers to read. */
1857 * We didn't receive a complete header
1858 * line yet, get the rest of it.
1860 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1862 log_error(LOG_LEVEL_ERROR,
1863 "Client headers did not arrive in time. Timeout: %d",
1864 csp->config->socket_timeout);
1865 destroy_list(headers);
1866 return JB_ERR_PARSE;
1869 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1872 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1873 destroy_list(headers);
1874 return JB_ERR_PARSE;
1877 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1880 * If there is no memory left for buffering the
1881 * request, there is nothing we can do but hang up
1883 destroy_list(headers);
1884 return JB_ERR_MEMORY;
1889 if (!strncmpic(p, "Transfer-Encoding:", 18))
1892 * XXX: should be called through sed()
1893 * but currently can't.
1895 client_transfer_encoding(csp, &p);
1898 * We were able to read a complete
1899 * header and can finally enlist it.
1906 if (http->host == NULL)
1909 * If we still don't know the request destination,
1910 * the request is invalid or the client uses
1911 * Privoxy without its knowledge.
1913 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1916 * Our attempts to get the request destination
1917 * elsewhere failed or Privoxy is configured
1918 * to only accept proxy requests.
1920 * An error response has already been sent
1921 * and we're done here.
1923 return JB_ERR_PARSE;
1927 #ifdef FEATURE_CLIENT_TAGS
1928 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1929 set_client_address(csp, headers);
1930 get_tag_list_for_client(csp->client_tags, csp->client_address);
1934 * Determine the actions for this URL
1936 #ifdef FEATURE_TOGGLE
1937 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1939 /* Most compatible set of actions (i.e. none) */
1940 init_current_action(csp->action);
1943 #endif /* ndef FEATURE_TOGGLE */
1945 get_url_actions(csp, http);
1948 enlist(csp->headers, http->cmd);
1950 /* Append the previously read headers */
1951 err = list_append_list_unique(csp->headers, headers);
1952 destroy_list(headers);
1959 /*********************************************************************
1961 * Function : parse_client_request
1963 * Description : Parses the client's request and decides what to do
1966 * Note that since we're not using select() we could get
1967 * blocked here if a client connected, then didn't say
1971 * 1 : csp = Current client state (buffers, headers, etc...)
1973 * Returns : JB_ERR_OK or JB_ERR_PARSE
1975 *********************************************************************/
1976 static jb_err parse_client_request(struct client_state *csp)
1978 struct http_request *http = csp->http;
1981 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1982 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1983 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1984 && (csp->http->ssl == 0))
1986 /* Assume persistence until further notice */
1987 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1989 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1991 if (csp->http->ssl == 0)
1994 * This whole block belongs to chat() but currently
1995 * has to be executed before sed().
1997 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1999 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
2001 return JB_ERR_PARSE;
2006 csp->expected_client_content_length = get_expected_content_length(csp->headers);
2008 verify_request_length(csp);
2010 #ifndef FEATURE_HTTPS_INSPECTION
2013 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2017 err = sed(csp, FILTER_CLIENT_HEADERS);
2018 if (JB_ERR_OK != err)
2020 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2022 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2023 csp->ip_addr_str, csp->http->cmd);
2024 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
2025 return JB_ERR_PARSE;
2027 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
2029 /* Check request line for rewrites. */
2030 if ((NULL == csp->headers->first->str)
2031 || (strcmp(http->cmd, csp->headers->first->str) &&
2032 (JB_ERR_OK != change_request_destination(csp))))
2035 * A header filter broke the request line - bail out.
2037 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
2038 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2039 /* XXX: Use correct size */
2040 log_error(LOG_LEVEL_CLF,
2041 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2042 log_error(LOG_LEVEL_ERROR,
2043 "Invalid request line after applying header filters.");
2044 free_http_request(http);
2046 return JB_ERR_PARSE;
2049 if (client_has_unsupported_expectations(csp))
2051 return JB_ERR_PARSE;
2059 /*********************************************************************
2061 * Function : read_http_request_body
2063 * Description : Reads remaining request body from the client.
2066 * 1 : csp = Current client state (buffers, headers, etc...)
2068 * Returns : 0 on success, anything else is an error.
2070 *********************************************************************/
2071 static int read_http_request_body(struct client_state *csp)
2073 size_t to_read = csp->expected_client_content_length;
2076 assert(to_read != 0);
2078 /* check if all data has been already read */
2079 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2084 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2085 to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2086 to_read -= (unsigned)len)
2088 char buf[BUFFER_SIZE];
2089 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2091 log_error(LOG_LEVEL_CONNECT,
2092 "Waiting for up to %lu bytes of request body from the client.",
2094 len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2097 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2100 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2104 assert(to_read >= len);
2109 log_error(LOG_LEVEL_CONNECT,
2110 "Not enough request body has been read: expected %lu more bytes",
2114 log_error(LOG_LEVEL_CONNECT,
2115 "The last %d bytes of the request body have been read", len);
2120 /*********************************************************************
2122 * Function : update_client_headers
2124 * Description : Updates the HTTP headers from the client request.
2127 * 1 : csp = Current client state (buffers, headers, etc...)
2128 * 2 : new_content_length = new content length value to set
2130 * Returns : 0 on success, anything else is an error.
2132 *********************************************************************/
2133 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2135 static const char content_length[] = "Content-Length:";
2137 struct list_entry *p;
2139 #ifndef FEATURE_HTTPS_INSPECTION
2140 for (p = csp->headers->first;
2142 for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2144 !updated && (p != NULL); p = p->next)
2146 /* Header crunch()ed in previous run? -> ignore */
2152 /* Does the current parser handle this header? */
2153 if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2155 updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2167 /*********************************************************************
2169 * Function : can_filter_request_body
2171 * Description : Checks if the current request body can be stored in
2172 * the client_iob without hitting buffer limit.
2175 * 1 : csp = Current client state (buffers, headers, etc...)
2177 * Returns : TRUE if the current request size do not exceed buffer limit
2180 *********************************************************************/
2181 static int can_filter_request_body(const struct client_state *csp)
2183 if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2184 csp->expected_client_content_length))
2186 log_error(LOG_LEVEL_INFO,
2187 "Not filtering request body from %s: buffer limit %lu will be exceeded "
2188 "(content length %llu)", csp->ip_addr_str, csp->config->buffer_limit,
2189 csp->expected_client_content_length);
2196 /*********************************************************************
2198 * Function : send_http_request
2200 * Description : Sends the HTTP headers from the client request
2201 * and all the body data that has already been received.
2204 * 1 : csp = Current client state (buffers, headers, etc...)
2206 * Returns : 0 on success, anything else is an error.
2208 *********************************************************************/
2209 static int send_http_request(struct client_state *csp)
2213 const char *to_send;
2215 int filter_client_body = csp->expected_client_content_length != 0 &&
2216 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2218 if (filter_client_body)
2220 if (read_http_request_body(csp))
2224 to_send_len = csp->expected_client_content_length;
2225 to_send = execute_client_body_filters(csp, &to_send_len);
2226 if (to_send == NULL)
2228 /* just flush client_iob */
2229 filter_client_body = FALSE;
2231 else if (to_send_len != csp->expected_client_content_length &&
2232 update_client_headers(csp, to_send_len))
2234 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2238 csp->expected_client_content_length = 0;
2241 hdr = list_to_text(csp->headers);
2244 /* FIXME Should handle error properly */
2245 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2247 list_remove_all(csp->headers);
2250 * Write the client's (modified) header to the server
2251 * (along with anything else that may be in the buffer)
2253 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2258 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2259 csp->http->hostport);
2260 if (filter_client_body)
2267 if (filter_client_body)
2269 write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2273 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2274 csp->http->hostport);
2279 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2280 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2282 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2283 csp->http->hostport);
2290 #ifdef FEATURE_HTTPS_INSPECTION
2291 /*********************************************************************
2293 * Function : read_https_request_body
2295 * Description : Reads remaining request body from the client.
2298 * 1 : csp = Current client state (buffers, headers, etc...)
2300 * Returns : 0 on success, anything else is an error.
2302 *********************************************************************/
2303 static int read_https_request_body(struct client_state *csp)
2305 size_t to_read = csp->expected_client_content_length;
2308 assert(to_read != 0);
2310 /* check if all data has been already read */
2311 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2316 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2317 to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2318 data_is_available(csp->cfd, csp->config->socket_timeout));
2319 to_read -= (unsigned)len)
2321 unsigned char buf[BUFFER_SIZE];
2322 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2324 log_error(LOG_LEVEL_CONNECT,
2325 "Waiting for up to %lu bytes of request body from the client.",
2327 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2328 (unsigned)max_bytes_to_read);
2331 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2334 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2338 assert(to_read >= len);
2343 log_error(LOG_LEVEL_CONNECT,
2344 "Not enough request body has been read: expected %lu more bytes",
2349 log_error(LOG_LEVEL_CONNECT,
2350 "The last %llu bytes of the request body have been read",
2351 csp->expected_client_content_length);
2356 /*********************************************************************
2358 * Function : receive_and_send_encrypted_post_data
2360 * Description : Reads remaining request body from the client and sends
2364 * 1 : csp = Current client state (buffers, headers, etc...)
2366 * Returns : 0 on success, anything else is an error.
2368 *********************************************************************/
2369 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2371 int content_length_known = csp->expected_client_content_length != 0;
2373 while ((content_length_known && csp->expected_client_content_length != 0) ||
2374 (is_ssl_pending(&(csp->ssl_client_attr)) ||
2375 data_is_available(csp->cfd, csp->config->socket_timeout)))
2377 unsigned char buf[BUFFER_SIZE];
2379 int max_bytes_to_read = sizeof(buf);
2381 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2383 max_bytes_to_read = (int)csp->expected_client_content_length;
2385 log_error(LOG_LEVEL_CONNECT,
2386 "Waiting for up to %d bytes of request body from the client.",
2388 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2389 (unsigned)max_bytes_to_read);
2396 /* XXX: Does this actually happen? */
2399 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2401 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2406 if (csp->expected_client_content_length != 0)
2408 if (csp->expected_client_content_length >= len)
2410 csp->expected_client_content_length -= (unsigned)len;
2412 if (csp->expected_client_content_length == 0)
2414 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2420 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2427 /*********************************************************************
2429 * Function : send_https_request
2431 * Description : Sends the HTTP headers from the client request
2432 * and all the body data that has already been received.
2435 * 1 : csp = Current client state (buffers, headers, etc...)
2437 * Returns : 0 on success, anything else is an error.
2439 *********************************************************************/
2440 static int send_https_request(struct client_state *csp)
2445 const char *to_send;
2447 int filter_client_body = csp->expected_client_content_length != 0 &&
2448 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2450 if (filter_client_body)
2452 if (read_https_request_body(csp))
2456 to_send_len = csp->expected_client_content_length;
2457 to_send = execute_client_body_filters(csp, &to_send_len);
2458 if (to_send == NULL)
2460 /* just flush client_iob */
2461 filter_client_body = FALSE;
2463 else if (to_send_len != csp->expected_client_content_length &&
2464 update_client_headers(csp, to_send_len))
2466 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2469 csp->expected_client_content_length = 0;
2472 hdr = list_to_text(csp->https_headers);
2475 /* FIXME Should handle error properly */
2476 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2478 list_remove_all(csp->https_headers);
2481 * Write the client's (modified) header to the server
2482 * (along with anything else that may be in the buffer)
2484 ret = ssl_send_data(&(csp->ssl_server_attr),
2485 (const unsigned char *)hdr, strlen(hdr));
2490 log_error(LOG_LEVEL_CONNECT,
2491 "Failed sending encrypted request headers to: %s: %E",
2492 csp->http->hostport);
2493 mark_server_socket_tainted(csp);
2497 if (filter_client_body)
2499 ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2503 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2504 csp->http->hostport);
2509 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2510 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2511 csp->client_iob)) < 0))
2513 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2514 csp->http->hostport);
2517 if (flushed != 0 || csp->expected_client_content_length != 0)
2519 if (csp->expected_client_content_length != 0)
2521 if (csp->expected_client_content_length < flushed)
2523 log_error(LOG_LEVEL_ERROR,
2524 "Flushed %ld bytes of request body while only expecting %llu",
2525 flushed, csp->expected_client_content_length);
2526 csp->expected_client_content_length = 0;
2530 log_error(LOG_LEVEL_CONNECT,
2531 "Flushed %ld bytes of request body while expecting %llu",
2532 flushed, csp->expected_client_content_length);
2533 csp->expected_client_content_length -= (unsigned)flushed;
2534 if (receive_and_send_encrypted_post_data(csp))
2542 log_error(LOG_LEVEL_CONNECT,
2543 "Flushed %ld bytes of request body", flushed);
2547 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2554 /*********************************************************************
2556 * Function : receive_encrypted_request_headers
2558 * Description : Receives the encrypted request headers when
2562 * 1 : csp = Current client state (buffers, headers, etc...)
2564 * Returns : JB_ERR_OK on success,
2565 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2567 *********************************************************************/
2568 static jb_err receive_encrypted_request_headers(struct client_state *csp)
2570 char buf[BUFFER_SIZE];
2576 log_error(LOG_LEVEL_HEADER, "Waiting for encrypted client headers");
2577 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2578 !data_is_available(csp->cfd, csp->config->socket_timeout))
2580 log_error(LOG_LEVEL_CONNECT,
2581 "Socket %d timed out while waiting for client headers", csp->cfd);
2582 return JB_ERR_PARSE;
2584 len = ssl_recv_data(&(csp->ssl_client_attr),
2585 (unsigned char *)buf, sizeof(buf));
2588 log_error(LOG_LEVEL_CONNECT,
2589 "Socket %d closed while waiting for client headers", csp->cfd);
2590 return JB_ERR_PARSE;
2594 return JB_ERR_PARSE;
2596 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2598 return JB_ERR_MEMORY;
2600 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2601 } while (p == NULL);
2603 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2609 /*********************************************************************
2611 * Function : change_encrypted_request_destination
2613 * Description : Parse a (rewritten) request line from an encrypted
2614 * request and regenerate the http request data.
2617 * 1 : csp = Current client state (buffers, headers, etc...)
2619 * Returns : Forwards the parse_http_request() return code.
2620 * Terminates in case of memory problems.
2622 *********************************************************************/
2623 static jb_err change_encrypted_request_destination(struct client_state *csp)
2626 char *original_host = csp->http->host;
2627 int original_port = csp->http->port;
2629 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2630 csp->https_headers->first->str);
2631 csp->http->host = NULL;
2632 free_http_request(csp->http);
2633 err = parse_http_request(csp->https_headers->first->str, csp->http);
2634 if (JB_ERR_OK != err)
2636 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2637 jb_err_to_string(err));
2638 freez(original_host);
2642 if (csp->http->host == NULL)
2644 char port_string[10];
2646 * The rewritten request line did not specify a host
2647 * which means we can use the original host specified
2650 csp->http->host = original_host;
2651 csp->http->port = original_port;
2652 log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2655 * If the rewritten request line didn't contain a host
2656 * it also didn't contain a port so we can reuse the host
2659 freez(csp->http->hostport);
2660 csp->http->hostport = strdup_or_die(csp->http->host);
2661 snprintf(port_string, sizeof(port_string), ":%d", original_port);
2662 err = string_append(&csp->http->hostport, port_string);
2663 if (err != JB_ERR_OK)
2665 log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2666 jb_err_to_string(err));
2671 * While the request line didn't mention it,
2672 * we're https-inspecting and want to speak TLS
2675 csp->http->server_ssl = 1;
2680 /* The rewrite filter added a host so we can ditch the original */
2681 freez(original_host);
2682 csp->http->server_ssl = csp->http->ssl;
2685 csp->http->client_ssl = 1;
2687 freez(csp->https_headers->first->str);
2688 build_request_line(csp, NULL, &csp->https_headers->first->str);
2690 if (!server_use_ssl(csp))
2692 log_error(LOG_LEVEL_REDIRECTS,
2693 "Rewritten request line results in downgrade to http");
2695 * Replace the unencryptd headers received with the
2696 * CONNECT request with the ones we received securely.
2698 destroy_list(csp->headers);
2699 csp->headers->first = csp->https_headers->first;
2700 csp->headers->last = csp->https_headers->last;
2701 csp->https_headers->first = NULL;
2702 csp->https_headers->last = NULL;
2710 /*********************************************************************
2712 * Function : process_encrypted_request_headers
2714 * Description : Receives and parses the encrypted headers send
2715 * by the client when https-inspecting.
2718 * 1 : csp = Current client state (buffers, headers, etc...)
2720 * Returns : JB_ERR_OK on success,
2721 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2723 *********************************************************************/
2724 static jb_err process_encrypted_request_headers(struct client_state *csp)
2729 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2730 struct list header_list;
2731 struct list *headers = &header_list;
2733 assert(csp->ssl_with_client_is_opened);
2735 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2736 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2738 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2741 err = receive_encrypted_request_headers(csp);
2742 if (err != JB_ERR_OK)
2744 if (csp->client_iob->cur == NULL ||
2745 csp->client_iob->cur == csp->client_iob->eod)
2748 * We did not receive any data, most likely because the
2749 * client is done. Don't log this as a parse failure.
2751 return JB_ERR_PARSE;
2753 /* XXX: Also used for JB_ERR_MEMORY */
2754 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2755 jb_err_to_string(err));
2756 ssl_send_data_delayed(&(csp->ssl_client_attr),
2757 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2761 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2762 request_line = get_header(csp->client_iob);
2763 if (request_line == NULL)
2765 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2766 ssl_send_data_delayed(&(csp->ssl_client_attr),
2767 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2768 return JB_ERR_PARSE;
2770 assert(*request_line != '\0');
2772 if (client_protocol_is_unsupported(csp, request_line))
2775 * If the protocol is unsupported we're done here.
2776 * client_protocol_is_unsupported() took care of sending
2777 * the error response and logging the error message.
2779 return JB_ERR_PARSE;
2782 #ifdef FEATURE_FORCE_LOAD
2783 if (force_required(csp, request_line))
2785 csp->flags |= CSP_FLAG_FORCED;
2787 #endif /* def FEATURE_FORCE_LOAD */
2789 free_http_request(csp->http);
2791 err = parse_http_request(request_line, csp->http);
2792 /* XXX: Restore ssl setting. This is ugly */
2793 csp->http->client_ssl = 1;
2794 csp->http->server_ssl = 1;
2796 freez(request_line);
2797 if (JB_ERR_OK != err)
2799 ssl_send_data_delayed(&(csp->ssl_client_attr),
2800 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2801 /* XXX: Use correct size */
2802 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2803 log_error(LOG_LEVEL_ERROR,
2804 "Couldn't parse request line received from %s: %s",
2805 csp->ip_addr_str, jb_err_to_string(err));
2807 free_http_request(csp->http);
2808 return JB_ERR_PARSE;
2811 /* Parse the rest of the client's headers. */
2815 p = get_header(csp->client_iob);
2819 /* There are no additional headers to read. */
2826 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2829 * Our attempts to get the request destination
2832 log_error(LOG_LEVEL_ERROR,
2833 "Failed to get the encrypted request destination");
2834 ssl_send_data_delayed(&(csp->ssl_client_attr),
2835 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2836 destroy_list(headers);
2838 return JB_ERR_PARSE;
2841 /* Split the domain we just got for pattern matching */
2842 init_domain_components(csp->http);
2844 #ifdef FEATURE_CLIENT_TAGS
2845 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2846 if (csp->client_address == NULL)
2848 set_client_address(csp, headers);
2849 get_tag_list_for_client(csp->client_tags, csp->client_address);
2853 #ifdef FEATURE_TOGGLE
2854 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2858 * Determine the actions for this request after
2859 * clearing the ones from the previous one.
2861 free_current_action(csp->action);
2862 get_url_actions(csp, csp->http);
2865 enlist(csp->https_headers, csp->http->cmd);
2867 /* Append the previously read headers */
2868 err = list_append_list_unique(csp->https_headers, headers);
2869 destroy_list(headers);
2870 if (JB_ERR_OK != err)
2872 /* XXX: Send error message */
2876 /* XXX: Work around crash */
2877 csp->error_message = NULL;
2879 /* XXX: Why do this here? */
2882 err = sed_https(csp);
2883 if (JB_ERR_OK != err)
2885 ssl_send_data_delayed(&(csp->ssl_client_attr),
2886 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2887 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2889 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2890 csp->ip_addr_str, csp->http->cmd);
2891 return JB_ERR_PARSE;
2894 if ((NULL == csp->https_headers->first->str)
2895 || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2896 (JB_ERR_OK != change_encrypted_request_destination(csp))))
2898 ssl_send_data_delayed(&(csp->ssl_client_attr),
2899 (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2900 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2901 log_error(LOG_LEVEL_ERROR,
2902 "Invalid request line after applying header filters.");
2903 /* XXX: Use correct size */
2904 log_error(LOG_LEVEL_CLF,
2905 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2907 return JB_ERR_PARSE;
2910 log_error(LOG_LEVEL_HEADER, "Encrypted request headers processed");
2911 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2918 /*********************************************************************
2920 * Function : cgi_page_requested
2922 * Description : Checks if a request is for an internal CGI page.
2925 * 1 : host = The host requested by the client.
2927 * Returns : 1 if a CGI page has been requested, 0 otherwise
2929 *********************************************************************/
2930 static int cgi_page_requested(const char *host)
2932 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2933 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2934 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2935 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2945 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2946 /*********************************************************************
2948 * Function : continue_https_chat
2950 * Description : Behaves similar to chat() but only deals with
2951 * https-inspected requests that arrive on an already
2952 * established connection. The first request is always
2953 * served by chat() which is a lot more complex as it
2954 * has to deal with forwarding settings and connection
2957 * If a connection to the server has already been
2958 * opened it is reused unless the request is blocked
2959 * or the forwarder changed.
2961 * If a connection to the server has not yet been
2962 * opened (because the previous request was crunched),
2963 * or the forwarder changed, the connection is dropped
2964 * so that the client retries on a fresh one.
2967 * 1 : csp = Current client state (buffers, headers, etc...)
2969 * Returns : Nothing.
2971 *********************************************************************/
2972 static void continue_https_chat(struct client_state *csp)
2974 const struct forward_spec *fwd;
2976 if (JB_ERR_OK != process_encrypted_request_headers(csp))
2978 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2982 #if defined(FEATURE_STATISTICS) && defined(MUTEX_LOCKS_AVAILABLE)
2983 privoxy_mutex_lock(&block_statistics_mutex);
2984 number_of_requests_received++;
2985 privoxy_mutex_unlock(&block_statistics_mutex);
2988 csp->requests_received_total++;
2991 * We have an encrypted request. Check if one of the crunchers wants it.
2993 if (crunch_response_triggered(csp, crunchers_all))
2996 * Yes. The client got the crunch response and we're done here.
3000 if (csp->ssl_with_server_is_opened == 0)
3002 log_error(LOG_LEVEL_CONNECT,
3003 "Dropping the client connection on socket %d. "
3004 "The server connection has not been established yet.",
3006 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3009 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
3011 fwd = forward_url(csp, csp->http);
3012 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
3014 log_error(LOG_LEVEL_CONNECT,
3015 "Dropping the client connection on socket %d with "
3016 "server socket %d connected to %s. The forwarder has changed.",
3017 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
3018 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3022 log_applied_actions(csp->action);
3024 log_error(LOG_LEVEL_CONNECT,
3025 "Reusing server socket %d connected to %s. Requests already sent: %u.",
3026 csp->server_connection.sfd, csp->server_connection.host,
3027 csp->server_connection.requests_sent_total);
3029 if (send_https_request(csp))
3032 * Most likely the server connection timed out. We can't easily
3033 * create a new one so simply drop the client connection without a
3034 * error response to let the client retry.
3036 log_error(LOG_LEVEL_CONNECT,
3037 "Dropping client connection on socket %d. "
3038 "Forwarding the encrypted client request failed.",
3042 csp->server_connection.request_sent = time(NULL);
3043 csp->server_connection.requests_sent_total++;
3044 handle_established_connection(csp);
3045 freez(csp->receive_buffer);
3047 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3051 /*********************************************************************
3053 * Function : handle_established_connection
3055 * Description : Shuffle data between client and server once the
3056 * connection has been established and the request
3060 * 1 : csp = Current client state (buffers, headers, etc...)
3062 * Returns : Nothing.
3064 *********************************************************************/
3065 static void handle_established_connection(struct client_state *csp)
3071 struct pollfd poll_fds[2];
3075 struct timeval timeout;
3078 int ms_iis5_hack = 0;
3079 unsigned long long byte_count = 0;
3080 struct http_request *http;
3081 long len = 0; /* for buffer sizes (and negative error codes) */
3082 int buffer_and_filter_content = 0;
3083 unsigned int write_delay;
3084 #ifdef FEATURE_HTTPS_INSPECTION
3086 int use_ssl_tunnel = 0;
3087 csp->dont_verify_certificate = 0;
3089 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3091 /* Pass encrypted content without filtering. */
3096 /* Skeleton for HTTP response, if we should intercept the request */
3097 struct http_response *rsp;
3098 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3099 int watch_client_socket;
3102 csp->receive_buffer_size = csp->config->receive_buffer_size;
3103 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3104 if (csp->receive_buffer == NULL)
3106 log_error(LOG_LEVEL_ERROR,
3107 "Out of memory. Failed to allocate the receive buffer.");
3108 rsp = cgi_error_memory();
3109 send_crunch_response(csp, rsp);
3116 maxfd = (csp->cfd > csp->server_connection.sfd) ?
3117 csp->cfd : csp->server_connection.sfd;
3120 /* pass data between the client and server
3121 * until one or the other shuts down the connection.
3126 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3127 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3129 write_delay = get_write_delay(csp);
3133 #ifdef FEATURE_HTTPS_INSPECTION
3134 if (server_use_ssl(csp) && is_ssl_pending(&(csp->ssl_server_attr)))
3137 * It's possible that the TLS library already consumed all the
3138 * data the server intends to send. If that happens poll() and
3139 * select() will no longer see the data as available so we have
3140 * to skip the calls.
3142 goto server_wants_to_talk;
3144 if (watch_client_socket && client_use_ssl(csp) &&
3145 is_ssl_pending(&(csp->ssl_client_attr)))
3148 * The TLS libray may also consume all of the remaining data
3149 * from the client when we're shuffling the data from an
3150 * unbuffered request body to the server.
3152 goto client_wants_to_talk;
3157 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3158 if (!watch_client_socket)
3160 maxfd = csp->server_connection.sfd;
3163 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3165 FD_SET(csp->cfd, &rfds);
3168 FD_SET(csp->server_connection.sfd, &rfds);
3169 #endif /* ndef HAVE_POLL */
3171 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3172 if ((csp->flags & CSP_FLAG_CHUNKED)
3173 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3174 && ((csp->iob->eod - csp->iob->cur) >= 5)
3175 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3178 * XXX: This check should be obsolete now,
3179 * but let's wait a while to be sure.
3181 log_error(LOG_LEVEL_CONNECT,
3182 "Looks like we got the last chunk together with "
3183 "the server headers but didn't detect it earlier. "
3184 "We better stop reading.");
3185 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3186 csp->expected_content_length = byte_count;
3187 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3189 if (server_body && server_response_is_complete(csp, byte_count))
3191 if (csp->expected_content_length == byte_count)
3193 log_error(LOG_LEVEL_CONNECT,
3194 "Done reading from server. Content length: %llu as expected. "
3195 "Bytes most recently read: %ld.",
3200 log_error(LOG_LEVEL_CONNECT,
3201 "Done reading from server. Expected content length: %llu. "
3202 "Actual content length: %llu. Bytes most recently read: %ld.",
3203 csp->expected_content_length, byte_count, len);
3207 * XXX: Should not jump around, handle_established_connection()
3208 * is complicated enough already.
3212 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3215 poll_fds[0].fd = csp->cfd;
3216 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3217 if (!watch_client_socket)
3220 * Ignore incoming data, but still watch out
3221 * for disconnects etc. These flags are always
3222 * implied anyway but explicitly setting them
3225 poll_fds[0].events = POLLERR|POLLHUP;
3230 poll_fds[0].events = POLLIN;
3232 poll_fds[1].fd = csp->server_connection.sfd;
3233 poll_fds[1].events = POLLIN;
3234 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3236 timeout.tv_sec = csp->config->socket_timeout;
3237 timeout.tv_usec = 0;
3238 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3239 #endif /* def HAVE_POLL */
3241 /* Server or client not responding in timeout */
3244 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3245 csp->config->socket_timeout, http->url);
3246 if ((byte_count == 0) && (http->ssl == 0))
3248 send_crunch_response(csp, error_response(csp, "connection-timeout"));
3250 mark_server_socket_tainted(csp);
3251 #ifdef FEATURE_HTTPS_INSPECTION
3252 close_client_and_server_ssl_connections(csp);
3259 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3261 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3263 mark_server_socket_tainted(csp);
3264 #ifdef FEATURE_HTTPS_INSPECTION
3265 close_client_and_server_ssl_connections(csp);
3271 * This is the body of the browser's request,
3272 * just read and write it.
3274 * Receives data from browser and sends it to server
3276 * XXX: Make sure the client doesn't use pipelining
3277 * behind Privoxy's back.
3280 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3282 log_error(LOG_LEVEL_CONNECT,
3283 "The client socket %d has become unusable while "
3284 "the server socket %d is still open.",
3285 csp->cfd, csp->server_connection.sfd);
3286 mark_server_socket_tainted(csp);
3290 if (poll_fds[0].revents != 0)
3292 if (FD_ISSET(csp->cfd, &rfds))
3293 #endif /* def HAVE_POLL*/
3295 int max_bytes_to_read;
3297 #ifdef FEATURE_HTTPS_INSPECTION
3298 client_wants_to_talk:
3301 max_bytes_to_read = (int)csp->receive_buffer_size;
3303 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3304 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3306 if (data_is_available(csp->cfd, 0))
3309 * If the next request is already waiting, we have
3310 * to stop select()ing the client socket. Otherwise
3311 * we would always return right away and get nothing
3314 watch_client_socket = 0;
3315 log_error(LOG_LEVEL_CONNECT,
3316 "Stop watching client socket %d. "
3317 "There's already another request waiting.",
3322 * If the client socket is set, but there's no data
3323 * available on the socket, the client went fishing
3324 * and continuing talking to the server makes no sense.
3326 log_error(LOG_LEVEL_CONNECT,
3327 "The client closed socket %d while "
3328 "the server socket %d is still open.",
3329 csp->cfd, csp->server_connection.sfd);
3330 mark_server_socket_tainted(csp);
3333 if (csp->expected_client_content_length != 0)
3335 if (csp->expected_client_content_length < csp->receive_buffer_size)
3337 max_bytes_to_read = (int)csp->expected_client_content_length;
3339 log_error(LOG_LEVEL_CONNECT,
3340 "Waiting for up to %d bytes from the client.",
3343 assert(max_bytes_to_read <= csp->receive_buffer_size);
3344 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3346 #ifdef FEATURE_HTTPS_INSPECTION
3347 if (client_use_ssl(csp))
3349 if (csp->http->status == 101)
3351 len = ssl_recv_data(&(csp->ssl_client_attr),
3352 (unsigned char *)csp->receive_buffer,
3353 (size_t)max_bytes_to_read);
3356 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3357 "on client socket %d for an upgraded connection",
3363 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3364 "on client socket %d for an upgraded connection",
3368 byte_count += (unsigned long long)len;
3369 len = ssl_send_data(&(csp->ssl_server_attr),
3370 (unsigned char *)csp->receive_buffer, (size_t)len);
3373 log_error(LOG_LEVEL_ERROR, "Failed to send data "
3374 "on server socket %d for an upgraded connection",
3375 csp->server_connection.sfd);
3380 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3384 #endif /* def FEATURE_HTTPS_INSPECTION */
3386 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3390 /* XXX: not sure if this is necessary. */
3391 mark_server_socket_tainted(csp);
3392 break; /* "game over, man" */
3395 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3396 if (csp->expected_client_content_length != 0)
3398 assert(len <= max_bytes_to_read);
3399 csp->expected_client_content_length -= (unsigned)len;
3400 log_error(LOG_LEVEL_CONNECT,
3401 "Expected client content length set to %llu "
3402 "after reading %ld bytes.",
3403 csp->expected_client_content_length, len);
3404 if (csp->expected_client_content_length == 0)
3406 log_error(LOG_LEVEL_CONNECT,
3407 "Done reading from the client.");
3408 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3411 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3413 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3415 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3416 mark_server_socket_tainted(csp);
3424 * The server wants to talk. It could be the header or the body.
3425 * If `hdr' is null, then it's the header otherwise it's the body.
3426 * FIXME: Does `hdr' really mean `host'? No.
3429 if (poll_fds[1].revents != 0)
3431 if (FD_ISSET(csp->server_connection.sfd, &rfds))
3432 #endif /* HAVE_POLL */
3434 #ifdef FEATURE_HTTPS_INSPECTION
3435 server_wants_to_talk:
3437 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3439 * If we are buffering content, we don't want to eat up to
3440 * buffer-limit bytes if the client no longer cares about them.
3441 * If we aren't buffering, however, a dead client socket will be
3442 * noticed pretty much right away anyway, so we can reduce the
3443 * overhead by skipping the check.
3445 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3448 log_error(LOG_LEVEL_CONNECT,
3449 "The server still wants to talk, but the client may already have hung up on us.");
3451 log_error(LOG_LEVEL_CONNECT,
3452 "The server still wants to talk, but the client hung up on us.");
3453 mark_server_socket_tainted(csp);
3454 #ifdef FEATURE_HTTPS_INSPECTION
3455 close_client_and_server_ssl_connections(csp);
3458 #endif /* def _WIN32 */
3460 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3462 #ifdef FEATURE_HTTPS_INSPECTION
3464 * Reading data from standard or secured connection (HTTP/HTTPS)
3466 if (server_use_ssl(csp))
3468 len = ssl_recv_data(&(csp->ssl_server_attr),
3469 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3474 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3475 (int)csp->receive_buffer_size);
3480 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3482 if ((http->ssl && (csp->fwd == NULL))
3483 #ifdef FEATURE_HTTPS_INSPECTION
3489 * Just hang up. We already confirmed the client's CONNECT
3490 * request with status code 200 and unencrypted content is
3491 * no longer welcome.
3493 log_error(LOG_LEVEL_ERROR,
3494 "CONNECT already confirmed. Unable to tell the client about the problem.");
3497 else if (byte_count)
3500 * Just hang up. We already transmitted the original headers
3501 * and parts of the original content and therefore missed the
3502 * chance to send an error message (without risking data corruption).
3504 * XXX: we could retry with a fancy range request here.
3506 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3507 "Unable to tell the client about the problem.");
3508 mark_server_socket_tainted(csp);
3509 #ifdef FEATURE_HTTPS_INSPECTION
3510 close_client_and_server_ssl_connections(csp);
3515 * XXX: Consider handling the cases above the same.
3517 mark_server_socket_tainted(csp);
3521 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3522 if (csp->flags & CSP_FLAG_CHUNKED)
3524 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3526 /* XXX: this is a temporary hack */
3527 log_error(LOG_LEVEL_CONNECT,
3528 "Looks like we reached the end of the last chunk. "
3529 "We better stop reading.");
3530 csp->expected_content_length = byte_count + (unsigned long long)len;
3531 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3535 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3538 * This is guaranteed by allocating with zalloc_or_die()
3539 * and never (intentionally) writing to the last byte.
3541 * csp->receive_buffer_size is the size of the part of the
3542 * buffer we intentionally write to, but we actually
3543 * allocated csp->receive_buffer_size+1 bytes so the assertion
3544 * stays within the allocated range.
3546 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3549 * Add a trailing zero to let be able to use string operations.
3550 * XXX: do we still need this with filter_popups gone?
3552 assert(len <= csp->receive_buffer_size);
3553 csp->receive_buffer[len] = '\0';
3556 * Normally, this would indicate that we've read
3557 * as much as the server has sent us and we can
3558 * close the client connection. However, Microsoft
3559 * in its wisdom has released IIS/5 with a bug that
3560 * prevents it from sending the trailing \r\n in
3561 * a 302 redirect header (and possibly other headers).
3562 * To work around this if we've haven't parsed
3563 * a full header we'll append a trailing \r\n
3564 * and see if this now generates a valid one.
3566 * This hack shouldn't have any impacts. If we've
3567 * already transmitted the header or if this is a
3568 * SSL connection, then we won't bother with this
3569 * hack. So we only work on partially received
3570 * headers. If we append a \r\n and this still
3571 * doesn't generate a valid header, then we won't
3572 * transmit anything to the client.
3577 if (server_body || (http->ssl
3578 #ifdef FEATURE_HTTPS_INSPECTION
3584 * If we have been buffering up the document,
3585 * now is the time to apply content modification
3586 * and send the result to the client.
3588 if (buffer_and_filter_content)
3590 p = execute_content_filters(csp);
3592 * If content filtering fails, use the original
3593 * buffer and length.
3594 * (see p != NULL ? p : csp->iob->cur below)
3598 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3600 #ifdef FEATURE_COMPRESSION
3601 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3602 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3604 char *compressed_content = compress_buffer(p,
3605 (size_t *)&csp->content_length, csp->config->compression_level);
3606 if (compressed_content != NULL)
3609 p = compressed_content;
3610 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3615 if (JB_ERR_OK != update_server_headers(csp))
3617 log_error(LOG_LEVEL_FATAL,
3618 "Failed to update server headers. after filtering.");
3621 hdr = list_to_text(csp->headers);
3624 /* FIXME Should handle error properly */
3625 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3628 #ifdef FEATURE_HTTPS_INSPECTION
3630 * Sending data with standard or secured connection (HTTP/HTTPS)
3632 if (client_use_ssl(csp))
3634 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3635 (const unsigned char *)hdr, strlen(hdr),
3636 get_write_delay(csp)) < 0)
3637 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3638 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3639 csp->content_length, get_write_delay(csp)) < 0))
3641 log_error(LOG_LEVEL_ERROR,
3642 "Failed to send the modified content to the client over TLS");
3645 mark_server_socket_tainted(csp);
3646 close_client_and_server_ssl_connections(csp);
3651 #endif /* def FEATURE_HTTPS_INSPECTION */
3653 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3654 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3655 (size_t)csp->content_length, write_delay))
3657 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3660 mark_server_socket_tainted(csp);
3669 break; /* "game over, man" */
3673 * This is not the body, so let's pretend the server just sent
3676 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3677 len = (int)strlen(csp->receive_buffer);
3680 * Now, let the normal header parsing algorithm below do its
3681 * job. If it fails, we'll exit instead of continuing.
3688 * If we're in the body of the server document, just write it to
3689 * the client, unless we need to buffer the body for later
3690 * content-filtering.
3692 if (server_body || (http->ssl
3693 #ifdef FEATURE_HTTPS_INSPECTION
3698 if (buffer_and_filter_content)
3701 * If there is no memory left for buffering the content, or the buffer limit
3702 * has been reached, switch to non-filtering mode, i.e. make & write the
3703 * header, flush the iob and buf, and get out of the way.
3705 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3710 log_error(LOG_LEVEL_INFO,
3711 "Flushing header and buffers. Stepping back from filtering.");
3713 hdr = list_to_text(csp->headers);
3717 * Memory is too tight to even generate the header.
3718 * Send our static "Out-of-memory" page.
3720 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3721 rsp = cgi_error_memory();
3722 send_crunch_response(csp, rsp);
3723 mark_server_socket_tainted(csp);
3724 #ifdef FEATURE_HTTPS_INSPECTION
3725 close_client_and_server_ssl_connections(csp);
3729 hdrlen = strlen(hdr);
3731 #ifdef FEATURE_HTTPS_INSPECTION
3733 * Sending data with standard or secured connection (HTTP/HTTPS)
3735 if (client_use_ssl(csp))
3737 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3738 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3739 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3741 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3742 (const unsigned char *)csp->receive_buffer, (size_t)len,
3743 get_write_delay(csp)) < 0))
3745 log_error(LOG_LEVEL_CONNECT,
3746 "Flush header and buffers to client failed");
3748 mark_server_socket_tainted(csp);
3749 close_client_and_server_ssl_connections(csp);
3754 #endif /* def FEATURE_HTTPS_INSPECTION */
3756 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3757 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3758 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3761 log_error(LOG_LEVEL_CONNECT,
3762 "Flush header and buffers to client failed: %E");
3764 mark_server_socket_tainted(csp);
3770 * Reset the byte_count to the amount of bytes
3771 * we just flushed. len will be added a few lines below,
3772 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3774 byte_count = (unsigned long long)flushed;
3776 buffer_and_filter_content = 0;
3782 #ifdef FEATURE_HTTPS_INSPECTION
3784 * Sending data with standard or secured connection (HTTP/HTTPS)
3786 if (client_use_ssl(csp))
3788 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3789 (const unsigned char *)csp->receive_buffer, (size_t)len,
3790 get_write_delay(csp));
3793 log_error(LOG_LEVEL_ERROR,
3794 "Sending data to client failed");
3795 mark_server_socket_tainted(csp);
3796 close_client_and_server_ssl_connections(csp);
3801 #endif /* def FEATURE_HTTPS_INSPECTION */
3803 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3804 (size_t)len, write_delay))
3806 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3807 mark_server_socket_tainted(csp);
3812 byte_count += (unsigned long long)len;
3818 * We're still looking for the end of the server's header.
3819 * Buffer up the data we just read. If that fails, there's
3820 * little we can do but send our static out-of-memory page.
3822 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3824 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3825 rsp = cgi_error_memory();
3826 send_crunch_response(csp, rsp);
3827 mark_server_socket_tainted(csp);
3828 #ifdef FEATURE_HTTPS_INSPECTION
3829 close_client_and_server_ssl_connections(csp);
3834 /* Convert iob into something sed() can digest */
3835 if (JB_ERR_PARSE == get_server_headers(csp))
3840 * Well, we tried our MS IIS/5 hack and it didn't work.
3841 * The header is incomplete and there isn't anything
3842 * we can do about it.
3844 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3845 "Applying the MS IIS5 hack didn't help.");
3846 log_error(LOG_LEVEL_CLF,
3847 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3848 #ifdef FEATURE_HTTPS_INSPECTION
3850 * Sending data with standard or secured connection (HTTP/HTTPS)
3852 if (client_use_ssl(csp))
3854 ssl_send_data_delayed(&(csp->ssl_client_attr),
3855 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3856 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3859 #endif /* def FEATURE_HTTPS_INSPECTION */
3861 write_socket_delayed(csp->cfd,
3862 INVALID_SERVER_HEADERS_RESPONSE,
3863 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3865 mark_server_socket_tainted(csp);
3866 #ifdef FEATURE_HTTPS_INSPECTION
3867 close_client_and_server_ssl_connections(csp);
3874 * Since we have to wait for more from the server before
3875 * we can parse the headers we just continue here.
3877 log_error(LOG_LEVEL_CONNECT,
3878 "Continuing buffering server headers from socket %d. "
3879 "Bytes most recently read: %ld.", csp->cfd, len);
3886 * Account for the content bytes we
3887 * might have gotten with the headers.
3889 assert(csp->iob->eod >= csp->iob->cur);
3890 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3893 /* Did we actually get anything? */
3894 if (NULL == csp->headers->first)
3896 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3898 log_error(LOG_LEVEL_ERROR,
3899 "No server or forwarder response received on socket %d. "
3900 "Closing client socket %d without sending data.",
3901 csp->server_connection.sfd, csp->cfd);
3902 log_error(LOG_LEVEL_CLF,
3903 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3907 log_error(LOG_LEVEL_ERROR,
3908 "No server or forwarder response received on socket %d.",
3909 csp->server_connection.sfd);
3910 send_crunch_response(csp, error_response(csp, "no-server-data"));
3912 free_http_request(http);
3913 mark_server_socket_tainted(csp);
3914 #ifdef FEATURE_HTTPS_INSPECTION
3915 close_client_and_server_ssl_connections(csp);
3920 if (!csp->headers->first->str)
3922 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3924 assert(csp->headers->first->str);
3926 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3927 strncmpic(csp->headers->first->str, "ICY", 3))
3930 * It doesn't look like a HTTP (or Shoutcast) response:
3931 * tell the client and log the problem.
3933 if (strlen(csp->headers->first->str) > 30)
3935 csp->headers->first->str[30] = '\0';
3937 log_error(LOG_LEVEL_ERROR,
3938 "Invalid server or forwarder response. Starts with: %s",
3939 csp->headers->first->str);
3940 log_error(LOG_LEVEL_CLF,
3941 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3942 #ifdef FEATURE_HTTPS_INSPECTION
3944 * Sending data with standard or secured connection (HTTP/HTTPS)
3946 if (client_use_ssl(csp))
3948 ssl_send_data_delayed(&(csp->ssl_client_attr),
3949 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3950 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3951 get_write_delay(csp));
3954 #endif /* def FEATURE_HTTPS_INSPECTION */
3956 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3957 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3959 free_http_request(http);
3960 mark_server_socket_tainted(csp);
3961 #ifdef FEATURE_HTTPS_INSPECTION
3962 close_client_and_server_ssl_connections(csp);
3968 * Disable redirect checkers, so that they will be only run
3969 * again if the user also enables them through tags.
3971 * From a performance point of view it doesn't matter,
3972 * but it prevents duplicated log messages.
3974 #ifdef FEATURE_FAST_REDIRECTS
3975 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
3977 csp->action->flags &= ~ACTION_REDIRECT;
3980 * We have now received the entire server header,
3981 * filter it and send the result to the client
3983 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3985 log_error(LOG_LEVEL_CLF,
3986 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3987 #ifdef FEATURE_HTTPS_INSPECTION
3989 * Sending data with standard or secured connection (HTTP/HTTPS)
3991 if (client_use_ssl(csp))
3993 ssl_send_data_delayed(&(csp->ssl_client_attr),
3994 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3995 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3996 get_write_delay(csp));
4001 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4002 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4004 free_http_request(http);
4005 mark_server_socket_tainted(csp);
4006 #ifdef FEATURE_HTTPS_INSPECTION
4007 close_client_and_server_ssl_connections(csp);
4011 hdr = list_to_text(csp->headers);
4014 /* FIXME Should handle error properly */
4015 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
4018 if ((csp->flags & CSP_FLAG_CHUNKED)
4019 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4020 && ((csp->iob->eod - csp->iob->cur) >= 5)
4021 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
4023 log_error(LOG_LEVEL_CONNECT,
4024 "Looks like we got the last chunk together with "
4025 "the server headers. We better stop reading.");
4026 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
4027 csp->expected_content_length = byte_count;
4028 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
4031 csp->server_connection.response_received = time(NULL);
4033 if (crunch_response_triggered(csp, crunchers_light))
4036 * One of the tags created by a server-header
4037 * tagger triggered a crunch. We already
4038 * delivered the crunch response to the client
4039 * and are done here after cleaning up.
4042 mark_server_socket_tainted(csp);
4043 #ifdef FEATURE_HTTPS_INSPECTION
4044 close_client_and_server_ssl_connections(csp);
4049 /* Buffer and pcrs filter this if appropriate. */
4050 buffer_and_filter_content = content_requires_filtering(csp);
4052 if (!buffer_and_filter_content)
4055 * Write the server's (modified) header to
4056 * the client (along with anything else that
4057 * may be in the buffer). Use standard or secured
4060 #ifdef FEATURE_HTTPS_INSPECTION
4061 if (client_use_ssl(csp))
4063 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
4064 (const unsigned char *)hdr, strlen(hdr),
4065 get_write_delay(csp)) < 0)
4066 || ((len = ssl_flush_socket(&(csp->ssl_client_attr),
4069 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
4072 * The write failed, so don't bother mentioning it
4073 * to the client... it probably can't hear us anyway.
4076 mark_server_socket_tainted(csp);
4077 #ifdef FEATURE_HTTPS_INSPECTION
4078 close_client_and_server_ssl_connections(csp);
4084 #endif /* def FEATURE_HTTPS_INSPECTION */
4086 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
4087 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
4089 log_error(LOG_LEVEL_ERROR,
4090 "write header to client failed");
4092 * The write failed, so don't bother mentioning it
4093 * to the client... it probably can't hear us anyway.
4096 mark_server_socket_tainted(csp);
4102 /* we're finished with the server's header */
4108 * If this was a MS IIS/5 hack then it means the server
4109 * has already closed the connection. Nothing more to read.
4114 log_error(LOG_LEVEL_ERROR,
4115 "Closed server connection detected. "
4116 "Applying the MS IIS5 hack didn't help.");
4117 log_error(LOG_LEVEL_CLF,
4118 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4119 #ifdef FEATURE_HTTPS_INSPECTION
4121 * Sending data with standard or secured connection (HTTP/HTTPS)
4123 if (client_use_ssl(csp))
4125 ssl_send_data_delayed(&(csp->ssl_client_attr),
4126 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4127 strlen(INVALID_SERVER_HEADERS_RESPONSE),
4128 get_write_delay(csp));
4131 #endif /* def FEATURE_HTTPS_INSPECTION */
4133 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4134 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4136 mark_server_socket_tainted(csp);
4137 #ifdef FEATURE_HTTPS_INSPECTION
4138 close_client_and_server_ssl_connections(csp);
4145 mark_server_socket_tainted(csp);
4146 #ifdef FEATURE_HTTPS_INSPECTION
4147 close_client_and_server_ssl_connections(csp);
4149 return; /* huh? we should never get here */
4152 if (csp->content_length == 0)
4155 * If Privoxy didn't recalculate the Content-Length,
4156 * byte_count is still correct.
4158 csp->content_length = byte_count;
4161 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4162 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4163 && (csp->expected_content_length != byte_count))
4165 log_error(LOG_LEVEL_CONNECT,
4166 "Received %llu bytes while expecting %llu.",
4167 byte_count, csp->expected_content_length);
4168 mark_server_socket_tainted(csp);
4172 #ifdef FEATURE_HTTPS_INSPECTION
4173 if (client_use_ssl(csp))
4175 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4176 csp->ip_addr_str, http->gpc, http->hostport, http->path,
4177 http->version, csp->content_length);
4182 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4183 csp->ip_addr_str, http->ocmd, csp->content_length);
4185 csp->server_connection.timestamp = time(NULL);
4189 /*********************************************************************
4193 * Description : Once a connection from the client has been accepted,
4194 * this function is called (via serve()) to handle the
4195 * main business of the communication. This function
4196 * returns after dealing with a single request. It can
4197 * be called multiple times with the same client socket
4198 * if the client is keeping the connection alive.
4200 * The decision whether or not a client connection will
4201 * be kept alive is up to the caller which also must
4202 * close the client socket when done.
4204 * FIXME: chat is nearly thousand lines long.
4208 * 1 : csp = Current client state (buffers, headers, etc...)
4210 * Returns : Nothing.
4212 *********************************************************************/
4213 static void chat(struct client_state *csp)
4215 const struct forward_spec *fwd;
4216 struct http_request *http;
4217 /* Skeleton for HTTP response, if we should intercept the request */
4218 struct http_response *rsp;
4219 #ifdef FEATURE_HTTPS_INSPECTION
4220 int use_ssl_tunnel = 0;
4225 if (receive_client_request(csp) != JB_ERR_OK)
4230 #if defined(FEATURE_STATISTICS) && defined(MUTEX_LOCKS_AVAILABLE)
4231 privoxy_mutex_lock(&block_statistics_mutex);
4232 number_of_requests_received++;
4233 privoxy_mutex_unlock(&block_statistics_mutex);
4236 if (parse_client_request(csp) != JB_ERR_OK)
4241 #ifdef FEATURE_HTTPS_INSPECTION
4243 * Setting flags to use old solution with SSL tunnel and to disable
4244 * certificate verification.
4246 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4247 && !cgi_page_requested(csp->http->host))
4252 if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4254 csp->dont_verify_certificate = 1;
4259 * build the http request to send to the server
4260 * we have to do one of the following:
4262 * create = use the original HTTP request to create a new
4263 * HTTP request that has either the path component
4264 * without the http://domainspec (w/path) or the
4265 * full orininal URL (w/url)
4266 * Note that the path and/or the HTTP version may
4267 * have been altered by now.
4269 * SSL proxy = Open a socket to the host:port of the server
4270 * and create TLS/SSL connection with server and
4271 * with client. Then behave like mediator between
4272 * client and server over TLS/SSL.
4274 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4275 * with request to a parent proxy. Note that we'll be sending
4276 * forwarding the CFAIL message ourselves if connecting to the parent
4277 * fails, but we won't send a CSUCCEED message if it works,
4278 * since that would result in a double message (ours and the
4279 * parent's). After sending the request to the parent, we
4280 * must parse answer and send it to client. If connection
4281 * with server is established, we do TLS/SSL proxy. Otherwise
4282 * we send parent response to client and close connections.
4284 * here's the matrix:
4287 * +--------+--------+
4289 * 0 | create | SSL |
4290 * | w/path | proxy |
4291 * Forwarding +--------+--------+
4293 * 1 | create | proxy |
4294 * | w/url |+forward|
4295 * +--------+--------+
4299 #ifdef FEATURE_HTTPS_INSPECTION
4301 * Presetting SSL client and server flags
4303 if (http->ssl && !use_ssl_tunnel)
4305 http->client_ssl = 1;
4306 http->server_ssl = 1;
4310 http->client_ssl = 0;
4311 http->server_ssl = 0;
4315 #ifdef FEATURE_HTTPS_INSPECTION
4317 * Log the request unless we're https inspecting
4318 * in which case we don't have the path yet and
4319 * will log the request later.
4321 if (!client_use_ssl(csp))
4324 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4327 if (http->ssl && connect_port_is_forbidden(csp))
4329 const char *acceptable_connect_ports =
4330 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4331 assert(NULL != acceptable_connect_ports);
4332 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4333 "limit-connect{%s} doesn't allow CONNECT requests to %s",
4334 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4335 csp->action->flags |= ACTION_BLOCK;
4337 #ifdef FEATURE_HTTPS_INSPECTION
4338 http->client_ssl = 0;
4339 http->server_ssl = 0;
4344 * We have a request. Check if one of the crunchers wants it
4345 * unless the client wants to use TLS/SSL in which case we
4346 * haven't setup the TLS context yet and will send the crunch
4350 #ifdef FEATURE_HTTPS_INSPECTION
4351 !client_use_ssl(csp) &&
4353 crunch_response_triggered(csp, crunchers_all))
4356 * Yes. The client got the crunch response and we're done here.
4361 #ifdef FEATURE_HTTPS_INSPECTION
4362 if (client_use_ssl(csp) && !use_ssl_tunnel)
4366 * Creating a SSL proxy.
4368 * By sending the CSUCCEED message we're lying to the client as
4369 * the connection hasn't actually been established yet. We don't
4370 * establish the connection until we have seen and parsed the
4371 * encrypted client headers.
4373 if (write_socket_delayed(csp->cfd, CSUCCEED,
4374 strlen(CSUCCEED), get_write_delay(csp)) != 0)
4376 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4380 ret = create_client_ssl_connection(csp);
4383 log_error(LOG_LEVEL_ERROR,
4384 "Failed to open a secure connection with the client");
4387 if (JB_ERR_OK != process_encrypted_request_headers(csp))
4389 close_client_ssl_connection(csp);
4393 * We have an encrypted request. Check if one of the crunchers now
4394 * wants it (for example because the previously invisible path was
4395 * required to match).
4397 if (crunch_response_triggered(csp, crunchers_all))
4400 * Yes. The client got the crunch response and we're done here.
4407 log_applied_actions(csp->action);
4409 /* decide how to route the HTTP request */
4410 fwd = forward_url(csp, http);
4412 freez(csp->headers->first->str);
4413 build_request_line(csp, fwd, &csp->headers->first->str);
4415 if (fwd->forward_host)
4417 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4418 fwd->forward_host, fwd->forward_port, http->hostport);
4422 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4425 /* here we connect to the server, gateway, or the forwarder */
4427 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4428 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4429 && socket_is_still_alive(csp->server_connection.sfd)
4430 && connection_destination_matches(&csp->server_connection, http, fwd))
4432 log_error(LOG_LEVEL_CONNECT,
4433 "Reusing server socket %d connected to %s. Total requests: %u.",
4434 csp->server_connection.sfd, csp->server_connection.host,
4435 csp->server_connection.requests_sent_total);
4439 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4441 #ifdef FEATURE_CONNECTION_SHARING
4442 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4443 #ifdef FEATURE_HTTPS_INSPECTION
4444 && !server_use_ssl(csp)
4448 remember_connection(&csp->server_connection);
4451 #endif /* def FEATURE_CONNECTION_SHARING */
4453 log_error(LOG_LEVEL_CONNECT,
4454 "Closing server socket %d connected to %s. Total requests: %u.",
4455 csp->server_connection.sfd, csp->server_connection.host,
4456 csp->server_connection.requests_sent_total);
4457 close_socket(csp->server_connection.sfd);
4459 mark_connection_closed(&csp->server_connection);
4461 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4464 * Connecting to destination server
4466 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4468 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4470 if (fwd->type != SOCKS_NONE)
4473 rsp = error_response(csp, "forwarding-failed");
4475 else if (errno == EINVAL)
4477 rsp = error_response(csp, "no-such-domain");
4481 rsp = error_response(csp, "connect-failed");
4484 /* Write the answer to the client */
4487 send_crunch_response(csp, rsp);
4491 * Temporary workaround to prevent already-read client
4492 * bodies from being parsed as new requests. For now we
4493 * err on the safe side and throw all the following
4494 * requests under the bus, even if no client body has been
4495 * buffered. A compliant client will repeat the dropped
4496 * requests on an untainted connection.
4498 * The proper fix is to discard the no longer needed
4499 * client body in the buffer (if there is one) and to
4500 * continue parsing the bytes that follow.
4502 #ifdef FEATURE_HTTPS_INSPECTION
4503 close_client_ssl_connection(csp);
4505 drain_and_close_socket(csp->cfd);
4506 csp->cfd = JB_INVALID_SOCKET;
4511 #ifdef FEATURE_HTTPS_INSPECTION
4513 * Creating TLS/SSL connections with destination server or parent
4514 * proxy. If forwarding is enabled, we must send client request to
4515 * parent proxy and receive, parse and resend parent proxy answer.
4517 if (http->ssl && !use_ssl_tunnel)
4519 if (fwd->forward_host != NULL)
4521 char server_response[BUFFER_SIZE];
4524 char *hdr = list_to_text(csp->headers);
4525 memset(server_response, 0, sizeof(server_response));
4529 log_error(LOG_LEVEL_FATAL,
4530 "Out of memory parsing client header");
4532 list_remove_all(csp->headers);
4535 * Sending client's CONNECT request to the parent proxy
4537 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4543 log_error(LOG_LEVEL_CONNECT,
4544 "Sending request headers to: %s failed", http->hostport);
4545 mark_server_socket_tainted(csp);
4546 close_client_ssl_connection(csp);
4550 /* Waiting for parent proxy server response */
4551 len = read_socket(csp->server_connection.sfd, server_response,
4552 sizeof(server_response)-1);
4556 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4557 "server on socket %d.", csp->server_connection.sfd);
4559 rsp = error_response(csp, "no-server-data");
4562 send_crunch_response(csp, rsp);
4564 mark_server_socket_tainted(csp);
4565 close_client_ssl_connection(csp);
4570 * Test if the connection to the destination server was
4571 * established successfully by the parent proxy.
4573 if (!tunnel_established_successfully(server_response, (unsigned int)len))
4575 log_error(LOG_LEVEL_ERROR,
4576 "The forwarder %s failed to establish a connection with %s",
4577 fwd->forward_host, http->host);
4578 rsp = error_response(csp, "connect-failed");
4581 send_crunch_response(csp, rsp);
4583 mark_server_socket_tainted(csp);
4584 close_client_ssl_connection(csp);
4587 } /* -END- if (fwd->forward_host != NULL) */
4590 * We can now create the TLS/SSL connection with the destination server.
4592 int ret = create_server_ssl_connection(csp);
4595 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4596 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4599 * If the server certificate is invalid, we must inform
4600 * the client and then close connection to the client.
4602 ssl_send_certificate_error(csp);
4603 close_client_and_server_ssl_connections(csp);
4606 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4607 || csp->server_cert_verification_result == SSL_CERT_VALID)
4610 * The TLS/SSL connection wasn't created but an invalid
4611 * certificate wasn't detected. Report it as connection
4614 rsp = error_response(csp, "connect-failed");
4617 send_crunch_response(csp, rsp);
4619 close_client_and_server_ssl_connections(csp);
4623 }/* -END- if (http->ssl) */
4624 #endif /* def FEATURE_HTTPS_INSPECTION */
4626 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4627 save_connection_destination(csp->server_connection.sfd,
4628 http, fwd, &csp->server_connection);
4629 csp->server_connection.keep_alive_timeout =
4630 (unsigned)csp->config->keep_alive_timeout;
4632 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4634 csp->server_connection.requests_sent_total++;
4636 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4638 /* Client headers have been sent optimistically */
4639 assert(csp->headers->last == NULL);
4641 else if (http->ssl == 0 || (fwd->forward_host
4642 #ifdef FEATURE_HTTPS_INSPECTION
4647 if (send_http_request(csp))
4649 rsp = error_response(csp, "connect-failed");
4652 send_crunch_response(csp, rsp);
4660 * Using old solution with SSL tunnel or new solution with SSL proxy
4662 list_remove_all(csp->headers);
4663 #ifdef FEATURE_HTTPS_INSPECTION
4668 * We're running an SSL tunnel and we're not forwarding,
4669 * so just ditch the client headers, send the "connect succeeded"
4670 * message to the client, flush the rest, and get out of the way.
4672 if (write_socket_delayed(csp->cfd, CSUCCEED,
4673 strlen(CSUCCEED), get_write_delay(csp)))
4678 #ifdef FEATURE_HTTPS_INSPECTION
4682 * If server certificate has been verified and is invalid,
4683 * we must inform the client and then close the connection
4684 * with client and server.
4686 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4687 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4689 ssl_send_certificate_error(csp);
4690 close_client_and_server_ssl_connections(csp);
4693 if (send_https_request(csp))
4695 rsp = error_response(csp, "connect-failed");
4698 send_crunch_response(csp, rsp);
4700 close_client_and_server_ssl_connections(csp);
4704 #endif /* def FEATURE_HTTPS_INSPECTION */
4705 clear_iob(csp->client_iob);
4706 }/* -END- else ... if (http->ssl == 1) */
4708 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4710 /* XXX: should the time start earlier for optimistically sent data? */
4711 csp->server_connection.request_sent = time(NULL);
4713 handle_established_connection(csp);
4714 freez(csp->receive_buffer);
4719 /*********************************************************************
4721 * Function : fuzz_server_response
4723 * Description : Treat the input as a whole server response.
4726 * 1 : csp = Current client state (buffers, headers, etc...)
4727 * 2 : fuzz_input_file = File to read the input from.
4731 *********************************************************************/
4732 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4734 static struct forward_spec fwd; /* Zero'd due to being static */
4737 if (strcmp(fuzz_input_file, "-") == 0)
4739 /* XXX: Doesn't work yet. */
4740 csp->server_connection.sfd = 0;
4744 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4745 if (csp->server_connection.sfd == -1)
4747 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4752 csp->content_type |= CT_GIF;
4753 csp->action->flags |= ACTION_DEANIMATE;
4754 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4756 csp->http->path = strdup_or_die("/");
4757 csp->http->host = strdup_or_die("fuzz.example.org");
4758 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4759 /* Prevent client socket monitoring */
4760 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4761 csp->flags |= CSP_FLAG_CHUNKED;
4763 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4764 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4766 csp->content_type |= CT_DECLARED|CT_GIF;
4768 csp->config->socket_timeout = 0;
4770 cgi_init_error_messages();
4772 handle_established_connection(csp);
4773 freez(csp->receive_buffer);
4780 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4781 /*********************************************************************
4783 * Function : prepare_csp_for_next_request
4785 * Description : Put the csp in a mostly vergin state.
4788 * 1 : csp = Current client state (buffers, headers, etc...)
4792 *********************************************************************/
4793 static void prepare_csp_for_next_request(struct client_state *csp)
4795 csp->content_type = 0;
4796 csp->content_length = 0;
4797 csp->expected_content_length = 0;
4798 csp->expected_client_content_length = 0;
4799 list_remove_all(csp->headers);
4800 clear_iob(csp->iob);
4801 freez(csp->error_message);
4802 free_http_request(csp->http);
4803 destroy_list(csp->headers);
4804 #ifdef FEATURE_HTTPS_INSPECTION
4805 destroy_list(csp->https_headers);
4807 destroy_list(csp->tags);
4808 #ifdef FEATURE_CLIENT_TAGS
4809 destroy_list(csp->client_tags);
4810 freez(csp->client_address);
4812 free_current_action(csp->action);
4813 if (NULL != csp->fwd)
4815 unload_forward_spec(csp->fwd);
4818 /* XXX: Store per-connection flags someplace else. */
4819 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4820 #ifdef FEATURE_TOGGLE
4821 if (global_toggle_state)
4822 #endif /* def FEATURE_TOGGLE */
4824 csp->flags |= CSP_FLAG_TOGGLED_ON;
4827 if (csp->client_iob->eod > csp->client_iob->cur)
4829 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4830 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4832 assert(bytes_to_shift > 0);
4833 assert(data_length > 0);
4835 log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4836 data_length, bytes_to_shift);
4837 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4838 csp->client_iob->cur = csp->client_iob->buf;
4839 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4840 csp->client_iob->eod = csp->client_iob->buf + data_length;
4841 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4843 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4848 * We mainly care about resetting client_iob->cur so we don't
4849 * waste buffer space at the beginning and don't mess up the
4850 * request restoration done by cgi_show_request().
4852 * Freeing the buffer itself isn't technically necessary,
4853 * but makes debugging more convenient.
4855 clear_iob(csp->client_iob);
4858 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4861 /*********************************************************************
4865 * Description : This is little more than chat. We only "serve" to
4866 * to close (or remember) any socket that chat may have
4870 * 1 : csp = Current client state (buffers, headers, etc...)
4874 *********************************************************************/
4875 static void serve(struct client_state *csp)
4877 int config_file_change_detected = 0; /* Only used for debugging */
4878 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4879 #ifdef FEATURE_CONNECTION_SHARING
4880 static int monitor_thread_running = 0;
4881 #endif /* def FEATURE_CONNECTION_SHARING */
4882 int continue_chatting = 0;
4884 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4885 csp->ip_addr_str, csp->cfd);
4889 unsigned int latency;
4891 #ifdef FEATURE_HTTPS_INSPECTION
4892 if (continue_chatting && client_use_ssl(csp))
4894 continue_https_chat(csp);
4903 * If the request has been crunched,
4904 * the calculated latency is zero.
4906 latency = (unsigned)(csp->server_connection.response_received -
4907 csp->server_connection.request_sent) / 2;
4909 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4910 && (csp->flags & CSP_FLAG_CRUNCHED)
4911 && (csp->expected_client_content_length != 0))
4913 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4914 log_error(LOG_LEVEL_CONNECT,
4915 "Tainting client socket %d due to unread data.", csp->cfd);
4918 continue_chatting = (csp->config->feature_flags
4919 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4920 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4921 && (csp->cfd != JB_INVALID_SOCKET)
4922 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4923 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4924 || (csp->flags & CSP_FLAG_CHUNKED));
4926 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4927 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4929 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4931 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4933 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4934 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4935 || !socket_is_still_alive(csp->server_connection.sfd)
4936 || !(latency < csp->server_connection.keep_alive_timeout))
4938 log_error(LOG_LEVEL_CONNECT,
4939 "Closing server socket %d connected to %s. "
4940 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4941 csp->server_connection.sfd, (csp->server_connection.host != NULL) ?
4942 csp->server_connection.host : csp->http->host,
4943 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4944 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4945 socket_is_still_alive(csp->server_connection.sfd),
4946 csp->server_connection.keep_alive_timeout);
4947 #ifdef FEATURE_CONNECTION_SHARING
4948 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4950 forget_connection(csp->server_connection.sfd);
4952 #endif /* def FEATURE_CONNECTION_SHARING */
4953 #ifdef FEATURE_HTTPS_INSPECTION
4954 close_server_ssl_connection(csp);
4956 close_socket(csp->server_connection.sfd);
4957 mark_connection_closed(&csp->server_connection);
4958 #ifdef FEATURE_HTTPS_INSPECTION
4959 if (continue_chatting && client_use_ssl(csp))
4962 * Close the client socket as well as Privoxy currently
4963 * can't establish a new server connection when the client
4964 * socket is reused and would drop the connection in
4965 * continue_https_chat() anyway.
4967 continue_chatting = 0;
4968 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4969 log_error(LOG_LEVEL_CONNECT,
4970 "Client socket %d is no longer usable. "
4971 "The server socket has been closed.", csp->cfd);
4977 if (continue_chatting && any_loaded_file_changed(csp))
4979 continue_chatting = 0;
4980 config_file_change_detected = 1;
4982 #ifdef FEATURE_HTTPS_INSPECTION
4983 if (continue_chatting && client_use_ssl(csp) &&
4984 csp->ssl_with_client_is_opened == 0)
4986 continue_chatting = 0;
4987 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4988 "The TLS session has been terminated.", csp->cfd);
4992 if (continue_chatting)
4994 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
4995 && socket_is_still_alive(csp->cfd))
4997 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
4998 "pipelined on socket %d and the socket is still alive.",
4999 csp->requests_received_total+1, csp->cfd);
5000 prepare_csp_for_next_request(csp);
5004 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
5006 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5008 log_error(LOG_LEVEL_CONNECT,
5009 "Waiting for the next client request on socket %d. "
5010 "Keeping the server socket %d to %s open.",
5011 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
5015 log_error(LOG_LEVEL_CONNECT,
5016 "Waiting for the next client request on socket %d. "
5017 "No server socket to keep open.", csp->cfd);
5021 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
5022 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
5023 && socket_is_still_alive(csp->cfd))
5025 log_error(LOG_LEVEL_CONNECT,
5026 "Data arrived in time on client socket %d. Requests so far: %u",
5027 csp->cfd, csp->requests_received_total);
5028 prepare_csp_for_next_request(csp);
5032 #ifdef FEATURE_CONNECTION_SHARING
5033 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5034 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
5035 && (socket_is_still_alive(csp->server_connection.sfd))
5036 #ifdef FEATURE_HTTPS_INSPECTION
5037 && !server_use_ssl(csp)
5041 time_t time_open = time(NULL) - csp->server_connection.timestamp;
5043 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
5048 remember_connection(&csp->server_connection);
5049 csp->server_connection.sfd = JB_INVALID_SOCKET;
5050 drain_and_close_socket(csp->cfd);
5051 csp->cfd = JB_INVALID_SOCKET;
5052 privoxy_mutex_lock(&connection_reuse_mutex);
5053 if (!monitor_thread_running)
5055 monitor_thread_running = 1;
5056 privoxy_mutex_unlock(&connection_reuse_mutex);
5057 wait_for_alive_connections();
5058 privoxy_mutex_lock(&connection_reuse_mutex);
5059 monitor_thread_running = 0;
5061 privoxy_mutex_unlock(&connection_reuse_mutex);
5063 #endif /* def FEATURE_CONNECTION_SHARING */
5067 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5069 log_error(LOG_LEVEL_CONNECT,
5070 "Closing server socket %d connected to %s. Keep-alive: %u. "
5071 "Tainted: %u. Socket alive: %u. Timeout: %u. "
5072 "Configuration file change detected: %u",
5073 csp->server_connection.sfd, csp->server_connection.host,
5074 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
5075 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
5076 socket_is_still_alive(csp->server_connection.sfd),
5077 csp->server_connection.keep_alive_timeout,
5078 config_file_change_detected);
5080 } while (continue_chatting);
5084 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
5086 if (csp->cfd != JB_INVALID_SOCKET)
5088 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
5089 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
5090 "Configuration file change detected: %u. Requests received: %u.",
5091 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
5092 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
5093 config_file_change_detected, csp->requests_received_total);
5094 #ifdef FEATURE_HTTPS_INSPECTION
5095 close_client_ssl_connection(csp);
5097 drain_and_close_socket(csp->cfd);
5100 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5102 #ifdef FEATURE_CONNECTION_SHARING
5103 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5105 forget_connection(csp->server_connection.sfd);
5107 #endif /* def FEATURE_CONNECTION_SHARING */
5109 #ifdef FEATURE_HTTPS_INSPECTION
5110 close_server_ssl_connection(csp);
5111 #endif /* def FEATURE_HTTPS_INSPECTION */
5113 close_socket(csp->server_connection.sfd);
5116 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
5117 mark_connection_closed(&csp->server_connection);
5120 free_csp_resources(csp);
5122 csp->flags &= ~CSP_FLAG_ACTIVE;
5128 /*********************************************************************
5130 * Function : server_thread
5132 * Description : We only exist to call `serve' in a threaded environment.
5135 * 1 : data = Current client state (buffers, headers, etc...)
5137 * Returns : Always 0.
5139 *********************************************************************/
5140 static int32 server_thread(void *data)
5142 serve((struct client_state *) data);
5149 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5150 /*********************************************************************
5154 * Description : Print usage info & exit.
5156 * Parameters : Pointer to argv[0] for identifying ourselves
5160 *********************************************************************/
5161 static void usage(const char *name)
5163 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
5164 "Usage: %s [--config-test] "
5167 #endif /* defined(unix) */
5170 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
5171 #endif /* defined(unix) */
5172 "[--version] [configfile]\n",
5176 show_fuzz_usage(name);
5179 printf("Aborting\n");
5184 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5187 #ifdef MUTEX_LOCKS_AVAILABLE
5188 /*********************************************************************
5190 * Function : privoxy_mutex_lock
5192 * Description : Locks a mutex.
5195 * 1 : mutex = The mutex to lock.
5197 * Returns : Void. May exit in case of errors.
5199 *********************************************************************/
5200 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5202 #ifdef FEATURE_PTHREAD
5203 int err = pthread_mutex_lock(mutex);
5206 if (mutex != &log_mutex)
5208 log_error(LOG_LEVEL_FATAL,
5209 "Mutex locking failed: %s.\n", strerror(err));
5214 EnterCriticalSection(mutex);
5215 #endif /* def FEATURE_PTHREAD */
5219 /*********************************************************************
5221 * Function : privoxy_mutex_unlock
5223 * Description : Unlocks a mutex.
5226 * 1 : mutex = The mutex to unlock.
5228 * Returns : Void. May exit in case of errors.
5230 *********************************************************************/
5231 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5233 #ifdef FEATURE_PTHREAD
5234 int err = pthread_mutex_unlock(mutex);
5237 if (mutex != &log_mutex)
5239 log_error(LOG_LEVEL_FATAL,
5240 "Mutex unlocking failed: %s.\n", strerror(err));
5245 LeaveCriticalSection(mutex);
5246 #endif /* def FEATURE_PTHREAD */
5250 /*********************************************************************
5252 * Function : privoxy_mutex_init
5254 * Description : Prepares a mutex.
5257 * 1 : mutex = The mutex to initialize.
5259 * Returns : Void. May exit in case of errors.
5261 *********************************************************************/
5262 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5264 #ifdef FEATURE_PTHREAD
5265 int err = pthread_mutex_init(mutex, 0);
5268 printf("Fatal error. Mutex initialization failed: %s.\n",
5273 InitializeCriticalSection(mutex);
5274 #endif /* def FEATURE_PTHREAD */
5276 #endif /* def MUTEX_LOCKS_AVAILABLE */
5278 /*********************************************************************
5280 * Function : initialize_mutexes
5282 * Description : Prepares mutexes if mutex support is available.
5286 * Returns : Void, exits in case of errors.
5288 *********************************************************************/
5289 static void initialize_mutexes(void)
5291 #ifdef MUTEX_LOCKS_AVAILABLE
5293 * Prepare global mutex semaphores
5296 #ifdef FEATURE_HTTPS_INSPECTION
5297 privoxy_mutex_init(&certificate_mutex);
5298 privoxy_mutex_init(&ssl_init_mutex);
5301 privoxy_mutex_init(&log_mutex);
5302 privoxy_mutex_init(&log_init_mutex);
5303 privoxy_mutex_init(&connection_reuse_mutex);
5304 #ifdef FEATURE_EXTERNAL_FILTERS
5305 privoxy_mutex_init(&external_filter_mutex);
5307 #ifdef FEATURE_CLIENT_TAGS
5308 privoxy_mutex_init(&client_tags_mutex);
5310 #ifdef FEATURE_STATISTICS
5311 privoxy_mutex_init(&block_statistics_mutex);
5313 #ifdef FEATURE_EXTENDED_STATISTICS
5314 privoxy_mutex_init(&filter_statistics_mutex);
5315 privoxy_mutex_init(&block_reason_statistics_mutex);
5319 * XXX: The assumptions below are a bit naive
5320 * and can cause locks that aren't necessary.
5322 * For example older FreeBSD versions (< 6.x?)
5323 * have no gethostbyname_r, but gethostbyname is
5326 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5327 privoxy_mutex_init(&resolver_mutex);
5328 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5330 * XXX: should we use a single mutex for
5331 * localtime() and gmtime() as well?
5333 #ifndef HAVE_GMTIME_R
5334 privoxy_mutex_init(&gmtime_mutex);
5335 #endif /* ndef HAVE_GMTIME_R */
5337 #ifndef HAVE_LOCALTIME_R
5338 privoxy_mutex_init(&localtime_mutex);
5339 #endif /* ndef HAVE_GMTIME_R */
5341 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5342 privoxy_mutex_init(&rand_mutex);
5343 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5345 #endif /* def MUTEX_LOCKS_AVAILABLE */
5348 /*********************************************************************
5352 * Description : Load the config file and start the listen loop.
5353 * This function is a lot more *sane* with the `load_config'
5354 * and `listen_loop' functions; although it stills does
5355 * a *little* too much for my taste.
5358 * 1 : argc = Number of parameters (including $0).
5359 * 2 : argv = Array of (char *)'s to the parameters.
5361 * Returns : 1 if : can't open config file, unrecognized directive,
5362 * stats requested in multi-thread mode, can't open the
5363 * log file, can't open the jar file, listen port is invalid,
5364 * any load fails, and can't bind port.
5366 * Else main never returns, the process must be signaled
5367 * to terminate execution. Or, on Windows, use the
5368 * "File", "Exit" menu option.
5370 *********************************************************************/
5372 int real_main(int argc, char **argv)
5374 int main(int argc, char **argv)
5378 int do_config_test = 0;
5379 #ifndef HAVE_ARC4RANDOM
5380 unsigned int random_seed;
5383 struct passwd *pw = NULL;
5384 struct group *grp = NULL;
5386 char *pre_chroot_nslookup_to_load_resolver = NULL;
5389 char *fuzz_input_type = NULL;
5390 char *fuzz_input_file = NULL;
5397 #if !defined(_WIN32)
5404 /* Prepare mutexes if supported and necessary. */
5405 initialize_mutexes();
5407 /* Enable logging until further notice. */
5411 * Parse the command line arguments
5413 * XXX: simply printing usage information in case of
5414 * invalid arguments isn't particularly user friendly.
5416 while (++argc_pos < argc)
5419 /* Check to see if the service must be installed or uninstalled */
5420 if (strncmp(argv[argc_pos], "--install", 9) == 0)
5422 const char *pName = argv[argc_pos] + 9;
5425 exit((install_service(pName)) ? 0 : 1);
5427 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5429 const char *pName = argv[argc_pos] + 11;
5432 exit((uninstall_service(pName)) ? 0 : 1);
5434 else if (strcmp(argv[argc_pos], "--service") == 0)
5436 bRunAsService = TRUE;
5437 w32_set_service_cwd();
5438 atexit(w32_service_exit_notify);
5441 #endif /* defined(_WIN32) */
5444 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5446 if (strcmp(argv[argc_pos], "--help") == 0)
5451 else if (strcmp(argv[argc_pos], "--version") == 0)
5453 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5459 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5461 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5465 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5467 if (++argc_pos == argc) usage(argv[0]);
5468 pidfile = strdup_or_die(argv[argc_pos]);
5471 else if (strcmp(argv[argc_pos], "--user") == 0)
5476 if (++argc_pos == argc) usage(argv[argc_pos]);
5478 user_arg = strdup_or_die(argv[argc_pos]);
5479 group_name = strchr(user_arg, '.');
5480 if (NULL != group_name)
5482 /* Nul-terminate the user name */
5485 /* Skip the former delimiter to actually reach the group name */
5488 grp = getgrnam(group_name);
5491 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5494 pw = getpwnam(user_arg);
5497 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5503 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5505 if (++argc_pos == argc) usage(argv[0]);
5506 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5509 else if (strcmp(argv[argc_pos], "--chroot") == 0)
5513 #endif /* defined(unix) */
5515 else if (strcmp(argv[argc_pos], "--config-test") == 0)
5520 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5523 if (argc < argc_pos + 2) usage(argv[0]);
5524 fuzz_input_type = argv[argc_pos];
5526 fuzz_input_file = argv[argc_pos];
5528 else if (strcmp(argv[argc_pos], "--stfu") == 0)
5530 set_debug_level(LOG_LEVEL_STFU);
5533 else if (argc_pos + 1 != argc)
5536 * This is neither the last command line
5537 * option, nor was it recognized before,
5538 * therefore it must be invalid.
5544 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5546 configfile = argv[argc_pos];
5549 } /* -END- while (more arguments) */
5551 show_version(Argv[0]);
5554 if (*configfile != '/')
5556 char cwd[BUFFER_SIZE];
5558 size_t abs_file_size;
5560 /* make config-filename absolute here */
5561 if (NULL == getcwd(cwd, sizeof(cwd)))
5563 perror("failed to get current working directory");
5567 basedir = strdup_or_die(cwd);
5569 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5570 abs_file = malloc_or_die(abs_file_size);
5571 strlcpy(abs_file, basedir, abs_file_size);
5572 strlcat(abs_file, "/", abs_file_size);
5573 strlcat(abs_file, configfile, abs_file_size);
5574 configfile = abs_file;
5576 #endif /* defined unix */
5580 clients->next = NULL;
5582 /* XXX: factor out initialising after the next stable release. */
5587 #ifndef HAVE_ARC4RANDOM
5588 random_seed = (unsigned int)time(NULL);
5590 srandom(random_seed);
5593 #endif /* ifdef HAVE_RANDOM */
5594 #endif /* ifndef HAVE_ARC4RANDOM */
5597 * Unix signal handling
5599 * Catch the abort, interrupt and terminate signals for a graceful exit
5600 * Catch the hangup signal so the errlog can be reopened.
5602 * Ignore the broken pipe signal as connection failures
5603 * are handled when and where they occur without relying
5606 #if !defined(_WIN32)
5609 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5611 for (idx = 0; idx < SZ(catched_signals); idx++)
5613 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5614 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5616 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5617 #endif /* ifdef sun */
5619 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5623 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5625 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5629 #else /* ifdef _WIN32 */
5630 # ifdef _WIN_CONSOLE
5632 * We *are* in a windows console app.
5633 * Print a verbose messages about FAQ's and such
5635 printf("%s", win32_blurb);
5636 # endif /* def _WIN_CONSOLE */
5637 #endif /* def _WIN32 */
5640 if (fuzz_input_type != NULL)
5642 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5644 log_error(LOG_LEVEL_FATAL,
5645 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5646 "Various data structures are static which is unsafe when using threads.");
5651 exit(NULL == load_config());
5654 /* Initialize the CGI subsystem */
5655 cgi_init_error_messages();
5658 * If running on unix and without the --no-daemon
5659 * option, become a daemon. I.e. fork, detach
5660 * from tty and get process group leadership
5669 if (pid < 0) /* error */
5674 else if (pid != 0) /* parent */
5679 * must check for errors
5680 * child died due to missing files aso
5683 wpid = waitpid(pid, &status, WNOHANG);
5695 * stderr (fd 2) will be closed later on,
5696 * when the config file has been parsed.
5702 * Reserve fd 0 and 1 to prevent abort() and friends
5703 * from sending stuff to the clients or servers.
5705 fd = open("/dev/null", O_RDONLY);
5708 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5712 if (dup2(fd, 0) == -1)
5714 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5718 fd = open("/dev/null", O_WRONLY);
5721 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5725 if (dup2(fd, 1) == -1)
5727 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5732 #ifdef FEATURE_EXTERNAL_FILTERS
5733 for (fd = 0; fd < 3; fd++)
5735 mark_socket_for_close_on_execute(fd);
5739 if (chdir("/") != 0)
5741 log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5744 } /* -END- if (daemon_mode) */
5747 * As soon as we have written the PID file, we can switch
5748 * to the user and group ID indicated by the --user option
5750 if (pidfile != NULL)
5752 write_pid_file(pidfile);
5756 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5758 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5762 if (setgroups(1, &grp->gr_gid))
5764 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5767 else if (initgroups(pw->pw_name, pw->pw_gid))
5769 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5775 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5777 /* Read the time zone file from /etc before doing chroot. */
5779 if (NULL != pre_chroot_nslookup_to_load_resolver
5780 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5782 /* Initialize resolver library. */
5783 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5785 if (chroot(pw->pw_dir) < 0)
5787 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5791 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5794 if (setuid(pw->pw_uid))
5796 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5800 char putenv_dummy[64];
5802 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5803 if (putenv(putenv_dummy) != 0)
5805 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5808 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5809 if (putenv(putenv_dummy) != 0)
5811 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5817 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5820 #endif /* defined unix */
5823 /* This will be FALSE unless the command line specified --service
5827 /* Yup, so now we must attempt to establish a connection
5828 * with the service dispatcher. This will only work if this
5829 * process was launched by the service control manager to
5830 * actually run as a service. If this isn't the case, i've
5831 * known it take around 30 seconds or so for the call to return.
5834 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5835 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5837 /* Service has run, and at this point is now being stopped, so just return */
5842 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5844 /* An error occurred. Usually it's because --service was wrongly specified
5845 * and we were unable to connect to the Service Control Dispatcher because
5846 * it wasn't expecting us and is therefore not listening.
5848 * For now, just continue below to call the listen_loop function.
5851 #endif /* def _WIN32 */
5861 /*********************************************************************
5863 * Function : bind_port_helper
5865 * Description : Bind the listen port. Handles logging, and aborts
5869 * 1 : haddr = Host address to bind to. Use NULL to bind to
5871 * 2 : hport = Specifies port to bind to.
5872 * 3 : backlog = Listen backlog.
5874 * Returns : Port that was opened.
5876 *********************************************************************/
5877 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5882 result = bind_port(haddr, hport, backlog, &bfd);
5886 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5890 log_error(LOG_LEVEL_FATAL,
5891 "can't bind to %s:%d: There may be another Privoxy "
5892 "or some other proxy running on port %d",
5893 bind_address, hport, hport);
5897 log_error(LOG_LEVEL_FATAL,
5898 "can't bind to %s:%d: The hostname is not resolvable",
5899 bind_address, hport);
5903 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5904 bind_address, hport);
5908 /* shouldn't get here */
5909 return JB_INVALID_SOCKET;
5914 if (bfd >= FD_SETSIZE)
5916 log_error(LOG_LEVEL_FATAL,
5917 "Bind socket number too high to use select(): %d >= %d",
5925 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5930 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5938 /*********************************************************************
5940 * Function : bind_ports_helper
5942 * Description : Bind the listen ports. Handles logging, and aborts
5946 * 1 : config = Privoxy configuration. Specifies ports
5948 * 2 : sockets = Preallocated array of opened sockets
5949 * corresponding to specification in config.
5950 * All non-opened sockets will be set to
5951 * JB_INVALID_SOCKET.
5953 * Returns : Nothing. Inspect sockets argument.
5955 *********************************************************************/
5956 static void bind_ports_helper(struct configuration_spec * config,
5957 jb_socket sockets[])
5961 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5963 if (config->hport[i])
5965 sockets[i] = bind_port_helper(config->haddr[i],
5966 config->hport[i], config->listen_backlog);
5967 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5968 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5970 struct accept_filter_arg af_options;
5971 bzero(&af_options, sizeof(af_options));
5972 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5973 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5974 sizeof(af_options)))
5976 log_error(LOG_LEVEL_ERROR,
5977 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5984 sockets[i] = JB_INVALID_SOCKET;
5987 config->need_bind = 0;
5991 /*********************************************************************
5993 * Function : close_ports_helper
5995 * Description : Close listenings ports.
5998 * 1 : sockets = Array of opened and non-opened sockets to
5999 * close. All sockets will be set to
6000 * JB_INVALID_SOCKET.
6002 * Returns : Nothing.
6004 *********************************************************************/
6005 static void close_ports_helper(jb_socket sockets[])
6009 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
6011 if (JB_INVALID_SOCKET != sockets[i])
6013 close_socket(sockets[i]);
6015 sockets[i] = JB_INVALID_SOCKET;
6021 /* Without this simple workaround we get this compiler warning from _beginthread
6022 * warning C4028: formal parameter 1 different from declaration
6024 void w32_service_listen_loop(void *p)
6028 #endif /* def _WIN32 */
6031 /*********************************************************************
6033 * Function : listen_loop
6035 * Description : bind the listen port and enter a "FOREVER" listening loop.
6041 *********************************************************************/
6042 static void listen_loop(void)
6044 struct client_states *csp_list = NULL;
6045 struct client_state *csp = NULL;
6046 jb_socket bfds[MAX_LISTENING_SOCKETS];
6047 struct configuration_spec *config;
6048 unsigned int active_threads = 0;
6049 #if defined(FEATURE_PTHREAD)
6050 pthread_attr_t attrs;
6052 pthread_attr_init(&attrs);
6053 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
6056 config = load_config();
6058 #ifdef FEATURE_CONNECTION_SHARING
6060 * XXX: Should be relocated once it no
6061 * longer needs to emit log messages.
6063 initialize_reusable_connections();
6064 #endif /* def FEATURE_CONNECTION_SHARING */
6066 bind_ports_helper(config, bfds);
6068 #ifdef FEATURE_GRACEFUL_TERMINATION
6069 while (!g_terminate)
6074 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
6075 while (waitpid(-1, NULL, WNOHANG) > 0)
6077 /* zombie children */
6079 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
6082 * Free data that was used by died threads
6084 active_threads = sweep();
6088 * Re-open the errlog after HUP signal
6090 if (received_hup_signal)
6092 if (NULL != config->logfile)
6094 init_error_log(Argv[0], config->logfile);
6096 received_hup_signal = 0;
6100 csp_list = zalloc_or_die(sizeof(*csp_list));
6101 csp = &csp_list->csp;
6103 log_error(LOG_LEVEL_CONNECT,
6104 "Waiting for the next client connection. Currently active threads: %u",
6108 * This config may be outdated, but for accept_connection()
6109 * it's fresh enough.
6111 csp->config = config;
6113 if (!accept_connection(csp, bfds))
6115 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
6120 csp->flags |= CSP_FLAG_ACTIVE;
6121 csp->server_connection.sfd = JB_INVALID_SOCKET;
6123 csp->config = config = load_config();
6125 if (config->need_bind)
6128 * Since we were listening to the "old port", we will not see
6129 * a "listen" param change until the next request. So, at
6130 * least 1 more request must be made for us to find the new
6131 * setting. I am simply closing the old socket and binding the
6134 * Which-ever is correct, we will serve 1 more page via the
6135 * old settings. This should probably be a "show-status"
6136 * request. This should not be a so common of an operation
6137 * that this will hurt people's feelings.
6140 close_ports_helper(bfds);
6142 bind_ports_helper(config, bfds);
6145 #ifdef FEATURE_TOGGLE
6146 if (global_toggle_state)
6147 #endif /* def FEATURE_TOGGLE */
6149 csp->flags |= CSP_FLAG_TOGGLED_ON;
6152 if (run_loader(csp))
6154 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
6155 /* Never get here - LOG_LEVEL_FATAL causes program exit */
6159 if (block_acl(NULL,csp))
6161 log_error(LOG_LEVEL_CONNECT,
6162 "Connection from %s on %s (socket %d) dropped due to ACL",
6163 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
6164 close_socket(csp->cfd);
6165 freez(csp->ip_addr_str);
6166 freez(csp->listen_addr_str);
6170 #endif /* def FEATURE_ACL */
6172 if ((0 != config->max_client_connections)
6173 && (active_threads >= config->max_client_connections))
6175 log_error(LOG_LEVEL_ERROR,
6176 "Rejecting connection from %s. Maximum number of connections reached.",
6178 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6179 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6180 close_socket(csp->cfd);
6181 freez(csp->ip_addr_str);
6182 freez(csp->listen_addr_str);
6187 /* add it to the list of clients */
6188 csp_list->next = clients->next;
6189 clients->next = csp_list;
6191 if (config->multi_threaded)
6195 /* this is a switch () statement in the C preprocessor - ugh */
6196 #undef SELECTED_ONE_OPTION
6198 /* Use Pthreads in preference to native code */
6199 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6200 #define SELECTED_ONE_OPTION
6202 pthread_t the_thread;
6205 ret = pthread_create(&the_thread, &attrs,
6206 (void * (*)(void *))serve, csp);
6207 child_id = ret ? -1 : 0;
6211 #if defined(_WIN32) && !defined(SELECTED_ONE_OPTION)
6212 #define SELECTED_ONE_OPTION
6213 child_id = _beginthread(
6214 (void (*)(void *))serve,
6219 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6220 #define SELECTED_ONE_OPTION
6222 thread_id tid = spawn_thread
6223 (server_thread, "server", B_NORMAL_PRIORITY, csp);
6225 if ((tid >= 0) && (resume_thread(tid) == B_OK))
6227 child_id = (int) tid;
6236 #if !defined(SELECTED_ONE_OPTION)
6239 /* This block is only needed when using fork().
6240 * When using threads, the server thread was
6241 * created and run by the call to _beginthread().
6243 if (child_id == 0) /* child */
6246 #ifdef FEATURE_TOGGLE
6247 int inherited_toggle_state = global_toggle_state;
6248 #endif /* def FEATURE_TOGGLE */
6253 * If we've been toggled or we've blocked the request, tell Mom
6256 #ifdef FEATURE_TOGGLE
6257 if (inherited_toggle_state != global_toggle_state)
6259 rc |= RC_FLAG_TOGGLED;
6261 #endif /* def FEATURE_TOGGLE */
6263 #ifdef FEATURE_STATISTICS
6264 if (csp->flags & CSP_FLAG_REJECTED)
6266 rc |= RC_FLAG_BLOCKED;
6268 #endif /* ndef FEATURE_STATISTICS */
6272 else if (child_id > 0) /* parent */
6274 /* in a fork()'d environment, the parent's
6275 * copy of the client socket and the CSP
6279 #if !defined(_WIN32) && !defined(__CYGWIN__)
6281 wait(&child_status);
6284 * Evaluate child's return code: If the child has
6285 * - been toggled, toggle ourselves
6286 * - blocked its request, bump up the stats counter
6289 #ifdef FEATURE_TOGGLE
6290 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6292 global_toggle_state = !global_toggle_state;
6294 #endif /* def FEATURE_TOGGLE */
6296 #ifdef FEATURE_STATISTICS
6298 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6302 #endif /* def FEATURE_STATISTICS */
6304 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6305 close_socket(csp->cfd);
6306 csp->flags &= ~CSP_FLAG_ACTIVE;
6310 #undef SELECTED_ONE_OPTION
6311 /* end of cpp switch () */
6316 * Spawning the child failed, assume it's because
6317 * there are too many children running already.
6318 * XXX: If you assume ...
6320 log_error(LOG_LEVEL_ERROR,
6321 "Unable to take any additional connections: %E. Active threads: %u",
6323 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6324 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6325 close_socket(csp->cfd);
6326 csp->flags &= ~CSP_FLAG_ACTIVE;
6335 #if defined(FEATURE_PTHREAD)
6336 pthread_attr_destroy(&attrs);
6339 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6341 #ifdef FEATURE_GRACEFUL_TERMINATION
6343 log_error(LOG_LEVEL_INFO, "Graceful termination requested.");
6345 close_ports_helper(bfds);
6347 unload_current_config_file();
6348 unload_current_actions_file();
6349 unload_current_re_filterfile();
6350 #ifdef FEATURE_TRUST
6351 unload_current_trust_file();
6354 if (config->multi_threaded)
6361 } while ((clients->next != NULL) && (--i > 0));
6365 log_error(LOG_LEVEL_ERROR, "Graceful termination failed "
6366 "- still some live clients after 1 minute wait.");
6376 #ifdef FEATURE_HTTPS_INSPECTION
6378 * Only release TLS backed resources if there
6379 * are no active connections left.
6381 if (clients->next == NULL)
6387 log_error(LOG_LEVEL_INFO, "Exiting gracefully.");
6389 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6390 /* Cleanup - remove taskbar icon etc. */
6395 #endif /* FEATURE_GRACEFUL_TERMINATION */