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 CLIENT_BODY_BUFFER_ERROR_RESPONSE[] =
292 "HTTP/1.1 400 Failed reading client body\r\n"
293 "Content-Type: text/plain\r\n"
294 "Connection: close\r\n\r\n"
295 "Failed to buffer the client body to apply content filters.\n"
296 "Could be caused by a socket timeout\n";
298 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
299 "HTTP/1.1 417 Expecting too much\r\n"
300 "Content-Type: text/plain\r\n"
301 "Connection: close\r\n\r\n"
302 "Privoxy detected an unsupported Expect header value.\n";
304 /* A function to crunch a response */
305 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
307 /* Crunch function flags */
308 #define CF_NO_FLAGS 0
309 /* Cruncher applies to forced requests as well */
310 #define CF_IGNORE_FORCE 1
311 /* Crunched requests are counted for the block statistics */
312 #define CF_COUNT_AS_REJECT 2
314 /* A crunch function and its flags */
317 const crunch_func_ptr cruncher;
321 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
323 /* Complete list of cruncher functions */
324 static const struct cruncher crunchers_all[] = {
325 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
326 { block_url, CF_COUNT_AS_REJECT },
328 { trust_url, CF_COUNT_AS_REJECT },
329 #endif /* def FEATURE_TRUST */
330 { redirect_url, CF_NO_FLAGS },
331 { dispatch_cgi, CF_IGNORE_FORCE},
335 /* Light version, used after tags are applied */
336 static const struct cruncher crunchers_light[] = {
337 { block_url, CF_COUNT_AS_REJECT },
338 { redirect_url, CF_NO_FLAGS },
344 * XXX: Don't we really mean
351 /*********************************************************************
353 * Function : sig_handler
355 * Description : Signal handler for different signals.
356 * Exit gracefully on TERM and INT
357 * or set a flag that will cause the errlog
358 * to be reopened by the main thread on HUP.
361 * 1 : the_signal = the signal cause this function to call
365 *********************************************************************/
366 static void sig_handler(int the_signal)
372 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
384 received_hup_signal = 1;
390 * We shouldn't be here, unless we catch signals
391 * in main() that we can't handle here!
393 log_error(LOG_LEVEL_FATAL,
394 "sig_handler: exiting on unexpected signal %d", the_signal);
402 /*********************************************************************
404 * Function : get_write_delay
406 * Description : Parse the delay-response parameter.
409 * 1 : csp = Current client state (buffers, headers, etc...)
411 * Returns : Number of milliseconds to delay writes.
413 *********************************************************************/
414 static unsigned int get_write_delay(const struct client_state *csp)
420 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
424 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
426 delay = (unsigned)strtol(newval, &endptr, 0);
429 log_error(LOG_LEVEL_FATAL,
430 "Invalid delay-response{} parameter: '%s'", newval);
438 /*********************************************************************
440 * Function : client_protocol_is_unsupported
442 * Description : Checks if the client used a known unsupported
443 * protocol and deals with it by sending an error
447 * 1 : csp = Current client state (buffers, headers, etc...)
448 * 2 : req = the first request line send by the client
450 * Returns : TRUE if an error response has been generated, or
451 * FALSE if the request doesn't look invalid.
453 *********************************************************************/
454 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
457 * If it's a FTP or gopher request, we don't support it.
459 * These checks are better than nothing, but they might
460 * not work in all configurations and some clients might
461 * have problems digesting the answer.
463 * They should, however, never cause more problems than
464 * Privoxy's old behaviour (returning the misleading HTML
467 * "Could not resolve http://(ftp|gopher)://example.org").
469 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
471 const char *response = NULL;
472 const char *protocol = NULL;
474 if (!strncmpic(req, "GET ftp://", 10))
476 response = FTP_RESPONSE;
481 response = GOPHER_RESPONSE;
484 log_error(LOG_LEVEL_ERROR,
485 "%s tried to use Privoxy as %s proxy: %s",
486 csp->ip_addr_str, protocol, req);
487 log_error(LOG_LEVEL_CLF,
488 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
491 #ifdef FEATURE_HTTPS_INSPECTION
492 if (client_use_ssl(csp))
494 ssl_send_data_delayed(&(csp->ssl_client_attr),
495 (const unsigned char *)response, strlen(response),
496 get_write_delay(csp));
501 write_socket_delayed(csp->cfd, response, strlen(response),
502 get_write_delay(csp));
512 /*********************************************************************
514 * Function : client_has_unsupported_expectations
516 * Description : Checks if the client used an unsupported expectation
517 * in which case an error message is delivered.
520 * 1 : csp = Current client state (buffers, headers, etc...)
522 * Returns : TRUE if an error response has been generated, or
523 * FALSE if the request doesn't look invalid.
525 *********************************************************************/
526 static int client_has_unsupported_expectations(const struct client_state *csp)
528 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
530 log_error(LOG_LEVEL_ERROR,
531 "Rejecting request from client %s with unsupported Expect header value",
533 log_error(LOG_LEVEL_CLF,
534 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
535 write_socket_delayed(csp->cfd,
536 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
537 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
538 get_write_delay(csp));
548 /*********************************************************************
550 * Function : get_request_destination_elsewhere
552 * Description : If the client's request was redirected into
553 * Privoxy without the client's knowledge,
554 * the request line lacks the destination host.
556 * This function tries to get it elsewhere,
557 * provided accept-intercepted-requests is enabled.
559 * "Elsewhere" currently only means "Host: header",
560 * but in the future we may ask the redirecting
561 * packet filter to look the destination up.
563 * If the destination stays unknown, an error
564 * response is send to the client and headers
565 * are freed so that chat() can return directly.
568 * 1 : csp = Current client state (buffers, headers, etc...)
569 * 2 : headers = a header list
571 * Returns : JB_ERR_OK if the destination is now known, or
572 * JB_ERR_PARSE if it isn't.
574 *********************************************************************/
575 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
577 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
579 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
580 " Privoxy isn't configured to accept intercepted requests.",
581 csp->ip_addr_str, csp->http->cmd);
582 /* XXX: Use correct size */
583 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
584 csp->ip_addr_str, csp->http->cmd);
586 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
587 get_write_delay(csp));
588 destroy_list(headers);
592 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
594 /* Split the domain we just got for pattern matching */
595 init_domain_components(csp->http);
601 /* We can't work without destination. Go spread the news.*/
603 /* XXX: Use correct size */
604 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
605 csp->ip_addr_str, csp->http->cmd);
606 log_error(LOG_LEVEL_ERROR,
607 "Privoxy was unable to get the destination for %s's request: %s",
608 csp->ip_addr_str, csp->http->cmd);
610 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
611 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
612 destroy_list(headers);
617 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
618 * to get the destination IP address, use it as host directly
619 * or do a reverse DNS lookup first.
624 /*********************************************************************
626 * Function : get_server_headers
628 * Description : Parses server headers in iob and fills them
629 * into csp->headers so that they can later be
633 * 1 : csp = Current client state (buffers, headers, etc...)
635 * Returns : JB_ERR_OK if everything went fine, or
636 * JB_ERR_PARSE if the headers were incomplete.
638 *********************************************************************/
639 static jb_err get_server_headers(struct client_state *csp)
641 int continue_hack_in_da_house = 0;
644 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
649 * continue hack in da house. Ignore the ending of
650 * this head and continue enlisting header lines.
651 * The reason is described below.
653 enlist(csp->headers, "");
654 continue_hack_in_da_house = 0;
657 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
660 * It's a bodyless continue response, don't
661 * stop header parsing after reaching its end.
663 * As a result Privoxy will concatenate the
664 * next response's head and parse and deliver
665 * the headers as if they belonged to one request.
667 * The client will separate them because of the
668 * empty line between them.
670 * XXX: What we're doing here is clearly against
671 * the intended purpose of the continue header,
672 * and under some conditions (HTTP/1.0 client request)
673 * it's a standard violation.
675 * Anyway, "sort of against the spec" is preferable
676 * to "always getting confused by Continue responses"
677 * (Privoxy's behaviour before this hack was added)
679 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
680 continue_hack_in_da_house = 1;
682 else if (*header == '\0')
685 * If the header is empty, but the Continue hack
686 * isn't active, we can assume that we reached the
687 * end of the buffer before we hit the end of the
690 * Inform the caller an let it decide how to handle it.
695 if (JB_ERR_MEMORY == enlist(csp->headers, header))
698 * XXX: Should we quit the request and return a
699 * out of memory error page instead?
701 log_error(LOG_LEVEL_ERROR,
702 "Out of memory while enlisting server headers. %s lost.",
712 /*********************************************************************
714 * Function : crunch_reason
716 * Description : Translates the crunch reason code into a string.
719 * 1 : rsp = a http_response
721 * Returns : A string with the crunch reason or an error description.
723 *********************************************************************/
724 static const char *crunch_reason(const struct http_response *rsp)
726 char * reason = NULL;
731 return "Internal error while searching for crunch reason";
734 switch (rsp->crunch_reason)
737 reason = "Unsupported HTTP feature";
743 reason = "Untrusted";
746 reason = "Redirected";
752 reason = "DNS failure";
754 case FORWARDING_FAILED:
755 reason = "Forwarding failed";
758 reason = "Connection failure";
761 reason = "Out of memory (may mask other reasons)";
763 case CONNECTION_TIMEOUT:
764 reason = "Connection timeout";
767 reason = "No server data received";
770 reason = "No reason recorded";
778 /*********************************************************************
780 * Function : log_applied_actions
782 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
786 * 1 : actions = Current action spec to log
790 *********************************************************************/
791 static void log_applied_actions(const struct current_action_spec *actions)
794 * The conversion to text requires lots of memory allocations so
795 * we only do the conversion if the user is actually interested.
797 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
799 char *actions_as_text = actions_to_line_of_text(actions);
800 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
801 freez(actions_as_text);
806 /*********************************************************************
808 * Function : send_crunch_response
810 * Description : Delivers already prepared response for
811 * intercepted requests, logs the interception
812 * and frees the response.
815 * 1 : csp = Current client state (buffers, headers, etc...)
816 * 2 : rsp = Fully prepared response. Will be freed on exit.
820 *********************************************************************/
821 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
823 const struct http_request *http = csp->http;
827 assert(rsp->head != NULL);
831 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
835 * Extract the status code from the actual head
836 * that will be send to the client. It is the only
837 * way to get it right for all requests, including
838 * the fixed ones for out-of-memory problems.
840 * A head starts like this: 'HTTP/1.1 200...'
844 status_code[0] = rsp->head[9];
845 status_code[1] = rsp->head[10];
846 status_code[2] = rsp->head[11];
847 status_code[3] = '\0';
849 /* Log that the request was crunched and why. */
850 log_applied_actions(csp->action);
851 #ifdef FEATURE_HTTPS_INSPECTION
852 if (client_use_ssl(csp))
854 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
855 http->hostport, http->path);
856 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
857 csp->ip_addr_str, http->gpc, http->hostport, http->path,
858 http->version, status_code, rsp->content_length);
863 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
864 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
865 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
867 /* Write the answer to the client */
868 #ifdef FEATURE_HTTPS_INSPECTION
869 if (client_use_ssl(csp))
871 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
872 (const unsigned char *)rsp->head, rsp->head_length,
873 get_write_delay(csp)) < 0)
874 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
875 (const unsigned char *)rsp->body, rsp->content_length,
876 get_write_delay(csp)) < 0))
878 /* There is nothing we can do about it. */
879 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
880 "for https://%s%s through client socket %d using TLS/SSL",
881 http->hostport, http->url, csp->cfd);
887 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
888 get_write_delay(csp))
889 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
890 get_write_delay(csp)))
892 /* There is nothing we can do about it. */
893 log_error(LOG_LEVEL_CONNECT,
894 "Couldn't deliver the error message for %s through client socket %d: %E",
895 http->url, csp->cfd);
899 /* Clean up and return */
900 if (cgi_error_memory() != rsp)
902 free_http_response(rsp);
908 /*********************************************************************
910 * Function : crunch_response_triggered
912 * Description : Checks if the request has to be crunched,
913 * and delivers the crunch response if necessary.
916 * 1 : csp = Current client state (buffers, headers, etc...)
917 * 2 : crunchers = list of cruncher functions to run
919 * Returns : TRUE if the request was answered with a crunch response
922 *********************************************************************/
923 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
925 struct http_response *rsp = NULL;
926 const struct cruncher *c;
929 * If CGI request crunching is disabled,
930 * check the CGI dispatcher out of order to
931 * prevent unintentional blocks or redirects.
933 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
934 && (NULL != (rsp = dispatch_cgi(csp))))
936 /* Deliver, log and free the interception response. */
937 send_crunch_response(csp, rsp);
938 csp->flags |= CSP_FLAG_CRUNCHED;
942 for (c = crunchers; c->cruncher != NULL; c++)
945 * Check the cruncher if either Privoxy is toggled
946 * on and the request isn't forced, or if the cruncher
947 * applies to forced requests as well.
949 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
950 !(csp->flags & CSP_FLAG_FORCED)) ||
951 (c->flags & CF_IGNORE_FORCE))
953 rsp = c->cruncher(csp);
956 /* Deliver, log and free the interception response. */
957 send_crunch_response(csp, rsp);
958 csp->flags |= CSP_FLAG_CRUNCHED;
959 #ifdef FEATURE_STATISTICS
960 if (c->flags & CF_COUNT_AS_REJECT)
962 #ifdef MUTEX_LOCKS_AVAILABLE
963 privoxy_mutex_lock(&block_statistics_mutex);
964 number_of_requests_blocked++;
965 privoxy_mutex_unlock(&block_statistics_mutex);
967 csp->flags |= CSP_FLAG_REJECTED;
969 #endif /* def FEATURE_STATISTICS */
980 /*********************************************************************
982 * Function : build_request_line
984 * Description : Builds the HTTP request line.
986 * If a HTTP forwarder is used it expects the whole URL,
987 * web servers only get the path.
990 * 1 : csp = Current client state (buffers, headers, etc...)
991 * 2 : fwd = The forwarding spec used for the request.
993 * 3 : request_line = The old request line which will be replaced.
995 * Returns : Nothing. Terminates in case of memory problems.
997 *********************************************************************/
998 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
1000 struct http_request *http = csp->http;
1003 * Downgrade http version from 1.1 to 1.0
1004 * if +downgrade action applies.
1006 if ((csp->action->flags & ACTION_DOWNGRADE)
1007 && (!strcmpic(http->version, "HTTP/1.1")))
1009 freez(http->version);
1010 http->version = strdup_or_die("HTTP/1.0");
1014 * Rebuild the request line.
1016 freez(*request_line);
1017 #ifdef FEATURE_HTTPS_INSPECTION
1018 if (fwd != NULL && fwd->forward_host &&
1019 fwd->type != FORWARD_WEBSERVER && client_use_ssl(csp))
1021 *request_line = strdup("CONNECT ");
1026 *request_line = strdup(http->gpc);
1027 string_append(request_line, " ");
1030 if (fwd != NULL && fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1032 #ifdef FEATURE_HTTPS_INSPECTION
1033 if (client_use_ssl(csp))
1035 char port_string[10];
1037 string_append(request_line, http->host);
1038 snprintf(port_string, sizeof(port_string), ":%d", http->port);
1039 string_append(request_line, port_string);
1044 string_append(request_line, http->url);
1049 string_append(request_line, http->path);
1051 string_append(request_line, " ");
1052 string_append(request_line, http->version);
1054 if (*request_line == NULL)
1056 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1058 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1062 /*********************************************************************
1064 * Function : change_request_destination
1066 * Description : Parse a (rewritten) request line and regenerate
1067 * the http request data.
1070 * 1 : csp = Current client state (buffers, headers, etc...)
1072 * Returns : Forwards the parse_http_request() return code.
1073 * Terminates in case of memory problems.
1075 *********************************************************************/
1076 static jb_err change_request_destination(struct client_state *csp)
1078 struct http_request *http = csp->http;
1081 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1082 csp->headers->first->str);
1083 free_http_request(http);
1084 err = parse_http_request(csp->headers->first->str, http);
1085 if (JB_ERR_OK != err)
1087 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1088 jb_err_to_string(err));
1090 if (http->ssl && strcmpic(csp->http->gpc, "CONNECT"))
1093 * A client header filter changed the request URL from
1094 * http:// to https:// which we currently don't support.
1096 log_error(LOG_LEVEL_ERROR, "Changing the request destination from http "
1097 "to https behind the client's back currently isn't supported.");
1098 return JB_ERR_PARSE;
1105 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1106 /*********************************************************************
1108 * Function : server_response_is_complete
1110 * Description : Determines whether we should stop reading
1111 * from the server socket.
1114 * 1 : csp = Current client state (buffers, headers, etc...)
1115 * 2 : content_length = Length of content received so far.
1117 * Returns : TRUE if the response is complete,
1120 *********************************************************************/
1121 static int server_response_is_complete(struct client_state *csp,
1122 unsigned long long content_length)
1124 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1126 if (!strcmpic(csp->http->gpc, "HEAD"))
1129 * "HEAD" implies no body, we are thus expecting
1130 * no content. XXX: incomplete "list" of methods?
1132 csp->expected_content_length = 0;
1133 content_length_known = TRUE;
1134 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1137 if (csp->http->status == 204 || csp->http->status == 304)
1140 * Expect no body. XXX: incomplete "list" of status codes?
1142 csp->expected_content_length = 0;
1143 content_length_known = TRUE;
1144 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1147 return (content_length_known && ((0 == csp->expected_content_length)
1148 || (csp->expected_content_length <= content_length)));
1152 #ifdef FEATURE_CONNECTION_SHARING
1153 /*********************************************************************
1155 * Function : wait_for_alive_connections
1157 * Description : Waits for alive connections to timeout.
1163 *********************************************************************/
1164 static void wait_for_alive_connections(void)
1166 int connections_alive = close_unusable_connections();
1168 while (0 < connections_alive)
1170 log_error(LOG_LEVEL_CONNECT,
1171 "Waiting for %d connections to timeout.",
1174 connections_alive = close_unusable_connections();
1177 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1180 #endif /* def FEATURE_CONNECTION_SHARING */
1183 /*********************************************************************
1185 * Function : save_connection_destination
1187 * Description : Remembers a connection for reuse later on.
1190 * 1 : sfd = Open socket to remember.
1191 * 2 : http = The destination for the connection.
1192 * 3 : fwd = The forwarder settings used.
1193 * 4 : server_connection = storage.
1197 *********************************************************************/
1198 static void save_connection_destination(jb_socket sfd,
1199 const struct http_request *http,
1200 const struct forward_spec *fwd,
1201 struct reusable_connection *server_connection)
1203 assert(sfd != JB_INVALID_SOCKET);
1204 assert(NULL != http->host);
1206 server_connection->sfd = sfd;
1207 server_connection->host = strdup_or_die(http->host);
1208 server_connection->port = http->port;
1210 assert(NULL != fwd);
1211 assert(server_connection->gateway_host == NULL);
1212 assert(server_connection->gateway_port == 0);
1213 assert(server_connection->forwarder_type == 0);
1214 assert(server_connection->forward_host == NULL);
1215 assert(server_connection->forward_port == 0);
1217 server_connection->forwarder_type = fwd->type;
1218 if (NULL != fwd->gateway_host)
1220 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1224 server_connection->gateway_host = NULL;
1226 server_connection->gateway_port = fwd->gateway_port;
1227 if (NULL != fwd->auth_username)
1229 server_connection->auth_username = strdup_or_die(fwd->auth_username);
1233 server_connection->auth_username = NULL;
1235 if (NULL != fwd->auth_password)
1237 server_connection->auth_password = strdup_or_die(fwd->auth_password);
1241 server_connection->auth_password = NULL;
1244 if (NULL != fwd->forward_host)
1246 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1250 server_connection->forward_host = NULL;
1252 server_connection->forward_port = fwd->forward_port;
1254 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1257 /*********************************************************************
1259 * Function : verify_request_length
1261 * Description : Checks if we already got the whole client requests
1262 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1265 * Data that doesn't belong to the current request is
1266 * either thrown away to let the client retry on a clean
1267 * socket, or stashed to be dealt with after the current
1268 * request is served.
1271 * 1 : csp = Current client state (buffers, headers, etc...)
1275 *********************************************************************/
1276 static void verify_request_length(struct client_state *csp)
1278 unsigned long long buffered_request_bytes =
1279 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1281 if ((csp->expected_client_content_length != 0)
1282 && (buffered_request_bytes != 0))
1284 if (csp->expected_client_content_length >= buffered_request_bytes)
1286 csp->expected_client_content_length -= buffered_request_bytes;
1287 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1288 "to account for the %llu ones we already got.",
1289 csp->expected_client_content_length, buffered_request_bytes);
1293 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1294 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1295 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1296 "Marking the server socket tainted after throwing %llu bytes away.",
1297 buffered_request_bytes - csp->expected_client_content_length);
1298 csp->expected_client_content_length = 0;
1299 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1302 if (csp->expected_client_content_length == 0)
1304 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1308 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1309 && ((csp->client_iob->cur < csp->client_iob->eod)
1310 || (csp->expected_client_content_length != 0)))
1312 if (strcmpic(csp->http->gpc, "GET")
1313 && strcmpic(csp->http->gpc, "HEAD")
1314 && strcmpic(csp->http->gpc, "TRACE")
1315 && strcmpic(csp->http->gpc, "OPTIONS")
1316 && strcmpic(csp->http->gpc, "DELETE"))
1318 /* XXX: this is an incomplete hack */
1319 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1320 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1324 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1326 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1328 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1329 log_error(LOG_LEVEL_CONNECT,
1330 "Possible pipeline attempt detected. The connection will not "
1331 "be kept alive and we will only serve the first request.");
1332 /* Nuke the pipelined requests from orbit, just to be sure. */
1333 clear_iob(csp->client_iob);
1338 * Keep the pipelined data around for now, we'll deal with
1339 * it once we're done serving the current request.
1341 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1342 assert(csp->client_iob->eod >= csp->client_iob->cur);
1343 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1344 "%d bytes of pipelined data received.",
1345 (int)(csp->client_iob->eod - csp->client_iob->cur));
1351 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1352 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1357 /*********************************************************************
1359 * Function : mark_server_socket_tainted
1361 * Description : Makes sure we don't reuse a server socket
1362 * (if we didn't read everything the server sent
1363 * us reusing the socket would lead to garbage).
1366 * 1 : csp = Current client state (buffers, headers, etc...)
1370 *********************************************************************/
1371 static void mark_server_socket_tainted(struct client_state *csp)
1374 * For consistency we always mark the server socket
1375 * tainted, however, to reduce the log noise we only
1376 * emit a log message if the server socket could have
1377 * actually been reused.
1379 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1380 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1382 log_error(LOG_LEVEL_CONNECT,
1383 "Marking the server socket %d tainted.",
1384 csp->server_connection.sfd);
1386 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1389 /*********************************************************************
1391 * Function : get_request_line
1393 * Description : Read the client request line.
1396 * 1 : csp = Current client state (buffers, headers, etc...)
1398 * Returns : Pointer to request line or NULL in case of errors.
1400 *********************************************************************/
1401 static char *get_request_line(struct client_state *csp)
1403 char buf[BUFFER_SIZE];
1404 char *request_line = NULL;
1407 memset(buf, 0, sizeof(buf));
1409 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1412 * If there are multiple pipelined requests waiting,
1413 * the flag will be set again once the next request
1416 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1418 request_line = get_header(csp->client_iob);
1419 if ((NULL != request_line) && ('\0' != *request_line))
1421 return request_line;
1425 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1426 "received yet. Continuing reading from %d.", csp->cfd);
1434 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1436 !data_is_available(csp->cfd, csp->config->socket_timeout)
1439 if (socket_is_still_alive(csp->cfd))
1441 log_error(LOG_LEVEL_CONNECT,
1442 "No request line on socket %d received in time. Timeout: %d.",
1443 csp->cfd, csp->config->socket_timeout);
1444 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1445 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1446 get_write_delay(csp));
1450 log_error(LOG_LEVEL_CONNECT,
1451 "The client side of the connection on socket %d got "
1452 "closed without sending a complete request line.", csp->cfd);
1457 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1459 if (len <= 0) return NULL;
1462 * If there is no memory left for buffering the
1463 * request, there is nothing we can do but hang up
1465 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1470 request_line = get_header(csp->client_iob);
1472 } while ((NULL != request_line) && ('\0' == *request_line));
1474 return request_line;
1480 CHUNK_STATUS_MISSING_DATA,
1481 CHUNK_STATUS_BODY_COMPLETE,
1482 CHUNK_STATUS_PARSE_ERROR
1486 /*********************************************************************
1488 * Function : chunked_body_is_complete
1490 * Description : Figures out whether or not a chunked body is complete.
1492 * Currently it always starts at the beginning of the
1493 * buffer which is somewhat wasteful and prevents Privoxy
1494 * from starting to forward the correctly parsed chunks
1495 * as soon as theoretically possible.
1497 * Should be modified to work with a common buffer,
1498 * and allow the caller to skip already parsed chunks.
1500 * This would allow the function to be used for unbuffered
1501 * response bodies as well.
1504 * 1 : iob = Buffer with the body to check.
1505 * 2 : length = Length of complete body
1507 * Returns : Enum with the result of the check.
1509 *********************************************************************/
1510 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1512 unsigned int chunksize;
1518 * We need at least a single digit, followed by "\r\n",
1519 * followed by an unknown amount of data, followed by "\r\n".
1521 if (p + 5 > iob->eod)
1523 return CHUNK_STATUS_MISSING_DATA;
1525 if (sscanf(p, "%x", &chunksize) != 1)
1527 return CHUNK_STATUS_PARSE_ERROR;
1531 * We want at least a single digit, followed by "\r\n",
1532 * followed by the specified amount of data, followed by "\r\n".
1534 if (p + chunksize + 5 > iob->eod)
1536 return CHUNK_STATUS_MISSING_DATA;
1539 /* Skip chunk-size. */
1540 p = strstr(p, "\r\n");
1543 return CHUNK_STATUS_PARSE_ERROR;
1545 /* Move beyond the chunkdata. */
1548 /* Make sure we're still within the buffer and have two bytes left */
1549 if (p + 2 > iob->eod)
1551 return CHUNK_STATUS_MISSING_DATA;
1554 /* There should be another "\r\n" to skip */
1555 if (memcmp(p, "\r\n", 2))
1557 return CHUNK_STATUS_PARSE_ERROR;
1560 } while (chunksize > 0U);
1562 *length = (size_t)(p - iob->cur);
1563 assert(*length <= (size_t)(iob->eod - iob->cur));
1564 assert(p <= iob->eod);
1566 return CHUNK_STATUS_BODY_COMPLETE;
1571 /*********************************************************************
1573 * Function : receive_chunked_client_request_body
1575 * Description : Read the chunk-encoded client request body.
1576 * Failures are dealt with.
1579 * 1 : csp = Current client state (buffers, headers, etc...)
1581 * Returns : JB_ERR_OK or JB_ERR_PARSE
1583 *********************************************************************/
1584 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1587 enum chunk_status status;
1589 while (CHUNK_STATUS_MISSING_DATA ==
1590 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1592 char buf[BUFFER_SIZE];
1595 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1597 log_error(LOG_LEVEL_ERROR,
1598 "Timeout while waiting for the client body.");
1601 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1604 log_error(LOG_LEVEL_ERROR,
1605 "Reading the client body failed: %E");
1608 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1613 if (status != CHUNK_STATUS_BODY_COMPLETE)
1615 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1616 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1617 log_error(LOG_LEVEL_CLF,
1618 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1619 return JB_ERR_PARSE;
1621 log_error(LOG_LEVEL_CONNECT,
1622 "Chunked client body completely read. Length: %lu", body_length);
1623 csp->expected_client_content_length = body_length;
1631 /*********************************************************************
1633 * Function : fuzz_chunked_transfer_encoding
1635 * Description : Treat the fuzzed input as chunked transfer encoding
1636 * to check and dechunk.
1639 * 1 : csp = Used to store the data.
1640 * 2 : fuzz_input_file = File to read the input from.
1642 * Returns : Result of dechunking
1644 *********************************************************************/
1645 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1648 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1649 enum chunk_status status;
1651 status = chunked_body_is_complete(csp->iob, &length);
1652 if (CHUNK_STATUS_BODY_COMPLETE != status)
1654 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1656 if (get_bytes_missing_from_chunked_data(csp->iob->cur, size, 0) == 0)
1658 if (CHUNK_STATUS_BODY_COMPLETE != status)
1660 log_error(LOG_LEVEL_ERROR,
1661 "There's disagreement about whether or not the chunked body is complete.");
1665 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1670 /*********************************************************************
1672 * Function : fuzz_client_request
1674 * Description : Try to get a client request from the fuzzed input.
1677 * 1 : csp = Current client state (buffers, headers, etc...)
1678 * 2 : fuzz_input_file = File to read the input from.
1680 * Returns : Result of fuzzing.
1682 *********************************************************************/
1683 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1688 csp->ip_addr_str = "fuzzer";
1690 if (strcmp(fuzz_input_file, "-") != 0)
1692 log_error(LOG_LEVEL_FATAL,
1693 "Fuzzed client requests can currently only be read from stdin (-).");
1695 err = receive_client_request(csp);
1696 if (err != JB_ERR_OK)
1700 err = parse_client_request(csp);
1701 if (err != JB_ERR_OK)
1709 #endif /* def FUZZ */
1712 #ifdef FEATURE_FORCE_LOAD
1713 /*********************************************************************
1715 * Function : force_required
1717 * Description : Checks a request line to see if it contains
1718 * the FORCE_PREFIX. If it does, it is removed
1719 * unless enforcing requests has beend disabled.
1722 * 1 : request_line = HTTP request line
1724 * Returns : TRUE if force is required, FALSE otherwise.
1726 *********************************************************************/
1727 static int force_required(const struct client_state *csp, char *request_line)
1731 p = strstr(request_line, "http://");
1735 p += strlen("http://");
1739 /* Intercepted request usually don't specify the protocol. */
1743 /* Go to the beginning of the path */
1748 * If the path is missing the request line is invalid and we
1749 * are done here. The client-visible rejection happens later on.
1754 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1756 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1758 /* XXX: Should clean more carefully */
1759 strclean(request_line, FORCE_PREFIX);
1760 log_error(LOG_LEVEL_FORCE,
1761 "Enforcing request: \"%s\".", request_line);
1765 log_error(LOG_LEVEL_FORCE,
1766 "Ignored force prefix in request: \"%s\".", request_line);
1772 #endif /* def FEATURE_FORCE_LOAD */
1775 /*********************************************************************
1777 * Function : receive_client_request
1779 * Description : Read the client's request (more precisely the
1780 * client headers) and answer it if necessary.
1783 * 1 : csp = Current client state (buffers, headers, etc...)
1785 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1787 *********************************************************************/
1788 static jb_err receive_client_request(struct client_state *csp)
1790 char buf[BUFFER_SIZE];
1793 struct http_request *http;
1797 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1798 struct list header_list;
1799 struct list *headers = &header_list;
1801 /* We don't care if the arriving data is a valid HTTP request or not. */
1802 csp->requests_received_total++;
1806 memset(buf, 0, sizeof(buf));
1808 req = get_request_line(csp);
1811 mark_server_socket_tainted(csp);
1812 return JB_ERR_PARSE;
1814 assert(*req != '\0');
1816 if (client_protocol_is_unsupported(csp, req))
1818 return JB_ERR_PARSE;
1821 #ifdef FEATURE_FORCE_LOAD
1822 if (force_required(csp, req))
1824 csp->flags |= CSP_FLAG_FORCED;
1826 #endif /* def FEATURE_FORCE_LOAD */
1828 err = parse_http_request(req, http);
1830 if (JB_ERR_OK != err)
1832 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1833 get_write_delay(csp));
1834 /* XXX: Use correct size */
1835 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1836 log_error(LOG_LEVEL_ERROR,
1837 "Couldn't parse request line received from %s: %s",
1838 csp->ip_addr_str, jb_err_to_string(err));
1840 free_http_request(http);
1841 return JB_ERR_PARSE;
1843 if (http->ssl && strcmpic(http->gpc, "CONNECT"))
1845 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1846 get_write_delay(csp));
1847 /* XXX: Use correct size */
1848 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0",
1850 log_error(LOG_LEVEL_ERROR, "Client %s tried to send a https "
1851 "URL without sending a CONNECT request first",
1853 free_http_request(http);
1854 return JB_ERR_PARSE;
1857 /* grab the rest of the client's headers */
1861 p = get_header(csp->client_iob);
1865 /* There are no additional headers to read. */
1872 * We didn't receive a complete header
1873 * line yet, get the rest of it.
1875 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1877 log_error(LOG_LEVEL_ERROR,
1878 "Client headers did not arrive in time. Timeout: %d",
1879 csp->config->socket_timeout);
1880 destroy_list(headers);
1881 return JB_ERR_PARSE;
1884 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1887 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1888 destroy_list(headers);
1889 return JB_ERR_PARSE;
1892 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1895 * If there is no memory left for buffering the
1896 * request, there is nothing we can do but hang up
1898 destroy_list(headers);
1899 return JB_ERR_MEMORY;
1904 if (!strncmpic(p, "Transfer-Encoding:", 18))
1907 * XXX: should be called through sed()
1908 * but currently can't.
1910 client_transfer_encoding(csp, &p);
1913 * We were able to read a complete
1914 * header and can finally enlist it.
1921 if (http->host == NULL)
1924 * If we still don't know the request destination,
1925 * the request is invalid or the client uses
1926 * Privoxy without its knowledge.
1928 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1931 * Our attempts to get the request destination
1932 * elsewhere failed or Privoxy is configured
1933 * to only accept proxy requests.
1935 * An error response has already been sent
1936 * and we're done here.
1938 return JB_ERR_PARSE;
1942 #ifdef FEATURE_CLIENT_TAGS
1943 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1944 set_client_address(csp, headers);
1945 get_tag_list_for_client(csp->client_tags, csp->client_address);
1949 * Determine the actions for this URL
1951 #ifdef FEATURE_TOGGLE
1952 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1954 /* Most compatible set of actions (i.e. none) */
1955 init_current_action(csp->action);
1958 #endif /* ndef FEATURE_TOGGLE */
1960 get_url_actions(csp, http);
1963 enlist(csp->headers, http->cmd);
1965 /* Append the previously read headers */
1966 err = list_append_list_unique(csp->headers, headers);
1967 destroy_list(headers);
1974 /*********************************************************************
1976 * Function : parse_client_request
1978 * Description : Parses the client's request and decides what to do
1981 * Note that since we're not using select() we could get
1982 * blocked here if a client connected, then didn't say
1986 * 1 : csp = Current client state (buffers, headers, etc...)
1988 * Returns : JB_ERR_OK or JB_ERR_PARSE
1990 *********************************************************************/
1991 static jb_err parse_client_request(struct client_state *csp)
1993 struct http_request *http = csp->http;
1996 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1997 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1998 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1999 && (csp->http->ssl == 0))
2001 /* Assume persistence until further notice */
2002 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2004 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2006 if (csp->http->ssl == 0)
2009 * This whole block belongs to chat() but currently
2010 * has to be executed before sed().
2012 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
2014 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
2016 return JB_ERR_PARSE;
2021 csp->expected_client_content_length = get_expected_content_length(csp->headers);
2023 verify_request_length(csp);
2025 #ifndef FEATURE_HTTPS_INSPECTION
2028 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2032 err = sed(csp, FILTER_CLIENT_HEADERS);
2033 if (JB_ERR_OK != err)
2035 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2037 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2038 csp->ip_addr_str, csp->http->cmd);
2039 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
2040 return JB_ERR_PARSE;
2042 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
2044 /* Check request line for rewrites. */
2045 if ((NULL == csp->headers->first->str)
2046 || (strcmp(http->cmd, csp->headers->first->str) &&
2047 (JB_ERR_OK != change_request_destination(csp))))
2050 * A header filter broke the request line - bail out.
2052 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
2053 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2054 /* XXX: Use correct size */
2055 log_error(LOG_LEVEL_CLF,
2056 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2057 log_error(LOG_LEVEL_ERROR,
2058 "Invalid request line after applying header filters.");
2059 free_http_request(http);
2061 return JB_ERR_PARSE;
2064 if (client_has_unsupported_expectations(csp))
2066 return JB_ERR_PARSE;
2074 /*********************************************************************
2076 * Function : read_http_request_body
2078 * Description : Reads remaining request body from the client.
2081 * 1 : csp = Current client state (buffers, headers, etc...)
2083 * Returns : 0 on success, anything else is an error.
2085 *********************************************************************/
2086 static int read_http_request_body(struct client_state *csp)
2088 size_t to_read = csp->expected_client_content_length;
2091 assert(to_read != 0);
2093 /* check if all data has been already read */
2094 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2099 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2100 to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2101 to_read -= (unsigned)len)
2103 char buf[BUFFER_SIZE];
2104 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2106 log_error(LOG_LEVEL_CONNECT,
2107 "Waiting for up to %lu bytes of request body from the client.",
2109 len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2112 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2115 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2119 assert(to_read >= len);
2124 log_error(LOG_LEVEL_CONNECT,
2125 "Not enough request body has been read: expected %lu more bytes",
2129 log_error(LOG_LEVEL_CONNECT,
2130 "The last %d bytes of the request body have been read", len);
2135 /*********************************************************************
2137 * Function : update_client_headers
2139 * Description : Updates the HTTP headers from the client request.
2142 * 1 : csp = Current client state (buffers, headers, etc...)
2143 * 2 : new_content_length = new content length value to set
2145 * Returns : 0 on success, anything else is an error.
2147 *********************************************************************/
2148 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2150 static const char content_length[] = "Content-Length:";
2152 struct list_entry *p;
2154 #ifndef FEATURE_HTTPS_INSPECTION
2155 for (p = csp->headers->first;
2157 for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2159 !updated && (p != NULL); p = p->next)
2161 /* Header crunch()ed in previous run? -> ignore */
2167 /* Does the current parser handle this header? */
2168 if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2170 updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2182 /*********************************************************************
2184 * Function : can_buffer_request_body
2186 * Description : Checks if the current request body can be stored in
2187 * the client_iob without hitting buffer limit.
2190 * 1 : csp = Current client state (buffers, headers, etc...)
2192 * Returns : TRUE if the current request size do not exceed buffer limit
2195 *********************************************************************/
2196 static int can_buffer_request_body(const struct client_state *csp)
2198 if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2199 csp->expected_client_content_length))
2201 log_error(LOG_LEVEL_INFO,
2202 "Not filtering request body from %s: buffer limit %lu will be exceeded "
2203 "(content length %llu)", csp->ip_addr_str, csp->config->buffer_limit,
2204 csp->expected_client_content_length);
2211 /*********************************************************************
2213 * Function : send_http_request
2215 * Description : Sends the HTTP headers from the client request
2216 * and all the body data that has already been received.
2219 * 1 : csp = Current client state (buffers, headers, etc...)
2221 * Returns : 0 on success, 1 on error, 2 if the request got crunched.
2223 *********************************************************************/
2224 static int send_http_request(struct client_state *csp)
2229 hdr = list_to_text(csp->headers);
2232 /* FIXME Should handle error properly */
2233 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2235 list_remove_all(csp->headers);
2238 * Write the client's (modified) header to the server
2239 * (along with anything else that may be in the buffer)
2241 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2246 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2247 csp->http->hostport);
2251 /* XXX: Filtered data is not sent if there's a pipelined request? */
2252 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2253 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2255 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2256 csp->http->hostport);
2263 #ifdef FEATURE_HTTPS_INSPECTION
2264 /*********************************************************************
2266 * Function : read_https_request_body
2268 * Description : Reads remaining request body from the client.
2271 * 1 : csp = Current client state (buffers, headers, etc...)
2273 * Returns : 0 on success, anything else is an error.
2275 *********************************************************************/
2276 static int read_https_request_body(struct client_state *csp)
2278 size_t to_read = csp->expected_client_content_length;
2281 assert(to_read != 0);
2283 /* check if all data has been already read */
2284 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2289 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2290 to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2291 data_is_available(csp->cfd, csp->config->socket_timeout));
2292 to_read -= (unsigned)len)
2294 unsigned char buf[BUFFER_SIZE];
2295 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2297 log_error(LOG_LEVEL_CONNECT,
2298 "Buffering encrypted client body. Prepared to read up to %lu bytes.",
2300 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2301 (unsigned)max_bytes_to_read);
2304 log_error(LOG_LEVEL_CONNECT,
2305 "Did not receive the whole encrypted request body from %s",
2309 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2313 assert(to_read >= len);
2318 log_error(LOG_LEVEL_CONNECT,
2319 "Not enough encrypted request body has been read: expected %lu more bytes",
2324 log_error(LOG_LEVEL_CONNECT,
2325 "The last %llu bytes of the encrypted request body have been read",
2326 csp->expected_client_content_length);
2331 /*********************************************************************
2333 * Function : receive_and_send_encrypted_post_data
2335 * Description : Reads remaining request body from the client and sends
2339 * 1 : csp = Current client state (buffers, headers, etc...)
2341 * Returns : 0 on success, anything else is an error.
2343 *********************************************************************/
2344 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2346 int content_length_known = csp->expected_client_content_length != 0;
2348 while ((content_length_known && csp->expected_client_content_length != 0) ||
2349 (is_ssl_pending(&(csp->ssl_client_attr)) ||
2350 data_is_available(csp->cfd, csp->config->socket_timeout)))
2352 unsigned char buf[BUFFER_SIZE];
2354 int max_bytes_to_read = sizeof(buf);
2356 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2358 max_bytes_to_read = (int)csp->expected_client_content_length;
2360 log_error(LOG_LEVEL_CONNECT,
2361 "Prepared to read up to %d bytes of encrypted request body from the client.",
2363 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2364 (unsigned)max_bytes_to_read);
2371 /* XXX: Does this actually happen? */
2374 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body.",
2376 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2381 if (csp->expected_client_content_length != 0)
2383 if (csp->expected_client_content_length >= len)
2385 csp->expected_client_content_length -= (unsigned)len;
2387 if (csp->expected_client_content_length == 0)
2389 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes.", len);
2395 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body.");
2402 /*********************************************************************
2404 * Function : send_https_request
2406 * Description : Sends the HTTP headers from the client request
2407 * and all the body data that has already been received.
2410 * 1 : csp = Current client state (buffers, headers, etc...)
2412 * Returns : 0 on success, anything else is an error.
2414 *********************************************************************/
2415 static int send_https_request(struct client_state *csp)
2421 hdr = list_to_text(csp->https_headers);
2424 /* FIXME Should handle error properly */
2425 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header.");
2427 list_remove_all(csp->https_headers);
2430 * Write the client's (modified) header to the server
2431 * (along with anything else that may be in the buffer)
2433 ret = ssl_send_data(&(csp->ssl_server_attr),
2434 (const unsigned char *)hdr, strlen(hdr));
2439 log_error(LOG_LEVEL_CONNECT,
2440 "Failed sending encrypted request headers to: %s: %E",
2441 csp->http->hostport);
2442 mark_server_socket_tainted(csp);
2446 /* XXX: Client body isn't sent if there's pipelined data? */
2447 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2448 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2449 csp->client_iob)) < 0))
2451 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2452 csp->http->hostport);
2455 if (flushed != 0 || csp->expected_client_content_length != 0)
2457 if (csp->expected_client_content_length != 0)
2459 if (csp->expected_client_content_length < flushed)
2461 log_error(LOG_LEVEL_ERROR,
2462 "Flushed %ld bytes of request body while only expecting %llu.",
2463 flushed, csp->expected_client_content_length);
2464 csp->expected_client_content_length = 0;
2468 log_error(LOG_LEVEL_CONNECT,
2469 "Flushed %ld bytes of request body while expecting %llu.",
2470 flushed, csp->expected_client_content_length);
2471 csp->expected_client_content_length -= (unsigned)flushed;
2472 if (receive_and_send_encrypted_post_data(csp))
2480 log_error(LOG_LEVEL_CONNECT,
2481 "Flushed %ld bytes of request body.", flushed);
2485 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent.");
2492 /*********************************************************************
2494 * Function : receive_encrypted_request_headers
2496 * Description : Receives the encrypted request headers when
2500 * 1 : csp = Current client state (buffers, headers, etc...)
2502 * Returns : JB_ERR_OK on success,
2503 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2505 *********************************************************************/
2506 static jb_err receive_encrypted_request_headers(struct client_state *csp)
2508 char buf[BUFFER_SIZE];
2514 log_error(LOG_LEVEL_HEADER, "Waiting for encrypted client headers");
2515 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2516 !data_is_available(csp->cfd, csp->config->socket_timeout))
2518 log_error(LOG_LEVEL_CONNECT,
2519 "Socket %d timed out while waiting for client headers", csp->cfd);
2520 return JB_ERR_PARSE;
2522 len = ssl_recv_data(&(csp->ssl_client_attr),
2523 (unsigned char *)buf, sizeof(buf));
2526 log_error(LOG_LEVEL_CONNECT,
2527 "Socket %d closed while waiting for client headers", csp->cfd);
2528 return JB_ERR_PARSE;
2532 return JB_ERR_PARSE;
2534 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2536 return JB_ERR_MEMORY;
2538 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2539 } while (p == NULL);
2541 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2547 /*********************************************************************
2549 * Function : change_encrypted_request_destination
2551 * Description : Parse a (rewritten) request line from an encrypted
2552 * request and regenerate the http request data.
2555 * 1 : csp = Current client state (buffers, headers, etc...)
2557 * Returns : Forwards the parse_http_request() return code.
2558 * Terminates in case of memory problems.
2560 *********************************************************************/
2561 static jb_err change_encrypted_request_destination(struct client_state *csp)
2564 char *original_host = csp->http->host;
2565 int original_port = csp->http->port;
2567 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2568 csp->https_headers->first->str);
2569 csp->http->host = NULL;
2570 free_http_request(csp->http);
2571 err = parse_http_request(csp->https_headers->first->str, csp->http);
2572 if (JB_ERR_OK != err)
2574 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2575 jb_err_to_string(err));
2576 freez(original_host);
2580 if (csp->http->host == NULL)
2582 char port_string[10];
2584 * The rewritten request line did not specify a host
2585 * which means we can use the original host specified
2588 csp->http->host = original_host;
2589 csp->http->port = original_port;
2590 log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2593 * If the rewritten request line didn't contain a host
2594 * it also didn't contain a port so we can reuse the host
2597 freez(csp->http->hostport);
2598 csp->http->hostport = strdup_or_die(csp->http->host);
2599 snprintf(port_string, sizeof(port_string), ":%d", original_port);
2600 err = string_append(&csp->http->hostport, port_string);
2601 if (err != JB_ERR_OK)
2603 log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2604 jb_err_to_string(err));
2609 * While the request line didn't mention it,
2610 * we're https-inspecting and want to speak TLS
2613 csp->http->server_ssl = 1;
2618 /* The rewrite filter added a host so we can ditch the original */
2619 freez(original_host);
2620 csp->http->server_ssl = csp->http->ssl;
2623 csp->http->client_ssl = 1;
2625 freez(csp->https_headers->first->str);
2626 build_request_line(csp, NULL, &csp->https_headers->first->str);
2628 if (!server_use_ssl(csp))
2630 log_error(LOG_LEVEL_REDIRECTS,
2631 "Rewritten request line results in downgrade to http");
2633 * Replace the unencryptd headers received with the
2634 * CONNECT request with the ones we received securely.
2636 destroy_list(csp->headers);
2637 csp->headers->first = csp->https_headers->first;
2638 csp->headers->last = csp->https_headers->last;
2639 csp->https_headers->first = NULL;
2640 csp->https_headers->last = NULL;
2648 /*********************************************************************
2650 * Function : process_encrypted_request_headers
2652 * Description : Receives and parses the encrypted headers send
2653 * by the client when https-inspecting.
2656 * 1 : csp = Current client state (buffers, headers, etc...)
2658 * Returns : JB_ERR_OK on success,
2659 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2661 *********************************************************************/
2662 static jb_err process_encrypted_request_headers(struct client_state *csp)
2667 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2668 struct list header_list;
2669 struct list *headers = &header_list;
2671 assert(csp->ssl_with_client_is_opened);
2673 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2674 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2676 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2679 err = receive_encrypted_request_headers(csp);
2680 if (err != JB_ERR_OK)
2682 if (csp->client_iob->cur == NULL ||
2683 csp->client_iob->cur == csp->client_iob->eod)
2686 * We did not receive any data, most likely because the
2687 * client is done. Don't log this as a parse failure.
2689 return JB_ERR_PARSE;
2691 /* XXX: Also used for JB_ERR_MEMORY */
2692 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2693 jb_err_to_string(err));
2694 ssl_send_data_delayed(&(csp->ssl_client_attr),
2695 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2699 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2700 request_line = get_header(csp->client_iob);
2701 if (request_line == NULL)
2703 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2704 ssl_send_data_delayed(&(csp->ssl_client_attr),
2705 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2706 return JB_ERR_PARSE;
2708 assert(*request_line != '\0');
2710 if (client_protocol_is_unsupported(csp, request_line))
2713 * If the protocol is unsupported we're done here.
2714 * client_protocol_is_unsupported() took care of sending
2715 * the error response and logging the error message.
2717 return JB_ERR_PARSE;
2720 #ifdef FEATURE_FORCE_LOAD
2721 if (force_required(csp, request_line))
2723 csp->flags |= CSP_FLAG_FORCED;
2725 #endif /* def FEATURE_FORCE_LOAD */
2727 free_http_request(csp->http);
2729 err = parse_http_request(request_line, csp->http);
2730 /* XXX: Restore ssl setting. This is ugly */
2731 csp->http->client_ssl = 1;
2732 csp->http->server_ssl = 1;
2734 freez(request_line);
2735 if (JB_ERR_OK != err)
2737 ssl_send_data_delayed(&(csp->ssl_client_attr),
2738 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2739 /* XXX: Use correct size */
2740 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2741 log_error(LOG_LEVEL_ERROR,
2742 "Couldn't parse request line received from %s: %s",
2743 csp->ip_addr_str, jb_err_to_string(err));
2745 free_http_request(csp->http);
2746 return JB_ERR_PARSE;
2749 /* Parse the rest of the client's headers. */
2753 p = get_header(csp->client_iob);
2757 /* There are no additional headers to read. */
2764 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2767 * Our attempts to get the request destination
2770 log_error(LOG_LEVEL_ERROR,
2771 "Failed to get the encrypted request destination");
2772 ssl_send_data_delayed(&(csp->ssl_client_attr),
2773 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2774 destroy_list(headers);
2776 return JB_ERR_PARSE;
2779 /* Split the domain we just got for pattern matching */
2780 init_domain_components(csp->http);
2782 #ifdef FEATURE_CLIENT_TAGS
2783 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2784 if (csp->client_address == NULL)
2786 set_client_address(csp, headers);
2787 get_tag_list_for_client(csp->client_tags, csp->client_address);
2791 #ifdef FEATURE_TOGGLE
2792 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2796 * Determine the actions for this request after
2797 * clearing the ones from the previous one.
2799 free_current_action(csp->action);
2800 get_url_actions(csp, csp->http);
2803 enlist(csp->https_headers, csp->http->cmd);
2805 /* Append the previously read headers */
2806 err = list_append_list_unique(csp->https_headers, headers);
2807 destroy_list(headers);
2808 if (JB_ERR_OK != err)
2810 /* XXX: Send error message */
2814 /* XXX: Work around crash */
2815 csp->error_message = NULL;
2817 /* XXX: Why do this here? */
2820 err = sed_https(csp);
2821 if (JB_ERR_OK != err)
2823 ssl_send_data_delayed(&(csp->ssl_client_attr),
2824 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2825 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2827 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2828 csp->ip_addr_str, csp->http->cmd);
2829 return JB_ERR_PARSE;
2832 if ((NULL == csp->https_headers->first->str)
2833 || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2834 (JB_ERR_OK != change_encrypted_request_destination(csp))))
2836 ssl_send_data_delayed(&(csp->ssl_client_attr),
2837 (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2838 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2839 log_error(LOG_LEVEL_ERROR,
2840 "Invalid request line after applying header filters.");
2841 /* XXX: Use correct size */
2842 log_error(LOG_LEVEL_CLF,
2843 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2845 return JB_ERR_PARSE;
2848 log_error(LOG_LEVEL_HEADER, "Encrypted request headers processed");
2849 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2856 /*********************************************************************
2858 * Function : cgi_page_requested
2860 * Description : Checks if a request is for an internal CGI page.
2863 * 1 : host = The host requested by the client.
2865 * Returns : 1 if a CGI page has been requested, 0 otherwise
2867 *********************************************************************/
2868 static int cgi_page_requested(const char *host)
2870 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2871 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2872 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2873 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2883 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2884 /*********************************************************************
2886 * Function : continue_https_chat
2888 * Description : Behaves similar to chat() but only deals with
2889 * https-inspected requests that arrive on an already
2890 * established connection. The first request is always
2891 * served by chat() which is a lot more complex as it
2892 * has to deal with forwarding settings and connection
2895 * If a connection to the server has already been
2896 * opened it is reused unless the request is blocked
2897 * or the forwarder changed.
2899 * If a connection to the server has not yet been
2900 * opened (because the previous request was crunched),
2901 * or the forwarder changed, the connection is dropped
2902 * so that the client retries on a fresh one.
2905 * 1 : csp = Current client state (buffers, headers, etc...)
2907 * Returns : Nothing.
2909 *********************************************************************/
2910 static void continue_https_chat(struct client_state *csp)
2912 const struct forward_spec *fwd;
2914 if (JB_ERR_OK != process_encrypted_request_headers(csp))
2916 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2920 #if defined(FEATURE_STATISTICS) && defined(MUTEX_LOCKS_AVAILABLE)
2921 privoxy_mutex_lock(&block_statistics_mutex);
2922 number_of_requests_received++;
2923 privoxy_mutex_unlock(&block_statistics_mutex);
2926 csp->requests_received_total++;
2929 * We have an encrypted request. Check if one of the crunchers wants it.
2931 if (crunch_response_triggered(csp, crunchers_all))
2934 * Yes. The client got the crunch response and we're done here.
2938 if (csp->ssl_with_server_is_opened == 0)
2940 log_error(LOG_LEVEL_CONNECT,
2941 "Dropping the client connection on socket %d. "
2942 "The server connection has not been established yet.",
2944 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2947 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2949 if (csp->expected_client_content_length != 0 &&
2950 (client_body_filters_enabled(csp->action) ||
2951 client_body_taggers_enabled(csp->action)) &&
2952 can_buffer_request_body(csp))
2954 int content_modified;
2956 if (read_https_request_body(csp))
2961 if (client_body_taggers_enabled(csp->action))
2963 execute_client_body_taggers(csp, csp->expected_client_content_length);
2964 if (crunch_response_triggered(csp, crunchers_all))
2967 * Yes. The client got the crunch response and we're done here.
2972 if (client_body_filters_enabled(csp->action))
2974 size_t modified_content_length = csp->expected_client_content_length;
2975 content_modified = execute_client_body_filters(csp,
2976 &modified_content_length);
2977 if ((content_modified == 1) &&
2978 (modified_content_length != csp->expected_client_content_length) &&
2979 update_client_headers(csp, modified_content_length))
2981 /* XXX: Send error response */
2982 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2986 csp->expected_client_content_length = 0;
2989 fwd = forward_url(csp, csp->http);
2990 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2992 log_error(LOG_LEVEL_CONNECT,
2993 "Dropping the client connection on socket %d with "
2994 "server socket %d connected to %s. The forwarder has changed.",
2995 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2996 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3000 log_applied_actions(csp->action);
3002 log_error(LOG_LEVEL_CONNECT,
3003 "Reusing server socket %d connected to %s. Requests already sent: %u.",
3004 csp->server_connection.sfd, csp->server_connection.host,
3005 csp->server_connection.requests_sent_total);
3007 if (send_https_request(csp))
3010 * Most likely the server connection timed out. We can't easily
3011 * create a new one so simply drop the client connection without a
3012 * error response to let the client retry.
3014 log_error(LOG_LEVEL_CONNECT,
3015 "Dropping client connection on socket %d. "
3016 "Forwarding the encrypted client request failed.",
3020 csp->server_connection.request_sent = time(NULL);
3021 csp->server_connection.requests_sent_total++;
3022 handle_established_connection(csp);
3023 freez(csp->receive_buffer);
3025 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3029 /*********************************************************************
3031 * Function : send_server_headers
3033 * Description : Sends the server headers to the client.
3036 * 1 : csp = Current client state (buffers, headers, etc...)
3038 * Returns : 0 on succes, -1 on error.
3040 *********************************************************************/
3041 static int send_server_headers(struct client_state *csp)
3043 char *server_headers;
3046 server_headers = list_to_text(csp->headers);
3047 if (server_headers == NULL)
3050 * Memory is too tight to even generate the header.
3051 * Send our static "Out-of-memory" page.
3053 log_error(LOG_LEVEL_ERROR,
3054 "Out of memory while trying to send server headers.");
3055 send_crunch_response(csp, cgi_error_memory());
3056 mark_server_socket_tainted(csp);
3057 #ifdef FEATURE_HTTPS_INSPECTION
3058 close_client_and_server_ssl_connections(csp);
3062 #ifdef FEATURE_HTTPS_INSPECTION
3063 if (client_use_ssl(csp))
3065 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3066 (const unsigned char *)server_headers, strlen(server_headers),
3067 get_write_delay(csp));
3072 ret = write_socket_delayed(csp->cfd, server_headers, strlen(server_headers),
3073 get_write_delay(csp));
3075 freez(server_headers);
3078 log_error(LOG_LEVEL_ERROR, "Failed to send server headers to the client.");
3079 mark_server_socket_tainted(csp);
3080 #ifdef FEATURE_HTTPS_INSPECTION
3081 close_client_and_server_ssl_connections(csp);
3090 /*********************************************************************
3092 * Function : handle_established_connection
3094 * Description : Shuffle data between client and server once the
3095 * connection has been established and the request
3099 * 1 : csp = Current client state (buffers, headers, etc...)
3101 * Returns : Nothing.
3103 *********************************************************************/
3104 static void handle_established_connection(struct client_state *csp)
3109 struct pollfd poll_fds[2];
3113 struct timeval timeout;
3116 int ms_iis5_hack = 0;
3117 unsigned long long byte_count = 0;
3118 struct http_request *http;
3119 long len = 0; /* for buffer sizes (and negative error codes) */
3120 int buffer_and_filter_content = 0;
3121 unsigned int write_delay;
3122 size_t chunk_offset = 0;
3123 #ifdef FEATURE_HTTPS_INSPECTION
3125 int use_ssl_tunnel = 0;
3126 csp->dont_verify_certificate = 0;
3128 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3130 /* Pass encrypted content without filtering. */
3135 /* Skeleton for HTTP response, if we should intercept the request */
3136 struct http_response *rsp;
3137 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3138 int watch_client_socket;
3141 csp->receive_buffer_size = csp->config->receive_buffer_size;
3142 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3143 if (csp->receive_buffer == NULL)
3145 log_error(LOG_LEVEL_ERROR,
3146 "Out of memory. Failed to allocate the receive buffer.");
3147 rsp = cgi_error_memory();
3148 send_crunch_response(csp, rsp);
3155 maxfd = (csp->cfd > csp->server_connection.sfd) ?
3156 csp->cfd : csp->server_connection.sfd;
3159 /* pass data between the client and server
3160 * until one or the other shuts down the connection.
3165 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3166 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3168 write_delay = get_write_delay(csp);
3172 #ifdef FEATURE_HTTPS_INSPECTION
3173 if (server_use_ssl(csp) && is_ssl_pending(&(csp->ssl_server_attr)))
3176 * It's possible that the TLS library already consumed all the
3177 * data the server intends to send. If that happens poll() and
3178 * select() will no longer see the data as available so we have
3179 * to skip the calls.
3181 goto server_wants_to_talk;
3183 if (watch_client_socket && client_use_ssl(csp) &&
3184 is_ssl_pending(&(csp->ssl_client_attr)))
3187 * The TLS libray may also consume all of the remaining data
3188 * from the client when we're shuffling the data from an
3189 * unbuffered request body to the server.
3191 goto client_wants_to_talk;
3196 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3197 if (!watch_client_socket)
3199 maxfd = csp->server_connection.sfd;
3202 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3204 FD_SET(csp->cfd, &rfds);
3207 FD_SET(csp->server_connection.sfd, &rfds);
3208 #endif /* ndef HAVE_POLL */
3210 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3211 if (server_body && server_response_is_complete(csp, byte_count))
3213 if (csp->expected_content_length == byte_count)
3215 log_error(LOG_LEVEL_CONNECT,
3216 "Done reading from server. Content length: %llu as expected. "
3217 "Bytes most recently read: %ld.",
3222 log_error(LOG_LEVEL_CONNECT,
3223 "Done reading from server. Expected content length: %llu. "
3224 "Actual content length: %llu. Bytes most recently read: %ld.",
3225 csp->expected_content_length, byte_count, len);
3229 * XXX: Should not jump around, handle_established_connection()
3230 * is complicated enough already.
3234 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3237 poll_fds[0].fd = csp->cfd;
3238 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3239 if (!watch_client_socket)
3242 * Ignore incoming data, but still watch out
3243 * for disconnects etc. These flags are always
3244 * implied anyway but explicitly setting them
3247 poll_fds[0].events = POLLERR|POLLHUP;
3252 poll_fds[0].events = POLLIN;
3254 poll_fds[1].fd = csp->server_connection.sfd;
3255 poll_fds[1].events = POLLIN;
3256 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3258 timeout.tv_sec = csp->config->socket_timeout;
3259 timeout.tv_usec = 0;
3260 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3261 #endif /* def HAVE_POLL */
3263 /* Server or client not responding in timeout */
3266 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3267 csp->config->socket_timeout, http->url);
3268 if ((byte_count == 0) && (http->ssl == 0))
3270 send_crunch_response(csp, error_response(csp, "connection-timeout"));
3272 mark_server_socket_tainted(csp);
3273 #ifdef FEATURE_HTTPS_INSPECTION
3274 close_client_and_server_ssl_connections(csp);
3281 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3283 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3285 mark_server_socket_tainted(csp);
3286 #ifdef FEATURE_HTTPS_INSPECTION
3287 close_client_and_server_ssl_connections(csp);
3293 * This is the body of the browser's request,
3294 * just read and write it.
3296 * Receives data from browser and sends it to server
3298 * XXX: Make sure the client doesn't use pipelining
3299 * behind Privoxy's back.
3302 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3304 log_error(LOG_LEVEL_CONNECT,
3305 "The client socket %d has become unusable while "
3306 "the server socket %d is still open.",
3307 csp->cfd, csp->server_connection.sfd);
3308 mark_server_socket_tainted(csp);
3312 if (poll_fds[0].revents != 0)
3314 if (FD_ISSET(csp->cfd, &rfds))
3315 #endif /* def HAVE_POLL*/
3317 int max_bytes_to_read;
3319 #ifdef FEATURE_HTTPS_INSPECTION
3320 client_wants_to_talk:
3323 max_bytes_to_read = (int)csp->receive_buffer_size;
3325 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3326 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3328 if (data_is_available(csp->cfd, 0))
3331 * If the next request is already waiting, we have
3332 * to stop select()ing the client socket. Otherwise
3333 * we would always return right away and get nothing
3336 watch_client_socket = 0;
3337 log_error(LOG_LEVEL_CONNECT,
3338 "Stop watching client socket %d. "
3339 "There's already another request waiting.",
3344 * If the client socket is set, but there's no data
3345 * available on the socket, the client went fishing
3346 * and continuing talking to the server makes no sense.
3348 log_error(LOG_LEVEL_CONNECT,
3349 "The client closed socket %d while "
3350 "the server socket %d is still open.",
3351 csp->cfd, csp->server_connection.sfd);
3352 mark_server_socket_tainted(csp);
3355 if (csp->expected_client_content_length != 0)
3357 if (csp->expected_client_content_length < csp->receive_buffer_size)
3359 max_bytes_to_read = (int)csp->expected_client_content_length;
3361 log_error(LOG_LEVEL_CONNECT,
3362 "Waiting for up to %d bytes from the client.",
3365 assert(max_bytes_to_read <= csp->receive_buffer_size);
3366 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3368 #ifdef FEATURE_HTTPS_INSPECTION
3369 if (client_use_ssl(csp))
3371 if (csp->http->status == 101)
3373 len = ssl_recv_data(&(csp->ssl_client_attr),
3374 (unsigned char *)csp->receive_buffer,
3375 (size_t)max_bytes_to_read);
3378 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3379 "on client socket %d for an upgraded connection",
3385 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3386 "on client socket %d for an upgraded connection",
3390 byte_count += (unsigned long long)len;
3391 len = ssl_send_data(&(csp->ssl_server_attr),
3392 (unsigned char *)csp->receive_buffer, (size_t)len);
3395 log_error(LOG_LEVEL_ERROR, "Failed to send data "
3396 "on server socket %d for an upgraded connection",
3397 csp->server_connection.sfd);
3402 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3406 #endif /* def FEATURE_HTTPS_INSPECTION */
3408 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3412 /* XXX: not sure if this is necessary. */
3413 mark_server_socket_tainted(csp);
3414 break; /* "game over, man" */
3417 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3418 if (csp->expected_client_content_length != 0)
3420 assert(len <= max_bytes_to_read);
3421 csp->expected_client_content_length -= (unsigned)len;
3422 log_error(LOG_LEVEL_CONNECT,
3423 "Expected client content length set to %llu "
3424 "after reading %ld bytes.",
3425 csp->expected_client_content_length, len);
3426 if (csp->expected_client_content_length == 0)
3428 log_error(LOG_LEVEL_CONNECT,
3429 "Done reading from the client.");
3430 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3433 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3435 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3437 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3438 mark_server_socket_tainted(csp);
3446 * The server wants to talk. It could be the header or the body.
3449 if (poll_fds[1].revents != 0)
3451 if (FD_ISSET(csp->server_connection.sfd, &rfds))
3452 #endif /* HAVE_POLL */
3454 #ifdef FEATURE_HTTPS_INSPECTION
3455 server_wants_to_talk:
3457 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3459 * If we are buffering content, we don't want to eat up to
3460 * buffer-limit bytes if the client no longer cares about them.
3461 * If we aren't buffering, however, a dead client socket will be
3462 * noticed pretty much right away anyway, so we can reduce the
3463 * overhead by skipping the check.
3465 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3468 log_error(LOG_LEVEL_CONNECT,
3469 "The server still wants to talk, but the client may already have hung up on us.");
3471 log_error(LOG_LEVEL_CONNECT,
3472 "The server still wants to talk, but the client hung up on us.");
3473 mark_server_socket_tainted(csp);
3474 #ifdef FEATURE_HTTPS_INSPECTION
3475 close_client_and_server_ssl_connections(csp);
3478 #endif /* def _WIN32 */
3480 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3482 #ifdef FEATURE_HTTPS_INSPECTION
3484 * Reading data from standard or secured connection (HTTP/HTTPS)
3486 if (server_use_ssl(csp))
3488 len = ssl_recv_data(&(csp->ssl_server_attr),
3489 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3494 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3495 (int)csp->receive_buffer_size);
3500 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3502 if ((http->ssl && (csp->fwd == NULL))
3503 #ifdef FEATURE_HTTPS_INSPECTION
3509 * Just hang up. We already confirmed the client's CONNECT
3510 * request with status code 200 and unencrypted content is
3511 * no longer welcome.
3513 log_error(LOG_LEVEL_ERROR,
3514 "CONNECT already confirmed. Unable to tell the client about the problem.");
3517 else if (byte_count)
3520 * Just hang up. We already transmitted the original headers
3521 * and parts of the original content and therefore missed the
3522 * chance to send an error message (without risking data corruption).
3524 * XXX: we could retry with a fancy range request here.
3526 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3527 "Unable to tell the client about the problem.");
3528 mark_server_socket_tainted(csp);
3529 #ifdef FEATURE_HTTPS_INSPECTION
3530 close_client_and_server_ssl_connections(csp);
3535 * XXX: Consider handling the cases above the same.
3537 mark_server_socket_tainted(csp);
3541 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3543 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3546 * This is guaranteed by allocating with zalloc_or_die()
3547 * and never (intentionally) writing to the last byte.
3549 * csp->receive_buffer_size is the size of the part of the
3550 * buffer we intentionally write to, but we actually
3551 * allocated csp->receive_buffer_size+1 bytes so the assertion
3552 * stays within the allocated range.
3554 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3557 * Add a trailing zero to let be able to use string operations.
3558 * XXX: do we still need this with filter_popups gone?
3560 assert(len <= csp->receive_buffer_size);
3561 csp->receive_buffer[len] = '\0';
3564 * Normally, this would indicate that we've read
3565 * as much as the server has sent us and we can
3566 * close the client connection. However, Microsoft
3567 * in its wisdom has released IIS/5 with a bug that
3568 * prevents it from sending the trailing \r\n in
3569 * a 302 redirect header (and possibly other headers).
3570 * To work around this if we've haven't parsed
3571 * a full header we'll append a trailing \r\n
3572 * and see if this now generates a valid one.
3574 * This hack shouldn't have any impacts. If we've
3575 * already transmitted the header or if this is a
3576 * SSL connection, then we won't bother with this
3577 * hack. So we only work on partially received
3578 * headers. If we append a \r\n and this still
3579 * doesn't generate a valid header, then we won't
3580 * transmit anything to the client.
3585 if (server_body || (http->ssl
3586 #ifdef FEATURE_HTTPS_INSPECTION
3592 * If we have been buffering up the document,
3593 * now is the time to apply content modification
3594 * and send the result to the client.
3596 if (buffer_and_filter_content)
3598 p = execute_content_filters(csp);
3600 * If content filtering fails, use the original
3601 * buffer and length.
3602 * (see p != NULL ? p : csp->iob->cur below)
3606 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3608 #ifdef FEATURE_COMPRESSION
3609 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3610 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3612 char *compressed_content = compress_buffer(p,
3613 (size_t *)&csp->content_length, csp->config->compression_level);
3614 if (compressed_content != NULL)
3617 p = compressed_content;
3618 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3623 if (JB_ERR_OK != update_server_headers(csp))
3625 log_error(LOG_LEVEL_FATAL,
3626 "Failed to update server headers. after filtering.");
3629 if (send_server_headers(csp))
3634 #ifdef FEATURE_HTTPS_INSPECTION
3636 * Sending data with standard or secured connection (HTTP/HTTPS)
3638 if (client_use_ssl(csp))
3640 if (ssl_send_data_delayed(&(csp->ssl_client_attr),
3641 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3642 csp->content_length, get_write_delay(csp)) < 0)
3644 log_error(LOG_LEVEL_ERROR,
3645 "Failed to send the modified content to the client over TLS");
3647 mark_server_socket_tainted(csp);
3648 close_client_and_server_ssl_connections(csp);
3653 #endif /* def FEATURE_HTTPS_INSPECTION */
3655 if (write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3656 (size_t)csp->content_length, write_delay))
3658 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3660 mark_server_socket_tainted(csp);
3668 break; /* "game over, man" */
3672 * This is not the body, so let's pretend the server just sent
3675 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3676 len = (int)strlen(csp->receive_buffer);
3679 * Now, let the normal header parsing algorithm below do its
3680 * job. If it fails, we'll exit instead of continuing.
3687 * If we're in the body of the server document, just write it to
3688 * the client, unless we need to buffer the body for later
3689 * content-filtering.
3691 if (server_body || (http->ssl
3692 #ifdef FEATURE_HTTPS_INSPECTION
3697 if (buffer_and_filter_content)
3700 * If there is no memory left for buffering the content, or the buffer limit
3701 * has been reached, switch to non-filtering mode, i.e. make & write the
3702 * header, flush the iob and buf, and get out of the way.
3704 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3708 log_error(LOG_LEVEL_INFO,
3709 "Flushing header and buffers. Stepping back from filtering.");
3711 if (send_server_headers(csp))
3716 #ifdef FEATURE_HTTPS_INSPECTION
3718 * Sending data with standard or secured connection (HTTP/HTTPS)
3720 if (client_use_ssl(csp))
3722 if (((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3724 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3725 (const unsigned char *)csp->receive_buffer, (size_t)len,
3726 get_write_delay(csp)) < 0))
3728 log_error(LOG_LEVEL_CONNECT,
3729 "Flush header and buffers to client failed");
3730 mark_server_socket_tainted(csp);
3731 close_client_and_server_ssl_connections(csp);
3736 #endif /* def FEATURE_HTTPS_INSPECTION */
3738 if (((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3739 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3742 log_error(LOG_LEVEL_CONNECT,
3743 "Flush header and buffers to client failed: %E");
3744 mark_server_socket_tainted(csp);
3750 * Reset the byte_count to the amount of bytes we just
3751 * flushed. len will be added a few lines below.
3753 byte_count = (unsigned long long)flushed;
3754 if ((csp->flags & CSP_FLAG_CHUNKED) && (chunk_offset != 0))
3756 log_error(LOG_LEVEL_CONNECT,
3757 "Reducing chunk offset %lu by %ld to %lu.", chunk_offset, flushed,
3758 (chunk_offset - (unsigned)flushed));
3759 assert(chunk_offset >= flushed); /* XXX: Reachable with malicious input? */
3760 chunk_offset -= (unsigned)flushed;
3762 /* Make room in the iob. */
3763 csp->iob->cur = csp->iob->eod = csp->iob->buf;
3765 if (add_to_iob(csp->iob, csp->config->buffer_limit,
3766 csp->receive_buffer, len))
3768 /* This is not supposed to happen but ... */
3769 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3770 log_error(LOG_LEVEL_ERROR, "Failed to buffer %ld bytes of "
3771 "chunk-encoded data after resetting the buffer.", len);
3775 buffer_and_filter_content = 0;
3781 #ifdef FEATURE_HTTPS_INSPECTION
3783 * Sending data with standard or secured connection (HTTP/HTTPS)
3785 if (client_use_ssl(csp))
3787 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3788 (const unsigned char *)csp->receive_buffer, (size_t)len,
3789 get_write_delay(csp));
3792 log_error(LOG_LEVEL_ERROR,
3793 "Sending data to client failed");
3794 mark_server_socket_tainted(csp);
3795 close_client_and_server_ssl_connections(csp);
3800 #endif /* def FEATURE_HTTPS_INSPECTION */
3802 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3803 (size_t)len, write_delay))
3805 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3806 mark_server_socket_tainted(csp);
3810 if (csp->flags & CSP_FLAG_CHUNKED)
3813 * While we don't need the data to filter it, put it in the
3814 * buffer so we can keep track of the offset to the start of
3815 * the next chunk and detect when the response is finished.
3817 size_t encoded_bytes = (size_t)(csp->iob->eod - csp->iob->cur);
3819 if (csp->config->buffer_limit / 4 < encoded_bytes)
3822 * Reset the buffer to reduce the memory footprint.
3824 log_error(LOG_LEVEL_CONNECT,
3825 "Reducing the chunk offset from %lu to %lu after "
3826 "discarding %lu bytes to make room in the buffer.",
3827 chunk_offset, (chunk_offset - encoded_bytes),
3829 chunk_offset -= encoded_bytes;
3830 csp->iob->cur = csp->iob->eod = csp->iob->buf;
3832 if (add_to_iob(csp->iob, csp->config->buffer_limit,
3833 csp->receive_buffer, len))
3835 /* This is not supposed to happen but ... */
3836 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
3837 log_error(LOG_LEVEL_ERROR,
3838 "Failed to buffer %ld bytes of chunk-encoded data.",
3844 byte_count += (unsigned long long)len;
3846 if (csp->flags & CSP_FLAG_CHUNKED)
3849 size_t encoded_bytes = (size_t)(csp->iob->eod - csp->iob->cur);
3851 rc = get_bytes_missing_from_chunked_data(csp->iob->cur, encoded_bytes,
3857 chunk_offset = (size_t)rc;
3860 if (chunked_data_is_complete(csp->iob->cur, encoded_bytes, chunk_offset))
3862 log_error(LOG_LEVEL_CONNECT,
3863 "We buffered the last chunk of the response.");
3864 csp->expected_content_length = byte_count;
3865 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3875 * We're still looking for the end of the server's header.
3876 * Buffer up the data we just read. If that fails, there's
3877 * little we can do but send our static out-of-memory page.
3879 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3881 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3882 rsp = cgi_error_memory();
3883 send_crunch_response(csp, rsp);
3884 mark_server_socket_tainted(csp);
3885 #ifdef FEATURE_HTTPS_INSPECTION
3886 close_client_and_server_ssl_connections(csp);
3891 /* Convert iob into something sed() can digest */
3892 if (JB_ERR_PARSE == get_server_headers(csp))
3897 * Well, we tried our MS IIS/5 hack and it didn't work.
3898 * The header is incomplete and there isn't anything
3899 * we can do about it.
3901 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3902 "Applying the MS IIS5 hack didn't help.");
3903 log_error(LOG_LEVEL_CLF,
3904 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3905 #ifdef FEATURE_HTTPS_INSPECTION
3907 * Sending data with standard or secured connection (HTTP/HTTPS)
3909 if (client_use_ssl(csp))
3911 ssl_send_data_delayed(&(csp->ssl_client_attr),
3912 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3913 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3916 #endif /* def FEATURE_HTTPS_INSPECTION */
3918 write_socket_delayed(csp->cfd,
3919 INVALID_SERVER_HEADERS_RESPONSE,
3920 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3922 mark_server_socket_tainted(csp);
3923 #ifdef FEATURE_HTTPS_INSPECTION
3924 close_client_and_server_ssl_connections(csp);
3931 * Since we have to wait for more from the server before
3932 * we can parse the headers we just continue here.
3934 log_error(LOG_LEVEL_CONNECT,
3935 "Continuing buffering server headers from socket %d. "
3936 "Bytes most recently read: %ld.", csp->cfd, len);
3943 * Account for the content bytes we
3944 * might have gotten with the headers.
3946 assert(csp->iob->eod >= csp->iob->cur);
3947 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3950 /* Did we actually get anything? */
3951 if (NULL == csp->headers->first)
3953 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3955 log_error(LOG_LEVEL_ERROR,
3956 "No server or forwarder response received on socket %d. "
3957 "Closing client socket %d without sending data.",
3958 csp->server_connection.sfd, csp->cfd);
3959 log_error(LOG_LEVEL_CLF,
3960 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3964 log_error(LOG_LEVEL_ERROR,
3965 "No server or forwarder response received on socket %d.",
3966 csp->server_connection.sfd);
3967 send_crunch_response(csp, error_response(csp, "no-server-data"));
3969 free_http_request(http);
3970 mark_server_socket_tainted(csp);
3971 #ifdef FEATURE_HTTPS_INSPECTION
3972 close_client_and_server_ssl_connections(csp);
3977 if (!csp->headers->first->str)
3979 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3981 assert(csp->headers->first->str);
3983 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3984 strncmpic(csp->headers->first->str, "ICY", 3))
3987 * It doesn't look like a HTTP (or Shoutcast) response:
3988 * tell the client and log the problem.
3990 if (strlen(csp->headers->first->str) > 30)
3992 csp->headers->first->str[30] = '\0';
3994 log_error(LOG_LEVEL_ERROR,
3995 "Invalid server or forwarder response. Starts with: %s",
3996 csp->headers->first->str);
3997 log_error(LOG_LEVEL_CLF,
3998 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3999 #ifdef FEATURE_HTTPS_INSPECTION
4001 * Sending data with standard or secured connection (HTTP/HTTPS)
4003 if (client_use_ssl(csp))
4005 ssl_send_data_delayed(&(csp->ssl_client_attr),
4006 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4007 strlen(INVALID_SERVER_HEADERS_RESPONSE),
4008 get_write_delay(csp));
4011 #endif /* def FEATURE_HTTPS_INSPECTION */
4013 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4014 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4016 free_http_request(http);
4017 mark_server_socket_tainted(csp);
4018 #ifdef FEATURE_HTTPS_INSPECTION
4019 close_client_and_server_ssl_connections(csp);
4025 * Disable redirect checkers, so that they will be only run
4026 * again if the user also enables them through tags.
4028 * From a performance point of view it doesn't matter,
4029 * but it prevents duplicated log messages.
4031 #ifdef FEATURE_FAST_REDIRECTS
4032 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
4034 csp->action->flags &= ~ACTION_REDIRECT;
4037 * We have now received the entire server header,
4038 * filter it and send the result to the client
4040 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
4042 log_error(LOG_LEVEL_CLF,
4043 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4044 #ifdef FEATURE_HTTPS_INSPECTION
4046 * Sending data with standard or secured connection (HTTP/HTTPS)
4048 if (client_use_ssl(csp))
4050 ssl_send_data_delayed(&(csp->ssl_client_attr),
4051 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4052 strlen(INVALID_SERVER_HEADERS_RESPONSE),
4053 get_write_delay(csp));
4058 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4059 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4061 free_http_request(http);
4062 mark_server_socket_tainted(csp);
4063 #ifdef FEATURE_HTTPS_INSPECTION
4064 close_client_and_server_ssl_connections(csp);
4069 if ((csp->flags & CSP_FLAG_CHUNKED)
4070 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET))
4073 size_t encoded_size = (size_t)(csp->iob->eod - csp->iob->cur);
4075 rc = get_bytes_missing_from_chunked_data(csp->iob->cur, encoded_size,
4081 chunk_offset = (size_t)rc;
4083 if (chunked_data_is_complete(csp->iob->cur, encoded_size, chunk_offset))
4085 log_error(LOG_LEVEL_CONNECT,
4086 "Looks like we got the last chunk together with "
4087 "the server headers. We better stop reading.");
4088 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
4089 csp->expected_content_length = byte_count;
4090 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
4094 csp->server_connection.response_received = time(NULL);
4096 if (crunch_response_triggered(csp, crunchers_light))
4099 * One of the tags created by a server-header
4100 * tagger triggered a crunch. We already
4101 * delivered the crunch response to the client
4102 * and are done here after cleaning up.
4104 mark_server_socket_tainted(csp);
4105 #ifdef FEATURE_HTTPS_INSPECTION
4106 close_client_and_server_ssl_connections(csp);
4111 /* Buffer and pcrs filter this if appropriate. */
4112 buffer_and_filter_content = content_requires_filtering(csp);
4114 if (!buffer_and_filter_content)
4117 * Write the server's (modified) header to
4118 * the client (along with anything else that
4119 * may be in the buffer). Use standard or secured
4122 if (send_server_headers(csp))
4126 #ifdef FEATURE_HTTPS_INSPECTION
4127 if (client_use_ssl(csp))
4129 if ((len = ssl_flush_socket(&(csp->ssl_client_attr),
4132 log_error(LOG_LEVEL_CONNECT,
4133 "Sending buffered bytes to the client failed");
4136 * The write failed, so don't bother mentioning it
4137 * to the client... it probably can't hear us anyway.
4139 mark_server_socket_tainted(csp);
4140 #ifdef FEATURE_HTTPS_INSPECTION
4141 close_client_and_server_ssl_connections(csp);
4147 #endif /* def FEATURE_HTTPS_INSPECTION */
4149 if ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
4151 log_error(LOG_LEVEL_ERROR,
4152 "Sending buffered bytes to the client failed.");
4154 * The write failed, so don't bother mentioning it
4155 * to the client... it probably can't hear us anyway.
4157 mark_server_socket_tainted(csp);
4161 if (csp->flags & CSP_FLAG_CHUNKED &&
4162 !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET))
4165 * In case of valid data we shouldn't flush more
4166 * data than chunk_offset but the data may be invalid.
4168 if (chunk_offset >= len)
4170 log_error(LOG_LEVEL_CONNECT,
4171 "Reducing chunk offset from %lu to %lu after flushing %ld bytes",
4172 chunk_offset, (chunk_offset - (unsigned)len), len);
4173 chunk_offset = chunk_offset - (unsigned)len;
4177 log_error(LOG_LEVEL_CONNECT,
4178 "Keeping chunk offset at %lu despite flushing %ld bytes",
4181 * If we can't parse the chunk-encoded data we should
4182 * not reuse the server connection.
4184 mark_server_socket_tainted(csp);
4189 /* we're finished with the server's header */
4194 * If this was a MS IIS/5 hack then it means the server
4195 * has already closed the connection. Nothing more to read.
4200 log_error(LOG_LEVEL_ERROR,
4201 "Closed server connection detected. "
4202 "Applying the MS IIS5 hack didn't help.");
4203 log_error(LOG_LEVEL_CLF,
4204 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4205 #ifdef FEATURE_HTTPS_INSPECTION
4207 * Sending data with standard or secured connection (HTTP/HTTPS)
4209 if (client_use_ssl(csp))
4211 ssl_send_data_delayed(&(csp->ssl_client_attr),
4212 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4213 strlen(INVALID_SERVER_HEADERS_RESPONSE),
4214 get_write_delay(csp));
4217 #endif /* def FEATURE_HTTPS_INSPECTION */
4219 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4220 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4222 mark_server_socket_tainted(csp);
4223 #ifdef FEATURE_HTTPS_INSPECTION
4224 close_client_and_server_ssl_connections(csp);
4231 mark_server_socket_tainted(csp);
4232 #ifdef FEATURE_HTTPS_INSPECTION
4233 close_client_and_server_ssl_connections(csp);
4235 return; /* huh? we should never get here */
4238 if (csp->content_length == 0)
4241 * If Privoxy didn't recalculate the Content-Length,
4242 * byte_count is still correct.
4244 csp->content_length = byte_count;
4247 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4248 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4249 && (csp->expected_content_length != byte_count))
4251 log_error(LOG_LEVEL_CONNECT,
4252 "Received %llu bytes while expecting %llu.",
4253 byte_count, csp->expected_content_length);
4254 mark_server_socket_tainted(csp);
4258 #ifdef FEATURE_HTTPS_INSPECTION
4259 if (client_use_ssl(csp))
4261 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4262 csp->ip_addr_str, http->gpc, http->hostport, http->path,
4263 http->version, csp->content_length);
4268 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4269 csp->ip_addr_str, http->ocmd, csp->content_length);
4271 csp->server_connection.timestamp = time(NULL);
4275 /*********************************************************************
4279 * Description : Once a connection from the client has been accepted,
4280 * this function is called (via serve()) to handle the
4281 * main business of the communication. This function
4282 * returns after dealing with a single request. It can
4283 * be called multiple times with the same client socket
4284 * if the client is keeping the connection alive.
4286 * The decision whether or not a client connection will
4287 * be kept alive is up to the caller which also must
4288 * close the client socket when done.
4290 * FIXME: chat is nearly thousand lines long.
4294 * 1 : csp = Current client state (buffers, headers, etc...)
4296 * Returns : Nothing.
4298 *********************************************************************/
4299 static void chat(struct client_state *csp)
4301 const struct forward_spec *fwd;
4302 struct http_request *http;
4303 /* Skeleton for HTTP response, if we should intercept the request */
4304 struct http_response *rsp;
4305 #ifdef FEATURE_HTTPS_INSPECTION
4306 int use_ssl_tunnel = 0;
4311 if (receive_client_request(csp) != JB_ERR_OK)
4316 #if defined(FEATURE_STATISTICS) && defined(MUTEX_LOCKS_AVAILABLE)
4317 privoxy_mutex_lock(&block_statistics_mutex);
4318 number_of_requests_received++;
4319 privoxy_mutex_unlock(&block_statistics_mutex);
4322 if (parse_client_request(csp) != JB_ERR_OK)
4327 #ifdef FEATURE_HTTPS_INSPECTION
4329 * Setting flags to use old solution with SSL tunnel and to disable
4330 * certificate verification.
4332 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4333 && !cgi_page_requested(csp->http->host))
4338 if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4340 csp->dont_verify_certificate = 1;
4345 * build the http request to send to the server
4346 * we have to do one of the following:
4348 * create = use the original HTTP request to create a new
4349 * HTTP request that has either the path component
4350 * without the http://domainspec (w/path) or the
4351 * full orininal URL (w/url)
4352 * Note that the path and/or the HTTP version may
4353 * have been altered by now.
4355 * SSL proxy = Open a socket to the host:port of the server
4356 * and create TLS/SSL connection with server and
4357 * with client. Then behave like mediator between
4358 * client and server over TLS/SSL.
4360 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4361 * with request to a parent proxy. Note that we'll be sending
4362 * forwarding the CFAIL message ourselves if connecting to the parent
4363 * fails, but we won't send a CSUCCEED message if it works,
4364 * since that would result in a double message (ours and the
4365 * parent's). After sending the request to the parent, we
4366 * must parse answer and send it to client. If connection
4367 * with server is established, we do TLS/SSL proxy. Otherwise
4368 * we send parent response to client and close connections.
4370 * here's the matrix:
4373 * +--------+--------+
4375 * 0 | create | SSL |
4376 * | w/path | proxy |
4377 * Forwarding +--------+--------+
4379 * 1 | create | proxy |
4380 * | w/url |+forward|
4381 * +--------+--------+
4385 #ifdef FEATURE_HTTPS_INSPECTION
4387 * Presetting SSL client and server flags
4389 if (http->ssl && !use_ssl_tunnel)
4391 http->client_ssl = 1;
4392 http->server_ssl = 1;
4396 http->client_ssl = 0;
4397 http->server_ssl = 0;
4401 #ifdef FEATURE_HTTPS_INSPECTION
4403 * Log the request unless we're https inspecting
4404 * in which case we don't have the path yet and
4405 * will log the request later.
4407 if (!client_use_ssl(csp))
4410 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4413 if (http->ssl && connect_port_is_forbidden(csp))
4415 const char *acceptable_connect_ports =
4416 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4417 assert(NULL != acceptable_connect_ports);
4418 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4419 "limit-connect{%s} doesn't allow CONNECT requests to %s",
4420 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4421 csp->action->flags |= ACTION_BLOCK;
4423 #ifdef FEATURE_HTTPS_INSPECTION
4424 http->client_ssl = 0;
4425 http->server_ssl = 0;
4430 * We have a request. Check if one of the crunchers wants it
4431 * unless the client wants to use TLS/SSL in which case we
4432 * haven't setup the TLS context yet and will send the crunch
4436 #ifdef FEATURE_HTTPS_INSPECTION
4437 !client_use_ssl(csp) &&
4439 crunch_response_triggered(csp, crunchers_all))
4442 * Yes. The client got the crunch response and we're done here.
4447 #ifdef FEATURE_HTTPS_INSPECTION
4448 if (client_use_ssl(csp) && !use_ssl_tunnel)
4452 * Creating a SSL proxy.
4454 * By sending the CSUCCEED message we're lying to the client as
4455 * the connection hasn't actually been established yet. We don't
4456 * establish the connection until we have seen and parsed the
4457 * encrypted client headers.
4459 if (write_socket_delayed(csp->cfd, CSUCCEED,
4460 strlen(CSUCCEED), get_write_delay(csp)) != 0)
4462 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4466 ret = create_client_ssl_connection(csp);
4469 log_error(LOG_LEVEL_ERROR,
4470 "Failed to open a secure connection with the client");
4473 if (JB_ERR_OK != process_encrypted_request_headers(csp))
4475 close_client_ssl_connection(csp);
4479 * We have an encrypted request. Check if one of the crunchers now
4480 * wants it (for example because the previously invisible path was
4481 * required to match).
4483 if (crunch_response_triggered(csp, crunchers_all))
4486 * Yes. The client got the crunch response and we're done here.
4493 /* If we need to apply client body filters, buffer the whole request now. */
4494 if (csp->expected_client_content_length != 0 &&
4495 (client_body_filters_enabled(csp->action) ||
4496 client_body_taggers_enabled(csp->action)) &&
4497 can_buffer_request_body(csp))
4499 int content_modified;
4500 size_t modified_content_length;
4502 #ifdef FEATURE_HTTPS_INSPECTION
4503 if (client_use_ssl(csp) && read_https_request_body(csp))
4505 log_error(LOG_LEVEL_ERROR, "Failed to buffer the encrypted "
4506 "request body to apply filters or taggers.");
4507 log_error(LOG_LEVEL_CLF,
4508 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, csp->http->cmd);
4510 ssl_send_data_delayed(&(csp->ssl_client_attr),
4511 (const unsigned char *)CLIENT_BODY_BUFFER_ERROR_RESPONSE,
4512 strlen(CLIENT_BODY_BUFFER_ERROR_RESPONSE),
4513 get_write_delay(csp));
4519 if (read_http_request_body(csp))
4521 log_error(LOG_LEVEL_ERROR,
4522 "Failed to buffer the request body to apply filters or taggers,");
4523 log_error(LOG_LEVEL_CLF,
4524 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, csp->http->cmd);
4526 write_socket_delayed(csp->cfd, CLIENT_BODY_BUFFER_ERROR_RESPONSE,
4527 strlen(CLIENT_BODY_BUFFER_ERROR_RESPONSE), get_write_delay(csp));
4531 if (client_body_taggers_enabled(csp->action))
4533 execute_client_body_taggers(csp, csp->expected_client_content_length);
4534 if (crunch_response_triggered(csp, crunchers_all))
4537 * Yes. The client got the crunch response and we're done here.
4542 if (client_body_filters_enabled(csp->action))
4544 modified_content_length = csp->expected_client_content_length;
4545 content_modified = execute_client_body_filters(csp,
4546 &modified_content_length);
4547 if ((content_modified == 1) &&
4548 (modified_content_length != csp->expected_client_content_length) &&
4549 update_client_headers(csp, modified_content_length))
4551 /* XXX: Send error response */
4552 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
4556 csp->expected_client_content_length = 0;
4559 log_applied_actions(csp->action);
4561 /* decide how to route the HTTP request */
4562 fwd = forward_url(csp, http);
4564 freez(csp->headers->first->str);
4565 build_request_line(csp, fwd, &csp->headers->first->str);
4567 if (fwd->forward_host)
4569 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4570 fwd->forward_host, fwd->forward_port, http->hostport);
4574 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4577 /* here we connect to the server, gateway, or the forwarder */
4579 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4580 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4581 && socket_is_still_alive(csp->server_connection.sfd)
4582 && connection_destination_matches(&csp->server_connection, http, fwd))
4584 log_error(LOG_LEVEL_CONNECT,
4585 "Reusing server socket %d connected to %s. Total requests: %u.",
4586 csp->server_connection.sfd, csp->server_connection.host,
4587 csp->server_connection.requests_sent_total);
4591 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4593 #ifdef FEATURE_CONNECTION_SHARING
4594 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4595 #ifdef FEATURE_HTTPS_INSPECTION
4596 && !server_use_ssl(csp)
4600 remember_connection(&csp->server_connection);
4603 #endif /* def FEATURE_CONNECTION_SHARING */
4605 log_error(LOG_LEVEL_CONNECT,
4606 "Closing server socket %d connected to %s. Total requests: %u.",
4607 csp->server_connection.sfd, csp->server_connection.host,
4608 csp->server_connection.requests_sent_total);
4609 close_socket(csp->server_connection.sfd);
4611 mark_connection_closed(&csp->server_connection);
4613 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4616 * Connecting to destination server
4618 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4620 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4622 if (fwd->type != SOCKS_NONE)
4625 rsp = error_response(csp, "forwarding-failed");
4627 else if (errno == EINVAL)
4629 rsp = error_response(csp, "no-such-domain");
4633 rsp = error_response(csp, "connect-failed");
4636 /* Write the answer to the client */
4639 send_crunch_response(csp, rsp);
4643 * Temporary workaround to prevent already-read client
4644 * bodies from being parsed as new requests. For now we
4645 * err on the safe side and throw all the following
4646 * requests under the bus, even if no client body has been
4647 * buffered. A compliant client will repeat the dropped
4648 * requests on an untainted connection.
4650 * The proper fix is to discard the no longer needed
4651 * client body in the buffer (if there is one) and to
4652 * continue parsing the bytes that follow.
4654 #ifdef FEATURE_HTTPS_INSPECTION
4655 close_client_ssl_connection(csp);
4657 drain_and_close_socket(csp->cfd);
4658 csp->cfd = JB_INVALID_SOCKET;
4663 #ifdef FEATURE_HTTPS_INSPECTION
4665 * Creating TLS/SSL connections with destination server or parent
4666 * proxy. If forwarding is enabled, we must send client request to
4667 * parent proxy and receive, parse and resend parent proxy answer.
4669 if (http->ssl && !use_ssl_tunnel)
4671 if (fwd->forward_host != NULL)
4673 char server_response[BUFFER_SIZE];
4676 char *hdr = list_to_text(csp->headers);
4677 memset(server_response, 0, sizeof(server_response));
4681 log_error(LOG_LEVEL_FATAL,
4682 "Out of memory parsing client header");
4684 list_remove_all(csp->headers);
4687 * Sending client's CONNECT request to the parent proxy
4689 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4695 log_error(LOG_LEVEL_CONNECT,
4696 "Sending request headers to: %s failed", http->hostport);
4697 mark_server_socket_tainted(csp);
4698 close_client_ssl_connection(csp);
4702 /* Waiting for parent proxy server response */
4703 len = read_socket(csp->server_connection.sfd, server_response,
4704 sizeof(server_response)-1);
4708 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4709 "server on socket %d.", csp->server_connection.sfd);
4711 rsp = error_response(csp, "no-server-data");
4714 send_crunch_response(csp, rsp);
4716 mark_server_socket_tainted(csp);
4717 close_client_ssl_connection(csp);
4722 * Test if the connection to the destination server was
4723 * established successfully by the parent proxy.
4725 if (!tunnel_established_successfully(server_response, (unsigned int)len))
4727 log_error(LOG_LEVEL_ERROR,
4728 "The forwarder %s failed to establish a connection with %s",
4729 fwd->forward_host, http->host);
4730 rsp = error_response(csp, "connect-failed");
4733 send_crunch_response(csp, rsp);
4735 mark_server_socket_tainted(csp);
4736 close_client_ssl_connection(csp);
4739 } /* -END- if (fwd->forward_host != NULL) */
4742 * We can now create the TLS/SSL connection with the destination server.
4744 int ret = create_server_ssl_connection(csp);
4747 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4748 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4751 * If the server certificate is invalid, we must inform
4752 * the client and then close connection to the client.
4754 ssl_send_certificate_error(csp);
4755 close_client_and_server_ssl_connections(csp);
4758 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4759 || csp->server_cert_verification_result == SSL_CERT_VALID)
4762 * The TLS/SSL connection wasn't created but an invalid
4763 * certificate wasn't detected. Report it as connection
4766 rsp = error_response(csp, "connect-failed");
4769 send_crunch_response(csp, rsp);
4771 close_client_and_server_ssl_connections(csp);
4775 }/* -END- if (http->ssl) */
4776 #endif /* def FEATURE_HTTPS_INSPECTION */
4778 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4779 save_connection_destination(csp->server_connection.sfd,
4780 http, fwd, &csp->server_connection);
4781 csp->server_connection.keep_alive_timeout =
4782 (unsigned)csp->config->keep_alive_timeout;
4784 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4786 csp->server_connection.requests_sent_total++;
4788 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4790 /* Client headers have been sent optimistically */
4791 assert(csp->headers->last == NULL);
4793 else if (http->ssl == 0 || (fwd->forward_host
4794 #ifdef FEATURE_HTTPS_INSPECTION
4799 int status = send_http_request(csp);
4802 /* The request got crunched, a response has been delivered. */
4807 rsp = error_response(csp, "connect-failed");
4810 send_crunch_response(csp, rsp);
4818 * Using old solution with SSL tunnel or new solution with SSL proxy
4820 list_remove_all(csp->headers);
4821 #ifdef FEATURE_HTTPS_INSPECTION
4826 * We're running an SSL tunnel and we're not forwarding,
4827 * so just ditch the client headers, send the "connect succeeded"
4828 * message to the client, flush the rest, and get out of the way.
4830 if (write_socket_delayed(csp->cfd, CSUCCEED,
4831 strlen(CSUCCEED), get_write_delay(csp)))
4836 #ifdef FEATURE_HTTPS_INSPECTION
4840 * If server certificate has been verified and is invalid,
4841 * we must inform the client and then close the connection
4842 * with client and server.
4844 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4845 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4847 ssl_send_certificate_error(csp);
4848 close_client_and_server_ssl_connections(csp);
4851 if (send_https_request(csp))
4853 rsp = error_response(csp, "connect-failed");
4856 send_crunch_response(csp, rsp);
4858 close_client_and_server_ssl_connections(csp);
4862 #endif /* def FEATURE_HTTPS_INSPECTION */
4863 clear_iob(csp->client_iob);
4864 }/* -END- else ... if (http->ssl == 1) */
4866 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4868 /* XXX: should the time start earlier for optimistically sent data? */
4869 csp->server_connection.request_sent = time(NULL);
4871 handle_established_connection(csp);
4872 freez(csp->receive_buffer);
4877 /*********************************************************************
4879 * Function : fuzz_server_response
4881 * Description : Treat the input as a whole server response.
4884 * 1 : csp = Current client state (buffers, headers, etc...)
4885 * 2 : fuzz_input_file = File to read the input from.
4889 *********************************************************************/
4890 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4892 static struct forward_spec fwd; /* Zero'd due to being static */
4895 if (strcmp(fuzz_input_file, "-") == 0)
4897 /* XXX: Doesn't work yet. */
4898 csp->server_connection.sfd = 0;
4902 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4903 if (csp->server_connection.sfd == -1)
4905 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4910 csp->content_type |= CT_GIF;
4911 csp->action->flags |= ACTION_DEANIMATE;
4912 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4914 csp->http->path = strdup_or_die("/");
4915 csp->http->host = strdup_or_die("fuzz.example.org");
4916 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4917 /* Prevent client socket monitoring */
4918 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4919 csp->flags |= CSP_FLAG_CHUNKED;
4921 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4922 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4924 csp->content_type |= CT_DECLARED|CT_GIF;
4926 csp->config->socket_timeout = 0;
4928 cgi_init_error_messages();
4930 handle_established_connection(csp);
4931 freez(csp->receive_buffer);
4938 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4939 /*********************************************************************
4941 * Function : prepare_csp_for_next_request
4943 * Description : Put the csp in a mostly vergin state.
4946 * 1 : csp = Current client state (buffers, headers, etc...)
4950 *********************************************************************/
4951 static void prepare_csp_for_next_request(struct client_state *csp)
4953 csp->content_type = 0;
4954 csp->content_length = 0;
4955 csp->expected_content_length = 0;
4956 csp->expected_client_content_length = 0;
4957 list_remove_all(csp->headers);
4958 clear_iob(csp->iob);
4959 freez(csp->error_message);
4960 free_http_request(csp->http);
4961 destroy_list(csp->headers);
4962 #ifdef FEATURE_HTTPS_INSPECTION
4963 destroy_list(csp->https_headers);
4965 destroy_list(csp->tags);
4966 #ifdef FEATURE_CLIENT_TAGS
4967 destroy_list(csp->client_tags);
4968 freez(csp->client_address);
4970 free_current_action(csp->action);
4971 if (NULL != csp->fwd)
4973 unload_forward_spec(csp->fwd);
4976 /* XXX: Store per-connection flags someplace else. */
4977 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4978 #ifdef FEATURE_TOGGLE
4979 if (global_toggle_state)
4980 #endif /* def FEATURE_TOGGLE */
4982 csp->flags |= CSP_FLAG_TOGGLED_ON;
4985 if (csp->client_iob->eod > csp->client_iob->cur)
4987 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4988 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4990 assert(bytes_to_shift > 0);
4991 assert(data_length > 0);
4993 log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4994 data_length, bytes_to_shift);
4995 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4996 csp->client_iob->cur = csp->client_iob->buf;
4997 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4998 csp->client_iob->eod = csp->client_iob->buf + data_length;
4999 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
5001 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
5006 * We mainly care about resetting client_iob->cur so we don't
5007 * waste buffer space at the beginning and don't mess up the
5008 * request restoration done by cgi_show_request().
5010 * Freeing the buffer itself isn't technically necessary,
5011 * but makes debugging more convenient.
5013 clear_iob(csp->client_iob);
5016 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
5019 /*********************************************************************
5023 * Description : This is little more than chat. We only "serve" to
5024 * to close (or remember) any socket that chat may have
5028 * 1 : csp = Current client state (buffers, headers, etc...)
5032 *********************************************************************/
5033 static void serve(struct client_state *csp)
5035 int config_file_change_detected = 0; /* Only used for debugging */
5036 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
5037 #ifdef FEATURE_CONNECTION_SHARING
5038 static int monitor_thread_running = 0;
5039 #endif /* def FEATURE_CONNECTION_SHARING */
5040 int continue_chatting = 0;
5042 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
5043 csp->ip_addr_str, csp->cfd);
5047 unsigned int latency;
5049 #ifdef FEATURE_HTTPS_INSPECTION
5050 if (continue_chatting && client_use_ssl(csp))
5052 continue_https_chat(csp);
5061 * If the request has been crunched,
5062 * the calculated latency is zero.
5064 latency = (unsigned)(csp->server_connection.response_received -
5065 csp->server_connection.request_sent) / 2;
5067 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
5068 && (csp->flags & CSP_FLAG_CRUNCHED)
5069 && (csp->expected_client_content_length != 0))
5071 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
5072 log_error(LOG_LEVEL_CONNECT,
5073 "Tainting client socket %d due to unread data.", csp->cfd);
5076 continue_chatting = (csp->config->feature_flags
5077 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
5078 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
5079 && (csp->cfd != JB_INVALID_SOCKET)
5080 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
5081 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
5082 || (csp->flags & CSP_FLAG_CHUNKED));
5084 if (!(csp->flags & CSP_FLAG_CRUNCHED)
5085 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
5087 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
5089 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
5091 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
5092 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
5093 || !socket_is_still_alive(csp->server_connection.sfd)
5094 || !(latency < csp->server_connection.keep_alive_timeout))
5096 log_error(LOG_LEVEL_CONNECT,
5097 "Closing server socket %d connected to %s. "
5098 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
5099 csp->server_connection.sfd, (csp->server_connection.host != NULL) ?
5100 csp->server_connection.host : csp->http->host,
5101 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
5102 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
5103 socket_is_still_alive(csp->server_connection.sfd),
5104 csp->server_connection.keep_alive_timeout);
5105 #ifdef FEATURE_CONNECTION_SHARING
5106 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5108 forget_connection(csp->server_connection.sfd);
5110 #endif /* def FEATURE_CONNECTION_SHARING */
5111 #ifdef FEATURE_HTTPS_INSPECTION
5112 close_server_ssl_connection(csp);
5114 close_socket(csp->server_connection.sfd);
5115 mark_connection_closed(&csp->server_connection);
5116 #ifdef FEATURE_HTTPS_INSPECTION
5117 if (continue_chatting && client_use_ssl(csp))
5120 * Close the client socket as well as Privoxy currently
5121 * can't establish a new server connection when the client
5122 * socket is reused and would drop the connection in
5123 * continue_https_chat() anyway.
5125 continue_chatting = 0;
5126 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
5127 log_error(LOG_LEVEL_CONNECT,
5128 "Client socket %d is no longer usable. "
5129 "The server socket has been closed.", csp->cfd);
5135 if (continue_chatting && any_loaded_file_changed(csp))
5137 continue_chatting = 0;
5138 config_file_change_detected = 1;
5140 #ifdef FEATURE_HTTPS_INSPECTION
5141 if (continue_chatting && client_use_ssl(csp) &&
5142 csp->ssl_with_client_is_opened == 0)
5144 continue_chatting = 0;
5145 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
5146 "The TLS session has been terminated.", csp->cfd);
5150 if (continue_chatting)
5152 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
5153 && socket_is_still_alive(csp->cfd))
5155 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
5156 "pipelined on socket %d and the socket is still alive.",
5157 csp->requests_received_total+1, csp->cfd);
5158 prepare_csp_for_next_request(csp);
5162 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
5164 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5166 log_error(LOG_LEVEL_CONNECT,
5167 "Waiting for the next client request on socket %d. "
5168 "Keeping the server socket %d to %s open.",
5169 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
5173 log_error(LOG_LEVEL_CONNECT,
5174 "Waiting for the next client request on socket %d. "
5175 "No server socket to keep open.", csp->cfd);
5179 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
5180 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
5181 && socket_is_still_alive(csp->cfd))
5183 log_error(LOG_LEVEL_CONNECT,
5184 "Data arrived in time on client socket %d. Requests so far: %u",
5185 csp->cfd, csp->requests_received_total);
5186 prepare_csp_for_next_request(csp);
5190 #ifdef FEATURE_CONNECTION_SHARING
5191 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5192 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
5193 && (socket_is_still_alive(csp->server_connection.sfd))
5194 #ifdef FEATURE_HTTPS_INSPECTION
5195 && !server_use_ssl(csp)
5199 time_t time_open = time(NULL) - csp->server_connection.timestamp;
5201 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
5206 remember_connection(&csp->server_connection);
5207 csp->server_connection.sfd = JB_INVALID_SOCKET;
5208 drain_and_close_socket(csp->cfd);
5209 csp->cfd = JB_INVALID_SOCKET;
5210 privoxy_mutex_lock(&connection_reuse_mutex);
5211 if (!monitor_thread_running)
5213 monitor_thread_running = 1;
5214 privoxy_mutex_unlock(&connection_reuse_mutex);
5215 wait_for_alive_connections();
5216 privoxy_mutex_lock(&connection_reuse_mutex);
5217 monitor_thread_running = 0;
5219 privoxy_mutex_unlock(&connection_reuse_mutex);
5221 #endif /* def FEATURE_CONNECTION_SHARING */
5225 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5227 log_error(LOG_LEVEL_CONNECT,
5228 "Closing server socket %d connected to %s. Keep-alive: %u. "
5229 "Tainted: %u. Socket alive: %u. Timeout: %u. "
5230 "Configuration file change detected: %u",
5231 csp->server_connection.sfd, csp->server_connection.host,
5232 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
5233 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
5234 socket_is_still_alive(csp->server_connection.sfd),
5235 csp->server_connection.keep_alive_timeout,
5236 config_file_change_detected);
5238 } while (continue_chatting);
5242 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
5244 if (csp->cfd != JB_INVALID_SOCKET)
5246 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
5247 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
5248 "Configuration file change detected: %u. Requests received: %u.",
5249 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
5250 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
5251 config_file_change_detected, csp->requests_received_total);
5252 #ifdef FEATURE_HTTPS_INSPECTION
5253 close_client_ssl_connection(csp);
5255 drain_and_close_socket(csp->cfd);
5258 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5260 #ifdef FEATURE_CONNECTION_SHARING
5261 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5263 forget_connection(csp->server_connection.sfd);
5265 #endif /* def FEATURE_CONNECTION_SHARING */
5267 #ifdef FEATURE_HTTPS_INSPECTION
5268 close_server_ssl_connection(csp);
5269 #endif /* def FEATURE_HTTPS_INSPECTION */
5271 close_socket(csp->server_connection.sfd);
5274 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
5275 mark_connection_closed(&csp->server_connection);
5278 free_csp_resources(csp);
5280 csp->flags &= ~CSP_FLAG_ACTIVE;
5286 /*********************************************************************
5288 * Function : server_thread
5290 * Description : We only exist to call `serve' in a threaded environment.
5293 * 1 : data = Current client state (buffers, headers, etc...)
5295 * Returns : Always 0.
5297 *********************************************************************/
5298 static int32 server_thread(void *data)
5300 serve((struct client_state *) data);
5307 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5308 /*********************************************************************
5312 * Description : Print usage info & exit.
5314 * Parameters : Pointer to argv[0] for identifying ourselves
5318 *********************************************************************/
5319 static void usage(const char *name)
5321 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
5322 "Usage: %s [--config-test] "
5325 #endif /* defined(unix) */
5328 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
5329 #endif /* defined(unix) */
5330 "[--version] [configfile]\n",
5334 show_fuzz_usage(name);
5337 printf("Aborting\n");
5342 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5345 #ifdef MUTEX_LOCKS_AVAILABLE
5346 /*********************************************************************
5348 * Function : privoxy_mutex_lock
5350 * Description : Locks a mutex.
5353 * 1 : mutex = The mutex to lock.
5355 * Returns : Void. May exit in case of errors.
5357 *********************************************************************/
5358 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5360 #ifdef FEATURE_PTHREAD
5361 int err = pthread_mutex_lock(mutex);
5364 if (mutex != &log_mutex)
5366 log_error(LOG_LEVEL_FATAL,
5367 "Mutex locking failed: %s.\n", strerror(err));
5372 EnterCriticalSection(mutex);
5373 #endif /* def FEATURE_PTHREAD */
5377 /*********************************************************************
5379 * Function : privoxy_mutex_unlock
5381 * Description : Unlocks a mutex.
5384 * 1 : mutex = The mutex to unlock.
5386 * Returns : Void. May exit in case of errors.
5388 *********************************************************************/
5389 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5391 #ifdef FEATURE_PTHREAD
5392 int err = pthread_mutex_unlock(mutex);
5395 if (mutex != &log_mutex)
5397 log_error(LOG_LEVEL_FATAL,
5398 "Mutex unlocking failed: %s.\n", strerror(err));
5403 LeaveCriticalSection(mutex);
5404 #endif /* def FEATURE_PTHREAD */
5408 /*********************************************************************
5410 * Function : privoxy_mutex_init
5412 * Description : Prepares a mutex.
5415 * 1 : mutex = The mutex to initialize.
5417 * Returns : Void. May exit in case of errors.
5419 *********************************************************************/
5420 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5422 #ifdef FEATURE_PTHREAD
5423 int err = pthread_mutex_init(mutex, 0);
5426 printf("Fatal error. Mutex initialization failed: %s.\n",
5431 InitializeCriticalSection(mutex);
5432 #endif /* def FEATURE_PTHREAD */
5434 #endif /* def MUTEX_LOCKS_AVAILABLE */
5436 /*********************************************************************
5438 * Function : initialize_mutexes
5440 * Description : Prepares mutexes if mutex support is available.
5444 * Returns : Void, exits in case of errors.
5446 *********************************************************************/
5447 static void initialize_mutexes(void)
5449 #ifdef MUTEX_LOCKS_AVAILABLE
5451 * Prepare global mutex semaphores
5454 #ifdef FEATURE_HTTPS_INSPECTION
5455 privoxy_mutex_init(&certificate_mutex);
5456 privoxy_mutex_init(&ssl_init_mutex);
5459 privoxy_mutex_init(&log_mutex);
5460 privoxy_mutex_init(&log_init_mutex);
5461 privoxy_mutex_init(&connection_reuse_mutex);
5462 #ifdef FEATURE_EXTERNAL_FILTERS
5463 privoxy_mutex_init(&external_filter_mutex);
5465 #ifdef FEATURE_CLIENT_TAGS
5466 privoxy_mutex_init(&client_tags_mutex);
5468 #ifdef FEATURE_STATISTICS
5469 privoxy_mutex_init(&block_statistics_mutex);
5471 #ifdef FEATURE_EXTENDED_STATISTICS
5472 privoxy_mutex_init(&filter_statistics_mutex);
5473 privoxy_mutex_init(&block_reason_statistics_mutex);
5477 * XXX: The assumptions below are a bit naive
5478 * and can cause locks that aren't necessary.
5480 * For example older FreeBSD versions (< 6.x?)
5481 * have no gethostbyname_r, but gethostbyname is
5484 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5485 privoxy_mutex_init(&resolver_mutex);
5486 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5488 * XXX: should we use a single mutex for
5489 * localtime() and gmtime() as well?
5491 #ifndef HAVE_GMTIME_R
5492 privoxy_mutex_init(&gmtime_mutex);
5493 #endif /* ndef HAVE_GMTIME_R */
5495 #ifndef HAVE_LOCALTIME_R
5496 privoxy_mutex_init(&localtime_mutex);
5497 #endif /* ndef HAVE_GMTIME_R */
5499 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5500 privoxy_mutex_init(&rand_mutex);
5501 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5503 #endif /* def MUTEX_LOCKS_AVAILABLE */
5506 /*********************************************************************
5510 * Description : Load the config file and start the listen loop.
5511 * This function is a lot more *sane* with the `load_config'
5512 * and `listen_loop' functions; although it stills does
5513 * a *little* too much for my taste.
5516 * 1 : argc = Number of parameters (including $0).
5517 * 2 : argv = Array of (char *)'s to the parameters.
5519 * Returns : 1 if : can't open config file, unrecognized directive,
5520 * stats requested in multi-thread mode, can't open the
5521 * log file, can't open the jar file, listen port is invalid,
5522 * any load fails, and can't bind port.
5524 * Else main never returns, the process must be signaled
5525 * to terminate execution. Or, on Windows, use the
5526 * "File", "Exit" menu option.
5528 *********************************************************************/
5530 int real_main(int argc, char **argv)
5532 int main(int argc, char **argv)
5536 int do_config_test = 0;
5537 #ifndef HAVE_ARC4RANDOM
5538 unsigned int random_seed;
5541 struct passwd *pw = NULL;
5542 struct group *grp = NULL;
5544 char *pre_chroot_nslookup_to_load_resolver = NULL;
5547 char *fuzz_input_type = NULL;
5548 char *fuzz_input_file = NULL;
5555 #if !defined(_WIN32)
5562 /* Prepare mutexes if supported and necessary. */
5563 initialize_mutexes();
5565 /* Enable logging until further notice. */
5569 * Parse the command line arguments
5571 * XXX: simply printing usage information in case of
5572 * invalid arguments isn't particularly user friendly.
5574 while (++argc_pos < argc)
5577 /* Check to see if the service must be installed or uninstalled */
5578 if (strncmp(argv[argc_pos], "--install", 9) == 0)
5580 const char *pName = argv[argc_pos] + 9;
5583 exit((install_service(pName)) ? 0 : 1);
5585 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5587 const char *pName = argv[argc_pos] + 11;
5590 exit((uninstall_service(pName)) ? 0 : 1);
5592 else if (strcmp(argv[argc_pos], "--service") == 0)
5594 bRunAsService = TRUE;
5595 w32_set_service_cwd();
5596 atexit(w32_service_exit_notify);
5599 #endif /* defined(_WIN32) */
5602 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5604 if (strcmp(argv[argc_pos], "--help") == 0)
5609 else if (strcmp(argv[argc_pos], "--version") == 0)
5611 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5617 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5619 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5623 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5625 if (++argc_pos == argc) usage(argv[0]);
5626 pidfile = strdup_or_die(argv[argc_pos]);
5629 else if (strcmp(argv[argc_pos], "--user") == 0)
5634 if (++argc_pos == argc) usage(argv[argc_pos]);
5636 user_arg = strdup_or_die(argv[argc_pos]);
5637 group_name = strchr(user_arg, '.');
5638 if (NULL != group_name)
5640 /* Nul-terminate the user name */
5643 /* Skip the former delimiter to actually reach the group name */
5646 grp = getgrnam(group_name);
5649 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5652 pw = getpwnam(user_arg);
5655 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5661 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5663 if (++argc_pos == argc) usage(argv[0]);
5664 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5667 else if (strcmp(argv[argc_pos], "--chroot") == 0)
5671 #endif /* defined(unix) */
5673 else if (strcmp(argv[argc_pos], "--config-test") == 0)
5678 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5681 if (argc < argc_pos + 2) usage(argv[0]);
5682 fuzz_input_type = argv[argc_pos];
5684 fuzz_input_file = argv[argc_pos];
5686 else if (strcmp(argv[argc_pos], "--stfu") == 0)
5688 set_debug_level(LOG_LEVEL_STFU);
5691 else if (argc_pos + 1 != argc)
5694 * This is neither the last command line
5695 * option, nor was it recognized before,
5696 * therefore it must be invalid.
5702 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5704 configfile = argv[argc_pos];
5707 } /* -END- while (more arguments) */
5709 show_version(Argv[0]);
5712 if (*configfile != '/')
5714 char cwd[BUFFER_SIZE];
5716 size_t abs_file_size;
5718 /* make config-filename absolute here */
5719 if (NULL == getcwd(cwd, sizeof(cwd)))
5721 perror("failed to get current working directory");
5725 basedir = strdup_or_die(cwd);
5727 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5728 abs_file = malloc_or_die(abs_file_size);
5729 strlcpy(abs_file, basedir, abs_file_size);
5730 strlcat(abs_file, "/", abs_file_size);
5731 strlcat(abs_file, configfile, abs_file_size);
5732 configfile = abs_file;
5734 #endif /* defined unix */
5738 clients->next = NULL;
5740 /* XXX: factor out initialising after the next stable release. */
5745 #ifndef HAVE_ARC4RANDOM
5746 random_seed = (unsigned int)time(NULL);
5748 srandom(random_seed);
5751 #endif /* ifdef HAVE_RANDOM */
5752 #endif /* ifndef HAVE_ARC4RANDOM */
5755 * Unix signal handling
5757 * Catch the abort, interrupt and terminate signals for a graceful exit
5758 * Catch the hangup signal so the errlog can be reopened.
5760 * Ignore the broken pipe signal as connection failures
5761 * are handled when and where they occur without relying
5764 #if !defined(_WIN32)
5767 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5769 for (idx = 0; idx < SZ(catched_signals); idx++)
5771 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5772 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5774 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5775 #endif /* ifdef sun */
5777 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5781 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5783 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5787 #else /* ifdef _WIN32 */
5788 # ifdef _WIN_CONSOLE
5790 * We *are* in a windows console app.
5791 * Print a verbose messages about FAQ's and such
5793 printf("%s", win32_blurb);
5794 # endif /* def _WIN_CONSOLE */
5795 #endif /* def _WIN32 */
5798 if (fuzz_input_type != NULL)
5800 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5802 log_error(LOG_LEVEL_FATAL,
5803 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5804 "Various data structures are static which is unsafe when using threads.");
5809 exit(NULL == load_config());
5812 /* Initialize the CGI subsystem */
5813 cgi_init_error_messages();
5816 * If running on unix and without the --no-daemon
5817 * option, become a daemon. I.e. fork, detach
5818 * from tty and get process group leadership
5827 if (pid < 0) /* error */
5832 else if (pid != 0) /* parent */
5837 * must check for errors
5838 * child died due to missing files aso
5841 wpid = waitpid(pid, &status, WNOHANG);
5853 * stderr (fd 2) will be closed later on,
5854 * when the config file has been parsed.
5860 * Reserve fd 0 and 1 to prevent abort() and friends
5861 * from sending stuff to the clients or servers.
5863 fd = open("/dev/null", O_RDONLY);
5866 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5870 if (dup2(fd, 0) == -1)
5872 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5876 fd = open("/dev/null", O_WRONLY);
5879 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5883 if (dup2(fd, 1) == -1)
5885 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5890 #ifdef FEATURE_EXTERNAL_FILTERS
5891 for (fd = 0; fd < 3; fd++)
5893 mark_socket_for_close_on_execute(fd);
5897 if (chdir("/") != 0)
5899 log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5902 } /* -END- if (daemon_mode) */
5905 * As soon as we have written the PID file, we can switch
5906 * to the user and group ID indicated by the --user option
5908 if (pidfile != NULL)
5910 write_pid_file(pidfile);
5914 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5916 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5920 if (setgroups(1, &grp->gr_gid))
5922 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5925 else if (initgroups(pw->pw_name, pw->pw_gid))
5927 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5933 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5935 /* Read the time zone file from /etc before doing chroot. */
5937 if (NULL != pre_chroot_nslookup_to_load_resolver
5938 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5940 /* Initialize resolver library. */
5941 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5943 if (chroot(pw->pw_dir) < 0)
5945 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5949 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5952 if (setuid(pw->pw_uid))
5954 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5958 char putenv_dummy[64];
5960 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5961 if (putenv(putenv_dummy) != 0)
5963 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5966 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5967 if (putenv(putenv_dummy) != 0)
5969 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5975 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5978 #endif /* defined unix */
5981 /* This will be FALSE unless the command line specified --service
5985 /* Yup, so now we must attempt to establish a connection
5986 * with the service dispatcher. This will only work if this
5987 * process was launched by the service control manager to
5988 * actually run as a service. If this isn't the case, i've
5989 * known it take around 30 seconds or so for the call to return.
5992 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5993 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5995 /* Service has run, and at this point is now being stopped, so just return */
6000 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
6002 /* An error occurred. Usually it's because --service was wrongly specified
6003 * and we were unable to connect to the Service Control Dispatcher because
6004 * it wasn't expecting us and is therefore not listening.
6006 * For now, just continue below to call the listen_loop function.
6009 #endif /* def _WIN32 */
6019 /*********************************************************************
6021 * Function : bind_port_helper
6023 * Description : Bind the listen port. Handles logging, and aborts
6027 * 1 : haddr = Host address to bind to. Use NULL to bind to
6029 * 2 : hport = Specifies port to bind to.
6030 * 3 : backlog = Listen backlog.
6032 * Returns : Port that was opened.
6034 *********************************************************************/
6035 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
6040 result = bind_port(haddr, hport, backlog, &bfd);
6044 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
6048 log_error(LOG_LEVEL_FATAL,
6049 "can't bind to %s:%d: There may be another Privoxy "
6050 "or some other proxy running on port %d",
6051 bind_address, hport, hport);
6055 log_error(LOG_LEVEL_FATAL,
6056 "can't bind to %s:%d: The hostname is not resolvable",
6057 bind_address, hport);
6061 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
6062 bind_address, hport);
6066 /* shouldn't get here */
6067 return JB_INVALID_SOCKET;
6072 if (bfd >= FD_SETSIZE)
6074 log_error(LOG_LEVEL_FATAL,
6075 "Bind socket number too high to use select(): %d >= %d",
6083 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
6088 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
6096 /*********************************************************************
6098 * Function : bind_ports_helper
6100 * Description : Bind the listen ports. Handles logging, and aborts
6104 * 1 : config = Privoxy configuration. Specifies ports
6106 * 2 : sockets = Preallocated array of opened sockets
6107 * corresponding to specification in config.
6108 * All non-opened sockets will be set to
6109 * JB_INVALID_SOCKET.
6111 * Returns : Nothing. Inspect sockets argument.
6113 *********************************************************************/
6114 static void bind_ports_helper(struct configuration_spec * config,
6115 jb_socket sockets[])
6119 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
6121 if (config->hport[i])
6123 sockets[i] = bind_port_helper(config->haddr[i],
6124 config->hport[i], config->listen_backlog);
6125 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
6126 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
6128 struct accept_filter_arg af_options;
6129 bzero(&af_options, sizeof(af_options));
6130 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
6131 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
6132 sizeof(af_options)))
6134 log_error(LOG_LEVEL_ERROR,
6135 "Enabling accept filter for socket %d failed: %E", sockets[i]);
6142 sockets[i] = JB_INVALID_SOCKET;
6145 config->need_bind = 0;
6149 /*********************************************************************
6151 * Function : close_ports_helper
6153 * Description : Close listenings ports.
6156 * 1 : sockets = Array of opened and non-opened sockets to
6157 * close. All sockets will be set to
6158 * JB_INVALID_SOCKET.
6160 * Returns : Nothing.
6162 *********************************************************************/
6163 static void close_ports_helper(jb_socket sockets[])
6167 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
6169 if (JB_INVALID_SOCKET != sockets[i])
6171 close_socket(sockets[i]);
6173 sockets[i] = JB_INVALID_SOCKET;
6179 /* Without this simple workaround we get this compiler warning from _beginthread
6180 * warning C4028: formal parameter 1 different from declaration
6182 void w32_service_listen_loop(void *p)
6186 #endif /* def _WIN32 */
6189 /*********************************************************************
6191 * Function : listen_loop
6193 * Description : bind the listen port and enter a "FOREVER" listening loop.
6199 *********************************************************************/
6200 static void listen_loop(void)
6202 struct client_states *csp_list = NULL;
6203 struct client_state *csp = NULL;
6204 jb_socket bfds[MAX_LISTENING_SOCKETS];
6205 struct configuration_spec *config;
6206 unsigned int active_threads = 0;
6207 #if defined(FEATURE_PTHREAD)
6208 pthread_attr_t attrs;
6210 pthread_attr_init(&attrs);
6211 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
6214 config = load_config();
6216 #ifdef FEATURE_CONNECTION_SHARING
6218 * XXX: Should be relocated once it no
6219 * longer needs to emit log messages.
6221 initialize_reusable_connections();
6222 #endif /* def FEATURE_CONNECTION_SHARING */
6224 bind_ports_helper(config, bfds);
6226 #ifdef FEATURE_GRACEFUL_TERMINATION
6227 while (!g_terminate)
6232 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
6233 while (waitpid(-1, NULL, WNOHANG) > 0)
6235 /* zombie children */
6237 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
6240 * Free data that was used by died threads
6242 active_threads = sweep();
6246 * Re-open the errlog after HUP signal
6248 if (received_hup_signal)
6250 if (NULL != config->logfile)
6252 init_error_log(Argv[0], config->logfile);
6254 received_hup_signal = 0;
6258 csp_list = zalloc_or_die(sizeof(*csp_list));
6259 csp = &csp_list->csp;
6261 log_error(LOG_LEVEL_CONNECT,
6262 "Waiting for the next client connection. Currently active threads: %u",
6266 * This config may be outdated, but for accept_connection()
6267 * it's fresh enough.
6269 csp->config = config;
6271 if (!accept_connection(csp, bfds))
6273 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
6278 csp->flags |= CSP_FLAG_ACTIVE;
6279 csp->server_connection.sfd = JB_INVALID_SOCKET;
6281 csp->config = config = load_config();
6283 if (config->need_bind)
6286 * Since we were listening to the "old port", we will not see
6287 * a "listen" param change until the next request. So, at
6288 * least 1 more request must be made for us to find the new
6289 * setting. I am simply closing the old socket and binding the
6292 * Which-ever is correct, we will serve 1 more page via the
6293 * old settings. This should probably be a "show-status"
6294 * request. This should not be a so common of an operation
6295 * that this will hurt people's feelings.
6298 close_ports_helper(bfds);
6300 bind_ports_helper(config, bfds);
6303 #ifdef FEATURE_TOGGLE
6304 if (global_toggle_state)
6305 #endif /* def FEATURE_TOGGLE */
6307 csp->flags |= CSP_FLAG_TOGGLED_ON;
6310 if (run_loader(csp))
6312 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
6313 /* Never get here - LOG_LEVEL_FATAL causes program exit */
6317 if (block_acl(NULL,csp))
6319 log_error(LOG_LEVEL_CONNECT,
6320 "Connection from %s on %s (socket %d) dropped due to ACL",
6321 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
6322 close_socket(csp->cfd);
6323 freez(csp->ip_addr_str);
6324 freez(csp->listen_addr_str);
6328 #endif /* def FEATURE_ACL */
6330 if ((0 != config->max_client_connections)
6331 && (active_threads >= config->max_client_connections))
6333 log_error(LOG_LEVEL_ERROR,
6334 "Rejecting connection from %s. Maximum number of connections reached.",
6336 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6337 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6338 close_socket(csp->cfd);
6339 freez(csp->ip_addr_str);
6340 freez(csp->listen_addr_str);
6345 /* add it to the list of clients */
6346 csp_list->next = clients->next;
6347 clients->next = csp_list;
6349 if (config->multi_threaded)
6353 /* this is a switch () statement in the C preprocessor - ugh */
6354 #undef SELECTED_ONE_OPTION
6356 /* Use Pthreads in preference to native code */
6357 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6358 #define SELECTED_ONE_OPTION
6360 pthread_t the_thread;
6363 ret = pthread_create(&the_thread, &attrs,
6364 (void * (*)(void *))serve, csp);
6365 child_id = ret ? -1 : 0;
6369 #if defined(_WIN32) && !defined(SELECTED_ONE_OPTION)
6370 #define SELECTED_ONE_OPTION
6371 child_id = _beginthread(
6372 (void (*)(void *))serve,
6377 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6378 #define SELECTED_ONE_OPTION
6380 thread_id tid = spawn_thread
6381 (server_thread, "server", B_NORMAL_PRIORITY, csp);
6383 if ((tid >= 0) && (resume_thread(tid) == B_OK))
6385 child_id = (int) tid;
6394 #if !defined(SELECTED_ONE_OPTION)
6397 /* This block is only needed when using fork().
6398 * When using threads, the server thread was
6399 * created and run by the call to _beginthread().
6401 if (child_id == 0) /* child */
6404 #ifdef FEATURE_TOGGLE
6405 int inherited_toggle_state = global_toggle_state;
6406 #endif /* def FEATURE_TOGGLE */
6411 * If we've been toggled or we've blocked the request, tell Mom
6414 #ifdef FEATURE_TOGGLE
6415 if (inherited_toggle_state != global_toggle_state)
6417 rc |= RC_FLAG_TOGGLED;
6419 #endif /* def FEATURE_TOGGLE */
6421 #ifdef FEATURE_STATISTICS
6422 if (csp->flags & CSP_FLAG_REJECTED)
6424 rc |= RC_FLAG_BLOCKED;
6426 #endif /* ndef FEATURE_STATISTICS */
6430 else if (child_id > 0) /* parent */
6432 /* in a fork()'d environment, the parent's
6433 * copy of the client socket and the CSP
6437 #if !defined(_WIN32) && !defined(__CYGWIN__)
6439 wait(&child_status);
6442 * Evaluate child's return code: If the child has
6443 * - been toggled, toggle ourselves
6444 * - blocked its request, bump up the stats counter
6447 #ifdef FEATURE_TOGGLE
6448 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6450 global_toggle_state = !global_toggle_state;
6452 #endif /* def FEATURE_TOGGLE */
6454 #ifdef FEATURE_STATISTICS
6456 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6460 #endif /* def FEATURE_STATISTICS */
6462 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6463 close_socket(csp->cfd);
6464 csp->flags &= ~CSP_FLAG_ACTIVE;
6468 #undef SELECTED_ONE_OPTION
6469 /* end of cpp switch () */
6474 * Spawning the child failed, assume it's because
6475 * there are too many children running already.
6476 * XXX: If you assume ...
6478 log_error(LOG_LEVEL_ERROR,
6479 "Unable to take any additional connections: %E. Active threads: %u",
6481 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6482 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6483 close_socket(csp->cfd);
6484 csp->flags &= ~CSP_FLAG_ACTIVE;
6493 #if defined(FEATURE_PTHREAD)
6494 pthread_attr_destroy(&attrs);
6497 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6499 #ifdef FEATURE_GRACEFUL_TERMINATION
6501 log_error(LOG_LEVEL_INFO, "Graceful termination requested.");
6503 close_ports_helper(bfds);
6505 unload_current_config_file();
6506 unload_current_actions_file();
6507 unload_current_re_filterfile();
6508 #ifdef FEATURE_TRUST
6509 unload_current_trust_file();
6512 if (config->multi_threaded)
6519 } while ((clients->next != NULL) && (--i > 0));
6523 log_error(LOG_LEVEL_ERROR, "Graceful termination failed "
6524 "- still some live clients after 1 minute wait.");
6534 #ifdef FEATURE_HTTPS_INSPECTION
6536 * Only release TLS backed resources if there
6537 * are no active connections left.
6539 if (clients->next == NULL)
6545 log_error(LOG_LEVEL_INFO, "Exiting gracefully.");
6547 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6548 /* Cleanup - remove taskbar icon etc. */
6553 #endif /* FEATURE_GRACEFUL_TERMINATION */