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");
1657 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1662 /*********************************************************************
1664 * Function : fuzz_client_request
1666 * Description : Try to get a client request from the fuzzed input.
1669 * 1 : csp = Current client state (buffers, headers, etc...)
1670 * 2 : fuzz_input_file = File to read the input from.
1672 * Returns : Result of fuzzing.
1674 *********************************************************************/
1675 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1680 csp->ip_addr_str = "fuzzer";
1682 if (strcmp(fuzz_input_file, "-") != 0)
1684 log_error(LOG_LEVEL_FATAL,
1685 "Fuzzed client requests can currently only be read from stdin (-).");
1687 err = receive_client_request(csp);
1688 if (err != JB_ERR_OK)
1692 err = parse_client_request(csp);
1693 if (err != JB_ERR_OK)
1701 #endif /* def FUZZ */
1704 #ifdef FEATURE_FORCE_LOAD
1705 /*********************************************************************
1707 * Function : force_required
1709 * Description : Checks a request line to see if it contains
1710 * the FORCE_PREFIX. If it does, it is removed
1711 * unless enforcing requests has beend disabled.
1714 * 1 : request_line = HTTP request line
1716 * Returns : TRUE if force is required, FALSE otherwise.
1718 *********************************************************************/
1719 static int force_required(const struct client_state *csp, char *request_line)
1723 p = strstr(request_line, "http://");
1727 p += strlen("http://");
1731 /* Intercepted request usually don't specify the protocol. */
1735 /* Go to the beginning of the path */
1740 * If the path is missing the request line is invalid and we
1741 * are done here. The client-visible rejection happens later on.
1746 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1748 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1750 /* XXX: Should clean more carefully */
1751 strclean(request_line, FORCE_PREFIX);
1752 log_error(LOG_LEVEL_FORCE,
1753 "Enforcing request: \"%s\".", request_line);
1757 log_error(LOG_LEVEL_FORCE,
1758 "Ignored force prefix in request: \"%s\".", request_line);
1764 #endif /* def FEATURE_FORCE_LOAD */
1767 /*********************************************************************
1769 * Function : receive_client_request
1771 * Description : Read the client's request (more precisely the
1772 * client headers) and answer it if necessary.
1775 * 1 : csp = Current client state (buffers, headers, etc...)
1777 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1779 *********************************************************************/
1780 static jb_err receive_client_request(struct client_state *csp)
1782 char buf[BUFFER_SIZE];
1785 struct http_request *http;
1789 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1790 struct list header_list;
1791 struct list *headers = &header_list;
1793 /* We don't care if the arriving data is a valid HTTP request or not. */
1794 csp->requests_received_total++;
1798 memset(buf, 0, sizeof(buf));
1800 req = get_request_line(csp);
1803 mark_server_socket_tainted(csp);
1804 return JB_ERR_PARSE;
1806 assert(*req != '\0');
1808 if (client_protocol_is_unsupported(csp, req))
1810 return JB_ERR_PARSE;
1813 #ifdef FEATURE_FORCE_LOAD
1814 if (force_required(csp, req))
1816 csp->flags |= CSP_FLAG_FORCED;
1818 #endif /* def FEATURE_FORCE_LOAD */
1820 err = parse_http_request(req, http);
1822 if (JB_ERR_OK != err)
1824 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1825 get_write_delay(csp));
1826 /* XXX: Use correct size */
1827 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1828 log_error(LOG_LEVEL_ERROR,
1829 "Couldn't parse request line received from %s: %s",
1830 csp->ip_addr_str, jb_err_to_string(err));
1832 free_http_request(http);
1833 return JB_ERR_PARSE;
1835 if (http->ssl && strcmpic(http->gpc, "CONNECT"))
1837 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1838 get_write_delay(csp));
1839 /* XXX: Use correct size */
1840 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0",
1842 log_error(LOG_LEVEL_ERROR, "Client %s tried to send a https "
1843 "URL without sending a CONNECT request first",
1845 free_http_request(http);
1846 return JB_ERR_PARSE;
1849 /* grab the rest of the client's headers */
1853 p = get_header(csp->client_iob);
1857 /* There are no additional headers to read. */
1864 * We didn't receive a complete header
1865 * line yet, get the rest of it.
1867 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1869 log_error(LOG_LEVEL_ERROR,
1870 "Client headers did not arrive in time. Timeout: %d",
1871 csp->config->socket_timeout);
1872 destroy_list(headers);
1873 return JB_ERR_PARSE;
1876 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1879 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1880 destroy_list(headers);
1881 return JB_ERR_PARSE;
1884 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1887 * If there is no memory left for buffering the
1888 * request, there is nothing we can do but hang up
1890 destroy_list(headers);
1891 return JB_ERR_MEMORY;
1896 if (!strncmpic(p, "Transfer-Encoding:", 18))
1899 * XXX: should be called through sed()
1900 * but currently can't.
1902 client_transfer_encoding(csp, &p);
1905 * We were able to read a complete
1906 * header and can finally enlist it.
1913 if (http->host == NULL)
1916 * If we still don't know the request destination,
1917 * the request is invalid or the client uses
1918 * Privoxy without its knowledge.
1920 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1923 * Our attempts to get the request destination
1924 * elsewhere failed or Privoxy is configured
1925 * to only accept proxy requests.
1927 * An error response has already been sent
1928 * and we're done here.
1930 return JB_ERR_PARSE;
1934 #ifdef FEATURE_CLIENT_TAGS
1935 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1936 set_client_address(csp, headers);
1937 get_tag_list_for_client(csp->client_tags, csp->client_address);
1941 * Determine the actions for this URL
1943 #ifdef FEATURE_TOGGLE
1944 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1946 /* Most compatible set of actions (i.e. none) */
1947 init_current_action(csp->action);
1950 #endif /* ndef FEATURE_TOGGLE */
1952 get_url_actions(csp, http);
1955 enlist(csp->headers, http->cmd);
1957 /* Append the previously read headers */
1958 err = list_append_list_unique(csp->headers, headers);
1959 destroy_list(headers);
1966 /*********************************************************************
1968 * Function : parse_client_request
1970 * Description : Parses the client's request and decides what to do
1973 * Note that since we're not using select() we could get
1974 * blocked here if a client connected, then didn't say
1978 * 1 : csp = Current client state (buffers, headers, etc...)
1980 * Returns : JB_ERR_OK or JB_ERR_PARSE
1982 *********************************************************************/
1983 static jb_err parse_client_request(struct client_state *csp)
1985 struct http_request *http = csp->http;
1988 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1989 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1990 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1991 && (csp->http->ssl == 0))
1993 /* Assume persistence until further notice */
1994 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1996 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1998 if (csp->http->ssl == 0)
2001 * This whole block belongs to chat() but currently
2002 * has to be executed before sed().
2004 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
2006 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
2008 return JB_ERR_PARSE;
2013 csp->expected_client_content_length = get_expected_content_length(csp->headers);
2015 verify_request_length(csp);
2017 #ifndef FEATURE_HTTPS_INSPECTION
2020 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
2024 err = sed(csp, FILTER_CLIENT_HEADERS);
2025 if (JB_ERR_OK != err)
2027 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2029 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2030 csp->ip_addr_str, csp->http->cmd);
2031 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
2032 return JB_ERR_PARSE;
2034 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
2036 /* Check request line for rewrites. */
2037 if ((NULL == csp->headers->first->str)
2038 || (strcmp(http->cmd, csp->headers->first->str) &&
2039 (JB_ERR_OK != change_request_destination(csp))))
2042 * A header filter broke the request line - bail out.
2044 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
2045 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2046 /* XXX: Use correct size */
2047 log_error(LOG_LEVEL_CLF,
2048 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2049 log_error(LOG_LEVEL_ERROR,
2050 "Invalid request line after applying header filters.");
2051 free_http_request(http);
2053 return JB_ERR_PARSE;
2056 if (client_has_unsupported_expectations(csp))
2058 return JB_ERR_PARSE;
2066 /*********************************************************************
2068 * Function : read_http_request_body
2070 * Description : Reads remaining request body from the client.
2073 * 1 : csp = Current client state (buffers, headers, etc...)
2075 * Returns : 0 on success, anything else is an error.
2077 *********************************************************************/
2078 static int read_http_request_body(struct client_state *csp)
2080 size_t to_read = csp->expected_client_content_length;
2083 assert(to_read != 0);
2085 /* check if all data has been already read */
2086 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2091 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2092 to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2093 to_read -= (unsigned)len)
2095 char buf[BUFFER_SIZE];
2096 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2098 log_error(LOG_LEVEL_CONNECT,
2099 "Waiting for up to %lu bytes of request body from the client.",
2101 len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2104 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2107 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2111 assert(to_read >= len);
2116 log_error(LOG_LEVEL_CONNECT,
2117 "Not enough request body has been read: expected %lu more bytes",
2121 log_error(LOG_LEVEL_CONNECT,
2122 "The last %d bytes of the request body have been read", len);
2127 /*********************************************************************
2129 * Function : update_client_headers
2131 * Description : Updates the HTTP headers from the client request.
2134 * 1 : csp = Current client state (buffers, headers, etc...)
2135 * 2 : new_content_length = new content length value to set
2137 * Returns : 0 on success, anything else is an error.
2139 *********************************************************************/
2140 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2142 static const char content_length[] = "Content-Length:";
2144 struct list_entry *p;
2146 #ifndef FEATURE_HTTPS_INSPECTION
2147 for (p = csp->headers->first;
2149 for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2151 !updated && (p != NULL); p = p->next)
2153 /* Header crunch()ed in previous run? -> ignore */
2159 /* Does the current parser handle this header? */
2160 if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2162 updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2174 /*********************************************************************
2176 * Function : can_filter_request_body
2178 * Description : Checks if the current request body can be stored in
2179 * the client_iob without hitting buffer limit.
2182 * 1 : csp = Current client state (buffers, headers, etc...)
2184 * Returns : TRUE if the current request size do not exceed buffer limit
2187 *********************************************************************/
2188 static int can_filter_request_body(const struct client_state *csp)
2190 if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2191 csp->expected_client_content_length))
2193 log_error(LOG_LEVEL_INFO,
2194 "Not filtering request body from %s: buffer limit %lu will be exceeded "
2195 "(content length %llu)", csp->ip_addr_str, csp->config->buffer_limit,
2196 csp->expected_client_content_length);
2203 /*********************************************************************
2205 * Function : send_http_request
2207 * Description : Sends the HTTP headers from the client request
2208 * and all the body data that has already been received.
2211 * 1 : csp = Current client state (buffers, headers, etc...)
2213 * Returns : 0 on success, anything else is an error.
2215 *********************************************************************/
2216 static int send_http_request(struct client_state *csp)
2221 hdr = list_to_text(csp->headers);
2224 /* FIXME Should handle error properly */
2225 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2227 list_remove_all(csp->headers);
2230 * Write the client's (modified) header to the server
2231 * (along with anything else that may be in the buffer)
2233 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2238 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2239 csp->http->hostport);
2243 /* XXX: Filtered data is not sent if there's a pipelined request? */
2244 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2245 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2247 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2248 csp->http->hostport);
2255 #ifdef FEATURE_HTTPS_INSPECTION
2256 /*********************************************************************
2258 * Function : read_https_request_body
2260 * Description : Reads remaining request body from the client.
2263 * 1 : csp = Current client state (buffers, headers, etc...)
2265 * Returns : 0 on success, anything else is an error.
2267 *********************************************************************/
2268 static int read_https_request_body(struct client_state *csp)
2270 size_t to_read = csp->expected_client_content_length;
2273 assert(to_read != 0);
2275 /* check if all data has been already read */
2276 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2281 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2282 to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2283 data_is_available(csp->cfd, csp->config->socket_timeout));
2284 to_read -= (unsigned)len)
2286 unsigned char buf[BUFFER_SIZE];
2287 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2289 log_error(LOG_LEVEL_CONNECT,
2290 "Buffering encrypted client body. Prepared to read up to %lu bytes.",
2292 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2293 (unsigned)max_bytes_to_read);
2296 log_error(LOG_LEVEL_CONNECT,
2297 "Did not receive the whole encrypted request body from %s",
2301 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2305 assert(to_read >= len);
2310 log_error(LOG_LEVEL_CONNECT,
2311 "Not enough encrypted request body has been read: expected %lu more bytes",
2316 log_error(LOG_LEVEL_CONNECT,
2317 "The last %llu bytes of the encrypted request body have been read",
2318 csp->expected_client_content_length);
2323 /*********************************************************************
2325 * Function : receive_and_send_encrypted_post_data
2327 * Description : Reads remaining request body from the client and sends
2331 * 1 : csp = Current client state (buffers, headers, etc...)
2333 * Returns : 0 on success, anything else is an error.
2335 *********************************************************************/
2336 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2338 int content_length_known = csp->expected_client_content_length != 0;
2340 while ((content_length_known && csp->expected_client_content_length != 0) ||
2341 (is_ssl_pending(&(csp->ssl_client_attr)) ||
2342 data_is_available(csp->cfd, csp->config->socket_timeout)))
2344 unsigned char buf[BUFFER_SIZE];
2346 int max_bytes_to_read = sizeof(buf);
2348 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2350 max_bytes_to_read = (int)csp->expected_client_content_length;
2352 log_error(LOG_LEVEL_CONNECT,
2353 "Prepared to read up to %d bytes of encrypted request body from the client.",
2355 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2356 (unsigned)max_bytes_to_read);
2363 /* XXX: Does this actually happen? */
2366 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2368 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2373 if (csp->expected_client_content_length != 0)
2375 if (csp->expected_client_content_length >= len)
2377 csp->expected_client_content_length -= (unsigned)len;
2379 if (csp->expected_client_content_length == 0)
2381 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2387 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2394 /*********************************************************************
2396 * Function : send_https_request
2398 * Description : Sends the HTTP headers from the client request
2399 * and all the body data that has already been received.
2402 * 1 : csp = Current client state (buffers, headers, etc...)
2404 * Returns : 0 on success, anything else is an error.
2406 *********************************************************************/
2407 static int send_https_request(struct client_state *csp)
2413 hdr = list_to_text(csp->https_headers);
2416 /* FIXME Should handle error properly */
2417 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2419 list_remove_all(csp->https_headers);
2422 * Write the client's (modified) header to the server
2423 * (along with anything else that may be in the buffer)
2425 ret = ssl_send_data(&(csp->ssl_server_attr),
2426 (const unsigned char *)hdr, strlen(hdr));
2431 log_error(LOG_LEVEL_CONNECT,
2432 "Failed sending encrypted request headers to: %s: %E",
2433 csp->http->hostport);
2434 mark_server_socket_tainted(csp);
2438 /* XXX: Client body isn't sent if there's pipelined data? */
2439 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2440 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2441 csp->client_iob)) < 0))
2443 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2444 csp->http->hostport);
2447 if (flushed != 0 || csp->expected_client_content_length != 0)
2449 if (csp->expected_client_content_length != 0)
2451 if (csp->expected_client_content_length < flushed)
2453 log_error(LOG_LEVEL_ERROR,
2454 "Flushed %ld bytes of request body while only expecting %llu",
2455 flushed, csp->expected_client_content_length);
2456 csp->expected_client_content_length = 0;
2460 log_error(LOG_LEVEL_CONNECT,
2461 "Flushed %ld bytes of request body while expecting %llu",
2462 flushed, csp->expected_client_content_length);
2463 csp->expected_client_content_length -= (unsigned)flushed;
2464 if (receive_and_send_encrypted_post_data(csp))
2472 log_error(LOG_LEVEL_CONNECT,
2473 "Flushed %ld bytes of request body", flushed);
2477 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2484 /*********************************************************************
2486 * Function : receive_encrypted_request_headers
2488 * Description : Receives the encrypted request headers when
2492 * 1 : csp = Current client state (buffers, headers, etc...)
2494 * Returns : JB_ERR_OK on success,
2495 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2497 *********************************************************************/
2498 static jb_err receive_encrypted_request_headers(struct client_state *csp)
2500 char buf[BUFFER_SIZE];
2506 log_error(LOG_LEVEL_HEADER, "Waiting for encrypted client headers");
2507 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2508 !data_is_available(csp->cfd, csp->config->socket_timeout))
2510 log_error(LOG_LEVEL_CONNECT,
2511 "Socket %d timed out while waiting for client headers", csp->cfd);
2512 return JB_ERR_PARSE;
2514 len = ssl_recv_data(&(csp->ssl_client_attr),
2515 (unsigned char *)buf, sizeof(buf));
2518 log_error(LOG_LEVEL_CONNECT,
2519 "Socket %d closed while waiting for client headers", csp->cfd);
2520 return JB_ERR_PARSE;
2524 return JB_ERR_PARSE;
2526 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2528 return JB_ERR_MEMORY;
2530 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2531 } while (p == NULL);
2533 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2539 /*********************************************************************
2541 * Function : change_encrypted_request_destination
2543 * Description : Parse a (rewritten) request line from an encrypted
2544 * request and regenerate the http request data.
2547 * 1 : csp = Current client state (buffers, headers, etc...)
2549 * Returns : Forwards the parse_http_request() return code.
2550 * Terminates in case of memory problems.
2552 *********************************************************************/
2553 static jb_err change_encrypted_request_destination(struct client_state *csp)
2556 char *original_host = csp->http->host;
2557 int original_port = csp->http->port;
2559 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2560 csp->https_headers->first->str);
2561 csp->http->host = NULL;
2562 free_http_request(csp->http);
2563 err = parse_http_request(csp->https_headers->first->str, csp->http);
2564 if (JB_ERR_OK != err)
2566 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2567 jb_err_to_string(err));
2568 freez(original_host);
2572 if (csp->http->host == NULL)
2574 char port_string[10];
2576 * The rewritten request line did not specify a host
2577 * which means we can use the original host specified
2580 csp->http->host = original_host;
2581 csp->http->port = original_port;
2582 log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2585 * If the rewritten request line didn't contain a host
2586 * it also didn't contain a port so we can reuse the host
2589 freez(csp->http->hostport);
2590 csp->http->hostport = strdup_or_die(csp->http->host);
2591 snprintf(port_string, sizeof(port_string), ":%d", original_port);
2592 err = string_append(&csp->http->hostport, port_string);
2593 if (err != JB_ERR_OK)
2595 log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2596 jb_err_to_string(err));
2601 * While the request line didn't mention it,
2602 * we're https-inspecting and want to speak TLS
2605 csp->http->server_ssl = 1;
2610 /* The rewrite filter added a host so we can ditch the original */
2611 freez(original_host);
2612 csp->http->server_ssl = csp->http->ssl;
2615 csp->http->client_ssl = 1;
2617 freez(csp->https_headers->first->str);
2618 build_request_line(csp, NULL, &csp->https_headers->first->str);
2620 if (!server_use_ssl(csp))
2622 log_error(LOG_LEVEL_REDIRECTS,
2623 "Rewritten request line results in downgrade to http");
2625 * Replace the unencryptd headers received with the
2626 * CONNECT request with the ones we received securely.
2628 destroy_list(csp->headers);
2629 csp->headers->first = csp->https_headers->first;
2630 csp->headers->last = csp->https_headers->last;
2631 csp->https_headers->first = NULL;
2632 csp->https_headers->last = NULL;
2640 /*********************************************************************
2642 * Function : process_encrypted_request_headers
2644 * Description : Receives and parses the encrypted headers send
2645 * by the client when https-inspecting.
2648 * 1 : csp = Current client state (buffers, headers, etc...)
2650 * Returns : JB_ERR_OK on success,
2651 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2653 *********************************************************************/
2654 static jb_err process_encrypted_request_headers(struct client_state *csp)
2659 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2660 struct list header_list;
2661 struct list *headers = &header_list;
2663 assert(csp->ssl_with_client_is_opened);
2665 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2666 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2668 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2671 err = receive_encrypted_request_headers(csp);
2672 if (err != JB_ERR_OK)
2674 if (csp->client_iob->cur == NULL ||
2675 csp->client_iob->cur == csp->client_iob->eod)
2678 * We did not receive any data, most likely because the
2679 * client is done. Don't log this as a parse failure.
2681 return JB_ERR_PARSE;
2683 /* XXX: Also used for JB_ERR_MEMORY */
2684 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2685 jb_err_to_string(err));
2686 ssl_send_data_delayed(&(csp->ssl_client_attr),
2687 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2691 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2692 request_line = get_header(csp->client_iob);
2693 if (request_line == NULL)
2695 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2696 ssl_send_data_delayed(&(csp->ssl_client_attr),
2697 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2698 return JB_ERR_PARSE;
2700 assert(*request_line != '\0');
2702 if (client_protocol_is_unsupported(csp, request_line))
2705 * If the protocol is unsupported we're done here.
2706 * client_protocol_is_unsupported() took care of sending
2707 * the error response and logging the error message.
2709 return JB_ERR_PARSE;
2712 #ifdef FEATURE_FORCE_LOAD
2713 if (force_required(csp, request_line))
2715 csp->flags |= CSP_FLAG_FORCED;
2717 #endif /* def FEATURE_FORCE_LOAD */
2719 free_http_request(csp->http);
2721 err = parse_http_request(request_line, csp->http);
2722 /* XXX: Restore ssl setting. This is ugly */
2723 csp->http->client_ssl = 1;
2724 csp->http->server_ssl = 1;
2726 freez(request_line);
2727 if (JB_ERR_OK != err)
2729 ssl_send_data_delayed(&(csp->ssl_client_attr),
2730 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2731 /* XXX: Use correct size */
2732 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2733 log_error(LOG_LEVEL_ERROR,
2734 "Couldn't parse request line received from %s: %s",
2735 csp->ip_addr_str, jb_err_to_string(err));
2737 free_http_request(csp->http);
2738 return JB_ERR_PARSE;
2741 /* Parse the rest of the client's headers. */
2745 p = get_header(csp->client_iob);
2749 /* There are no additional headers to read. */
2756 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2759 * Our attempts to get the request destination
2762 log_error(LOG_LEVEL_ERROR,
2763 "Failed to get the encrypted request destination");
2764 ssl_send_data_delayed(&(csp->ssl_client_attr),
2765 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2766 destroy_list(headers);
2768 return JB_ERR_PARSE;
2771 /* Split the domain we just got for pattern matching */
2772 init_domain_components(csp->http);
2774 #ifdef FEATURE_CLIENT_TAGS
2775 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2776 if (csp->client_address == NULL)
2778 set_client_address(csp, headers);
2779 get_tag_list_for_client(csp->client_tags, csp->client_address);
2783 #ifdef FEATURE_TOGGLE
2784 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2788 * Determine the actions for this request after
2789 * clearing the ones from the previous one.
2791 free_current_action(csp->action);
2792 get_url_actions(csp, csp->http);
2795 enlist(csp->https_headers, csp->http->cmd);
2797 /* Append the previously read headers */
2798 err = list_append_list_unique(csp->https_headers, headers);
2799 destroy_list(headers);
2800 if (JB_ERR_OK != err)
2802 /* XXX: Send error message */
2806 /* XXX: Work around crash */
2807 csp->error_message = NULL;
2809 /* XXX: Why do this here? */
2812 err = sed_https(csp);
2813 if (JB_ERR_OK != err)
2815 ssl_send_data_delayed(&(csp->ssl_client_attr),
2816 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2817 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2819 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2820 csp->ip_addr_str, csp->http->cmd);
2821 return JB_ERR_PARSE;
2824 if ((NULL == csp->https_headers->first->str)
2825 || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2826 (JB_ERR_OK != change_encrypted_request_destination(csp))))
2828 ssl_send_data_delayed(&(csp->ssl_client_attr),
2829 (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2830 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2831 log_error(LOG_LEVEL_ERROR,
2832 "Invalid request line after applying header filters.");
2833 /* XXX: Use correct size */
2834 log_error(LOG_LEVEL_CLF,
2835 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2837 return JB_ERR_PARSE;
2840 log_error(LOG_LEVEL_HEADER, "Encrypted request headers processed");
2841 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2848 /*********************************************************************
2850 * Function : cgi_page_requested
2852 * Description : Checks if a request is for an internal CGI page.
2855 * 1 : host = The host requested by the client.
2857 * Returns : 1 if a CGI page has been requested, 0 otherwise
2859 *********************************************************************/
2860 static int cgi_page_requested(const char *host)
2862 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2863 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2864 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2865 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2875 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2876 /*********************************************************************
2878 * Function : continue_https_chat
2880 * Description : Behaves similar to chat() but only deals with
2881 * https-inspected requests that arrive on an already
2882 * established connection. The first request is always
2883 * served by chat() which is a lot more complex as it
2884 * has to deal with forwarding settings and connection
2887 * If a connection to the server has already been
2888 * opened it is reused unless the request is blocked
2889 * or the forwarder changed.
2891 * If a connection to the server has not yet been
2892 * opened (because the previous request was crunched),
2893 * or the forwarder changed, the connection is dropped
2894 * so that the client retries on a fresh one.
2897 * 1 : csp = Current client state (buffers, headers, etc...)
2899 * Returns : Nothing.
2901 *********************************************************************/
2902 static void continue_https_chat(struct client_state *csp)
2904 const struct forward_spec *fwd;
2906 if (JB_ERR_OK != process_encrypted_request_headers(csp))
2908 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2912 #if defined(FEATURE_STATISTICS) && defined(MUTEX_LOCKS_AVAILABLE)
2913 privoxy_mutex_lock(&block_statistics_mutex);
2914 number_of_requests_received++;
2915 privoxy_mutex_unlock(&block_statistics_mutex);
2918 csp->requests_received_total++;
2921 * We have an encrypted request. Check if one of the crunchers wants it.
2923 if (crunch_response_triggered(csp, crunchers_all))
2926 * Yes. The client got the crunch response and we're done here.
2930 if (csp->ssl_with_server_is_opened == 0)
2932 log_error(LOG_LEVEL_CONNECT,
2933 "Dropping the client connection on socket %d. "
2934 "The server connection has not been established yet.",
2936 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2939 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2941 if (csp->expected_client_content_length != 0 &&
2942 client_body_filters_enabled(csp->action) &&
2943 can_filter_request_body(csp))
2945 int content_modified;
2946 size_t buffered_content_length;
2948 if (read_https_request_body(csp))
2953 buffered_content_length = csp->expected_client_content_length;
2954 content_modified = execute_client_body_filters(csp, &buffered_content_length);
2955 if ((content_modified == 1) &&
2956 (buffered_content_length != csp->expected_client_content_length) &&
2957 update_client_headers(csp, buffered_content_length))
2959 log_error(LOG_LEVEL_HEADER, "Failed to update client headers "
2960 "after filtering the encrypted client body");
2964 csp->expected_client_content_length = 0;
2967 fwd = forward_url(csp, csp->http);
2968 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2970 log_error(LOG_LEVEL_CONNECT,
2971 "Dropping the client connection on socket %d with "
2972 "server socket %d connected to %s. The forwarder has changed.",
2973 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2974 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2978 log_applied_actions(csp->action);
2980 log_error(LOG_LEVEL_CONNECT,
2981 "Reusing server socket %d connected to %s. Requests already sent: %u.",
2982 csp->server_connection.sfd, csp->server_connection.host,
2983 csp->server_connection.requests_sent_total);
2985 if (send_https_request(csp))
2988 * Most likely the server connection timed out. We can't easily
2989 * create a new one so simply drop the client connection without a
2990 * error response to let the client retry.
2992 log_error(LOG_LEVEL_CONNECT,
2993 "Dropping client connection on socket %d. "
2994 "Forwarding the encrypted client request failed.",
2998 csp->server_connection.request_sent = time(NULL);
2999 csp->server_connection.requests_sent_total++;
3000 handle_established_connection(csp);
3001 freez(csp->receive_buffer);
3003 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3007 /*********************************************************************
3009 * Function : handle_established_connection
3011 * Description : Shuffle data between client and server once the
3012 * connection has been established and the request
3016 * 1 : csp = Current client state (buffers, headers, etc...)
3018 * Returns : Nothing.
3020 *********************************************************************/
3021 static void handle_established_connection(struct client_state *csp)
3027 struct pollfd poll_fds[2];
3031 struct timeval timeout;
3034 int ms_iis5_hack = 0;
3035 unsigned long long byte_count = 0;
3036 struct http_request *http;
3037 long len = 0; /* for buffer sizes (and negative error codes) */
3038 int buffer_and_filter_content = 0;
3039 unsigned int write_delay;
3040 #ifdef FEATURE_HTTPS_INSPECTION
3042 int use_ssl_tunnel = 0;
3043 csp->dont_verify_certificate = 0;
3045 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3047 /* Pass encrypted content without filtering. */
3052 /* Skeleton for HTTP response, if we should intercept the request */
3053 struct http_response *rsp;
3054 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3055 int watch_client_socket;
3058 csp->receive_buffer_size = csp->config->receive_buffer_size;
3059 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3060 if (csp->receive_buffer == NULL)
3062 log_error(LOG_LEVEL_ERROR,
3063 "Out of memory. Failed to allocate the receive buffer.");
3064 rsp = cgi_error_memory();
3065 send_crunch_response(csp, rsp);
3072 maxfd = (csp->cfd > csp->server_connection.sfd) ?
3073 csp->cfd : csp->server_connection.sfd;
3076 /* pass data between the client and server
3077 * until one or the other shuts down the connection.
3082 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3083 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3085 write_delay = get_write_delay(csp);
3089 #ifdef FEATURE_HTTPS_INSPECTION
3090 if (server_use_ssl(csp) && is_ssl_pending(&(csp->ssl_server_attr)))
3093 * It's possible that the TLS library already consumed all the
3094 * data the server intends to send. If that happens poll() and
3095 * select() will no longer see the data as available so we have
3096 * to skip the calls.
3098 goto server_wants_to_talk;
3100 if (watch_client_socket && client_use_ssl(csp) &&
3101 is_ssl_pending(&(csp->ssl_client_attr)))
3104 * The TLS libray may also consume all of the remaining data
3105 * from the client when we're shuffling the data from an
3106 * unbuffered request body to the server.
3108 goto client_wants_to_talk;
3113 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3114 if (!watch_client_socket)
3116 maxfd = csp->server_connection.sfd;
3119 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3121 FD_SET(csp->cfd, &rfds);
3124 FD_SET(csp->server_connection.sfd, &rfds);
3125 #endif /* ndef HAVE_POLL */
3127 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3128 if ((csp->flags & CSP_FLAG_CHUNKED)
3129 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3130 && ((csp->iob->eod - csp->iob->cur) >= 5)
3131 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3134 * XXX: This check should be obsolete now,
3135 * but let's wait a while to be sure.
3137 log_error(LOG_LEVEL_CONNECT,
3138 "Looks like we got the last chunk together with "
3139 "the server headers but didn't detect it earlier. "
3140 "We better stop reading.");
3141 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3142 csp->expected_content_length = byte_count;
3143 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3145 if (server_body && server_response_is_complete(csp, byte_count))
3147 if (csp->expected_content_length == byte_count)
3149 log_error(LOG_LEVEL_CONNECT,
3150 "Done reading from server. Content length: %llu as expected. "
3151 "Bytes most recently read: %ld.",
3156 log_error(LOG_LEVEL_CONNECT,
3157 "Done reading from server. Expected content length: %llu. "
3158 "Actual content length: %llu. Bytes most recently read: %ld.",
3159 csp->expected_content_length, byte_count, len);
3163 * XXX: Should not jump around, handle_established_connection()
3164 * is complicated enough already.
3168 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3171 poll_fds[0].fd = csp->cfd;
3172 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3173 if (!watch_client_socket)
3176 * Ignore incoming data, but still watch out
3177 * for disconnects etc. These flags are always
3178 * implied anyway but explicitly setting them
3181 poll_fds[0].events = POLLERR|POLLHUP;
3186 poll_fds[0].events = POLLIN;
3188 poll_fds[1].fd = csp->server_connection.sfd;
3189 poll_fds[1].events = POLLIN;
3190 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3192 timeout.tv_sec = csp->config->socket_timeout;
3193 timeout.tv_usec = 0;
3194 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3195 #endif /* def HAVE_POLL */
3197 /* Server or client not responding in timeout */
3200 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3201 csp->config->socket_timeout, http->url);
3202 if ((byte_count == 0) && (http->ssl == 0))
3204 send_crunch_response(csp, error_response(csp, "connection-timeout"));
3206 mark_server_socket_tainted(csp);
3207 #ifdef FEATURE_HTTPS_INSPECTION
3208 close_client_and_server_ssl_connections(csp);
3215 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3217 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3219 mark_server_socket_tainted(csp);
3220 #ifdef FEATURE_HTTPS_INSPECTION
3221 close_client_and_server_ssl_connections(csp);
3227 * This is the body of the browser's request,
3228 * just read and write it.
3230 * Receives data from browser and sends it to server
3232 * XXX: Make sure the client doesn't use pipelining
3233 * behind Privoxy's back.
3236 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3238 log_error(LOG_LEVEL_CONNECT,
3239 "The client socket %d has become unusable while "
3240 "the server socket %d is still open.",
3241 csp->cfd, csp->server_connection.sfd);
3242 mark_server_socket_tainted(csp);
3246 if (poll_fds[0].revents != 0)
3248 if (FD_ISSET(csp->cfd, &rfds))
3249 #endif /* def HAVE_POLL*/
3251 int max_bytes_to_read;
3253 #ifdef FEATURE_HTTPS_INSPECTION
3254 client_wants_to_talk:
3257 max_bytes_to_read = (int)csp->receive_buffer_size;
3259 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3260 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3262 if (data_is_available(csp->cfd, 0))
3265 * If the next request is already waiting, we have
3266 * to stop select()ing the client socket. Otherwise
3267 * we would always return right away and get nothing
3270 watch_client_socket = 0;
3271 log_error(LOG_LEVEL_CONNECT,
3272 "Stop watching client socket %d. "
3273 "There's already another request waiting.",
3278 * If the client socket is set, but there's no data
3279 * available on the socket, the client went fishing
3280 * and continuing talking to the server makes no sense.
3282 log_error(LOG_LEVEL_CONNECT,
3283 "The client closed socket %d while "
3284 "the server socket %d is still open.",
3285 csp->cfd, csp->server_connection.sfd);
3286 mark_server_socket_tainted(csp);
3289 if (csp->expected_client_content_length != 0)
3291 if (csp->expected_client_content_length < csp->receive_buffer_size)
3293 max_bytes_to_read = (int)csp->expected_client_content_length;
3295 log_error(LOG_LEVEL_CONNECT,
3296 "Waiting for up to %d bytes from the client.",
3299 assert(max_bytes_to_read <= csp->receive_buffer_size);
3300 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3302 #ifdef FEATURE_HTTPS_INSPECTION
3303 if (client_use_ssl(csp))
3305 if (csp->http->status == 101)
3307 len = ssl_recv_data(&(csp->ssl_client_attr),
3308 (unsigned char *)csp->receive_buffer,
3309 (size_t)max_bytes_to_read);
3312 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3313 "on client socket %d for an upgraded connection",
3319 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3320 "on client socket %d for an upgraded connection",
3324 byte_count += (unsigned long long)len;
3325 len = ssl_send_data(&(csp->ssl_server_attr),
3326 (unsigned char *)csp->receive_buffer, (size_t)len);
3329 log_error(LOG_LEVEL_ERROR, "Failed to send data "
3330 "on server socket %d for an upgraded connection",
3331 csp->server_connection.sfd);
3336 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3340 #endif /* def FEATURE_HTTPS_INSPECTION */
3342 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3346 /* XXX: not sure if this is necessary. */
3347 mark_server_socket_tainted(csp);
3348 break; /* "game over, man" */
3351 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3352 if (csp->expected_client_content_length != 0)
3354 assert(len <= max_bytes_to_read);
3355 csp->expected_client_content_length -= (unsigned)len;
3356 log_error(LOG_LEVEL_CONNECT,
3357 "Expected client content length set to %llu "
3358 "after reading %ld bytes.",
3359 csp->expected_client_content_length, len);
3360 if (csp->expected_client_content_length == 0)
3362 log_error(LOG_LEVEL_CONNECT,
3363 "Done reading from the client.");
3364 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3367 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3369 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3371 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3372 mark_server_socket_tainted(csp);
3380 * The server wants to talk. It could be the header or the body.
3381 * If `hdr' is null, then it's the header otherwise it's the body.
3382 * FIXME: Does `hdr' really mean `host'? No.
3385 if (poll_fds[1].revents != 0)
3387 if (FD_ISSET(csp->server_connection.sfd, &rfds))
3388 #endif /* HAVE_POLL */
3390 #ifdef FEATURE_HTTPS_INSPECTION
3391 server_wants_to_talk:
3393 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3395 * If we are buffering content, we don't want to eat up to
3396 * buffer-limit bytes if the client no longer cares about them.
3397 * If we aren't buffering, however, a dead client socket will be
3398 * noticed pretty much right away anyway, so we can reduce the
3399 * overhead by skipping the check.
3401 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3404 log_error(LOG_LEVEL_CONNECT,
3405 "The server still wants to talk, but the client may already have hung up on us.");
3407 log_error(LOG_LEVEL_CONNECT,
3408 "The server still wants to talk, but the client hung up on us.");
3409 mark_server_socket_tainted(csp);
3410 #ifdef FEATURE_HTTPS_INSPECTION
3411 close_client_and_server_ssl_connections(csp);
3414 #endif /* def _WIN32 */
3416 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3418 #ifdef FEATURE_HTTPS_INSPECTION
3420 * Reading data from standard or secured connection (HTTP/HTTPS)
3422 if (server_use_ssl(csp))
3424 len = ssl_recv_data(&(csp->ssl_server_attr),
3425 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3430 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3431 (int)csp->receive_buffer_size);
3436 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3438 if ((http->ssl && (csp->fwd == NULL))
3439 #ifdef FEATURE_HTTPS_INSPECTION
3445 * Just hang up. We already confirmed the client's CONNECT
3446 * request with status code 200 and unencrypted content is
3447 * no longer welcome.
3449 log_error(LOG_LEVEL_ERROR,
3450 "CONNECT already confirmed. Unable to tell the client about the problem.");
3453 else if (byte_count)
3456 * Just hang up. We already transmitted the original headers
3457 * and parts of the original content and therefore missed the
3458 * chance to send an error message (without risking data corruption).
3460 * XXX: we could retry with a fancy range request here.
3462 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3463 "Unable to tell the client about the problem.");
3464 mark_server_socket_tainted(csp);
3465 #ifdef FEATURE_HTTPS_INSPECTION
3466 close_client_and_server_ssl_connections(csp);
3471 * XXX: Consider handling the cases above the same.
3473 mark_server_socket_tainted(csp);
3477 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3478 if (csp->flags & CSP_FLAG_CHUNKED)
3480 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3482 /* XXX: this is a temporary hack */
3483 log_error(LOG_LEVEL_CONNECT,
3484 "Looks like we reached the end of the last chunk. "
3485 "We better stop reading.");
3486 csp->expected_content_length = byte_count + (unsigned long long)len;
3487 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3491 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3494 * This is guaranteed by allocating with zalloc_or_die()
3495 * and never (intentionally) writing to the last byte.
3497 * csp->receive_buffer_size is the size of the part of the
3498 * buffer we intentionally write to, but we actually
3499 * allocated csp->receive_buffer_size+1 bytes so the assertion
3500 * stays within the allocated range.
3502 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3505 * Add a trailing zero to let be able to use string operations.
3506 * XXX: do we still need this with filter_popups gone?
3508 assert(len <= csp->receive_buffer_size);
3509 csp->receive_buffer[len] = '\0';
3512 * Normally, this would indicate that we've read
3513 * as much as the server has sent us and we can
3514 * close the client connection. However, Microsoft
3515 * in its wisdom has released IIS/5 with a bug that
3516 * prevents it from sending the trailing \r\n in
3517 * a 302 redirect header (and possibly other headers).
3518 * To work around this if we've haven't parsed
3519 * a full header we'll append a trailing \r\n
3520 * and see if this now generates a valid one.
3522 * This hack shouldn't have any impacts. If we've
3523 * already transmitted the header or if this is a
3524 * SSL connection, then we won't bother with this
3525 * hack. So we only work on partially received
3526 * headers. If we append a \r\n and this still
3527 * doesn't generate a valid header, then we won't
3528 * transmit anything to the client.
3533 if (server_body || (http->ssl
3534 #ifdef FEATURE_HTTPS_INSPECTION
3540 * If we have been buffering up the document,
3541 * now is the time to apply content modification
3542 * and send the result to the client.
3544 if (buffer_and_filter_content)
3546 p = execute_content_filters(csp);
3548 * If content filtering fails, use the original
3549 * buffer and length.
3550 * (see p != NULL ? p : csp->iob->cur below)
3554 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3556 #ifdef FEATURE_COMPRESSION
3557 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3558 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3560 char *compressed_content = compress_buffer(p,
3561 (size_t *)&csp->content_length, csp->config->compression_level);
3562 if (compressed_content != NULL)
3565 p = compressed_content;
3566 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3571 if (JB_ERR_OK != update_server_headers(csp))
3573 log_error(LOG_LEVEL_FATAL,
3574 "Failed to update server headers. after filtering.");
3577 hdr = list_to_text(csp->headers);
3580 /* FIXME Should handle error properly */
3581 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3584 #ifdef FEATURE_HTTPS_INSPECTION
3586 * Sending data with standard or secured connection (HTTP/HTTPS)
3588 if (client_use_ssl(csp))
3590 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3591 (const unsigned char *)hdr, strlen(hdr),
3592 get_write_delay(csp)) < 0)
3593 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3594 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3595 csp->content_length, get_write_delay(csp)) < 0))
3597 log_error(LOG_LEVEL_ERROR,
3598 "Failed to send the modified content to the client over TLS");
3601 mark_server_socket_tainted(csp);
3602 close_client_and_server_ssl_connections(csp);
3607 #endif /* def FEATURE_HTTPS_INSPECTION */
3609 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3610 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3611 (size_t)csp->content_length, write_delay))
3613 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3616 mark_server_socket_tainted(csp);
3625 break; /* "game over, man" */
3629 * This is not the body, so let's pretend the server just sent
3632 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3633 len = (int)strlen(csp->receive_buffer);
3636 * Now, let the normal header parsing algorithm below do its
3637 * job. If it fails, we'll exit instead of continuing.
3644 * If we're in the body of the server document, just write it to
3645 * the client, unless we need to buffer the body for later
3646 * content-filtering.
3648 if (server_body || (http->ssl
3649 #ifdef FEATURE_HTTPS_INSPECTION
3654 if (buffer_and_filter_content)
3657 * If there is no memory left for buffering the content, or the buffer limit
3658 * has been reached, switch to non-filtering mode, i.e. make & write the
3659 * header, flush the iob and buf, and get out of the way.
3661 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3666 log_error(LOG_LEVEL_INFO,
3667 "Flushing header and buffers. Stepping back from filtering.");
3669 hdr = list_to_text(csp->headers);
3673 * Memory is too tight to even generate the header.
3674 * Send our static "Out-of-memory" page.
3676 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3677 rsp = cgi_error_memory();
3678 send_crunch_response(csp, rsp);
3679 mark_server_socket_tainted(csp);
3680 #ifdef FEATURE_HTTPS_INSPECTION
3681 close_client_and_server_ssl_connections(csp);
3685 hdrlen = strlen(hdr);
3687 #ifdef FEATURE_HTTPS_INSPECTION
3689 * Sending data with standard or secured connection (HTTP/HTTPS)
3691 if (client_use_ssl(csp))
3693 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3694 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3695 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3697 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3698 (const unsigned char *)csp->receive_buffer, (size_t)len,
3699 get_write_delay(csp)) < 0))
3701 log_error(LOG_LEVEL_CONNECT,
3702 "Flush header and buffers to client failed");
3704 mark_server_socket_tainted(csp);
3705 close_client_and_server_ssl_connections(csp);
3710 #endif /* def FEATURE_HTTPS_INSPECTION */
3712 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3713 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3714 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3717 log_error(LOG_LEVEL_CONNECT,
3718 "Flush header and buffers to client failed: %E");
3720 mark_server_socket_tainted(csp);
3726 * Reset the byte_count to the amount of bytes
3727 * we just flushed. len will be added a few lines below,
3728 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3730 byte_count = (unsigned long long)flushed;
3732 buffer_and_filter_content = 0;
3738 #ifdef FEATURE_HTTPS_INSPECTION
3740 * Sending data with standard or secured connection (HTTP/HTTPS)
3742 if (client_use_ssl(csp))
3744 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3745 (const unsigned char *)csp->receive_buffer, (size_t)len,
3746 get_write_delay(csp));
3749 log_error(LOG_LEVEL_ERROR,
3750 "Sending data to client failed");
3751 mark_server_socket_tainted(csp);
3752 close_client_and_server_ssl_connections(csp);
3757 #endif /* def FEATURE_HTTPS_INSPECTION */
3759 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3760 (size_t)len, write_delay))
3762 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3763 mark_server_socket_tainted(csp);
3768 byte_count += (unsigned long long)len;
3774 * We're still looking for the end of the server's header.
3775 * Buffer up the data we just read. If that fails, there's
3776 * little we can do but send our static out-of-memory page.
3778 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3780 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3781 rsp = cgi_error_memory();
3782 send_crunch_response(csp, rsp);
3783 mark_server_socket_tainted(csp);
3784 #ifdef FEATURE_HTTPS_INSPECTION
3785 close_client_and_server_ssl_connections(csp);
3790 /* Convert iob into something sed() can digest */
3791 if (JB_ERR_PARSE == get_server_headers(csp))
3796 * Well, we tried our MS IIS/5 hack and it didn't work.
3797 * The header is incomplete and there isn't anything
3798 * we can do about it.
3800 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3801 "Applying the MS IIS5 hack didn't help.");
3802 log_error(LOG_LEVEL_CLF,
3803 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3804 #ifdef FEATURE_HTTPS_INSPECTION
3806 * Sending data with standard or secured connection (HTTP/HTTPS)
3808 if (client_use_ssl(csp))
3810 ssl_send_data_delayed(&(csp->ssl_client_attr),
3811 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3812 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3815 #endif /* def FEATURE_HTTPS_INSPECTION */
3817 write_socket_delayed(csp->cfd,
3818 INVALID_SERVER_HEADERS_RESPONSE,
3819 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3821 mark_server_socket_tainted(csp);
3822 #ifdef FEATURE_HTTPS_INSPECTION
3823 close_client_and_server_ssl_connections(csp);
3830 * Since we have to wait for more from the server before
3831 * we can parse the headers we just continue here.
3833 log_error(LOG_LEVEL_CONNECT,
3834 "Continuing buffering server headers from socket %d. "
3835 "Bytes most recently read: %ld.", csp->cfd, len);
3842 * Account for the content bytes we
3843 * might have gotten with the headers.
3845 assert(csp->iob->eod >= csp->iob->cur);
3846 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3849 /* Did we actually get anything? */
3850 if (NULL == csp->headers->first)
3852 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3854 log_error(LOG_LEVEL_ERROR,
3855 "No server or forwarder response received on socket %d. "
3856 "Closing client socket %d without sending data.",
3857 csp->server_connection.sfd, csp->cfd);
3858 log_error(LOG_LEVEL_CLF,
3859 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3863 log_error(LOG_LEVEL_ERROR,
3864 "No server or forwarder response received on socket %d.",
3865 csp->server_connection.sfd);
3866 send_crunch_response(csp, error_response(csp, "no-server-data"));
3868 free_http_request(http);
3869 mark_server_socket_tainted(csp);
3870 #ifdef FEATURE_HTTPS_INSPECTION
3871 close_client_and_server_ssl_connections(csp);
3876 if (!csp->headers->first->str)
3878 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3880 assert(csp->headers->first->str);
3882 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3883 strncmpic(csp->headers->first->str, "ICY", 3))
3886 * It doesn't look like a HTTP (or Shoutcast) response:
3887 * tell the client and log the problem.
3889 if (strlen(csp->headers->first->str) > 30)
3891 csp->headers->first->str[30] = '\0';
3893 log_error(LOG_LEVEL_ERROR,
3894 "Invalid server or forwarder response. Starts with: %s",
3895 csp->headers->first->str);
3896 log_error(LOG_LEVEL_CLF,
3897 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3898 #ifdef FEATURE_HTTPS_INSPECTION
3900 * Sending data with standard or secured connection (HTTP/HTTPS)
3902 if (client_use_ssl(csp))
3904 ssl_send_data_delayed(&(csp->ssl_client_attr),
3905 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3906 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3907 get_write_delay(csp));
3910 #endif /* def FEATURE_HTTPS_INSPECTION */
3912 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3913 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3915 free_http_request(http);
3916 mark_server_socket_tainted(csp);
3917 #ifdef FEATURE_HTTPS_INSPECTION
3918 close_client_and_server_ssl_connections(csp);
3924 * Disable redirect checkers, so that they will be only run
3925 * again if the user also enables them through tags.
3927 * From a performance point of view it doesn't matter,
3928 * but it prevents duplicated log messages.
3930 #ifdef FEATURE_FAST_REDIRECTS
3931 csp->action->flags &= ~ACTION_FAST_REDIRECTS;
3933 csp->action->flags &= ~ACTION_REDIRECT;
3936 * We have now received the entire server header,
3937 * filter it and send the result to the client
3939 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3941 log_error(LOG_LEVEL_CLF,
3942 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3943 #ifdef FEATURE_HTTPS_INSPECTION
3945 * Sending data with standard or secured connection (HTTP/HTTPS)
3947 if (client_use_ssl(csp))
3949 ssl_send_data_delayed(&(csp->ssl_client_attr),
3950 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3951 strlen(INVALID_SERVER_HEADERS_RESPONSE),
3952 get_write_delay(csp));
3957 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3958 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3960 free_http_request(http);
3961 mark_server_socket_tainted(csp);
3962 #ifdef FEATURE_HTTPS_INSPECTION
3963 close_client_and_server_ssl_connections(csp);
3967 hdr = list_to_text(csp->headers);
3970 /* FIXME Should handle error properly */
3971 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3974 if ((csp->flags & CSP_FLAG_CHUNKED)
3975 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3976 && ((csp->iob->eod - csp->iob->cur) >= 5)
3977 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3979 log_error(LOG_LEVEL_CONNECT,
3980 "Looks like we got the last chunk together with "
3981 "the server headers. We better stop reading.");
3982 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3983 csp->expected_content_length = byte_count;
3984 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3987 csp->server_connection.response_received = time(NULL);
3989 if (crunch_response_triggered(csp, crunchers_light))
3992 * One of the tags created by a server-header
3993 * tagger triggered a crunch. We already
3994 * delivered the crunch response to the client
3995 * and are done here after cleaning up.
3998 mark_server_socket_tainted(csp);
3999 #ifdef FEATURE_HTTPS_INSPECTION
4000 close_client_and_server_ssl_connections(csp);
4005 /* Buffer and pcrs filter this if appropriate. */
4006 buffer_and_filter_content = content_requires_filtering(csp);
4008 if (!buffer_and_filter_content)
4011 * Write the server's (modified) header to
4012 * the client (along with anything else that
4013 * may be in the buffer). Use standard or secured
4016 #ifdef FEATURE_HTTPS_INSPECTION
4017 if (client_use_ssl(csp))
4019 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
4020 (const unsigned char *)hdr, strlen(hdr),
4021 get_write_delay(csp)) < 0)
4022 || ((len = ssl_flush_socket(&(csp->ssl_client_attr),
4025 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
4028 * The write failed, so don't bother mentioning it
4029 * to the client... it probably can't hear us anyway.
4032 mark_server_socket_tainted(csp);
4033 #ifdef FEATURE_HTTPS_INSPECTION
4034 close_client_and_server_ssl_connections(csp);
4040 #endif /* def FEATURE_HTTPS_INSPECTION */
4042 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
4043 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
4045 log_error(LOG_LEVEL_ERROR,
4046 "write header to client failed");
4048 * The write failed, so don't bother mentioning it
4049 * to the client... it probably can't hear us anyway.
4052 mark_server_socket_tainted(csp);
4058 /* we're finished with the server's header */
4064 * If this was a MS IIS/5 hack then it means the server
4065 * has already closed the connection. Nothing more to read.
4070 log_error(LOG_LEVEL_ERROR,
4071 "Closed server connection detected. "
4072 "Applying the MS IIS5 hack didn't help.");
4073 log_error(LOG_LEVEL_CLF,
4074 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
4075 #ifdef FEATURE_HTTPS_INSPECTION
4077 * Sending data with standard or secured connection (HTTP/HTTPS)
4079 if (client_use_ssl(csp))
4081 ssl_send_data_delayed(&(csp->ssl_client_attr),
4082 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
4083 strlen(INVALID_SERVER_HEADERS_RESPONSE),
4084 get_write_delay(csp));
4087 #endif /* def FEATURE_HTTPS_INSPECTION */
4089 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
4090 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
4092 mark_server_socket_tainted(csp);
4093 #ifdef FEATURE_HTTPS_INSPECTION
4094 close_client_and_server_ssl_connections(csp);
4101 mark_server_socket_tainted(csp);
4102 #ifdef FEATURE_HTTPS_INSPECTION
4103 close_client_and_server_ssl_connections(csp);
4105 return; /* huh? we should never get here */
4108 if (csp->content_length == 0)
4111 * If Privoxy didn't recalculate the Content-Length,
4112 * byte_count is still correct.
4114 csp->content_length = byte_count;
4117 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4118 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
4119 && (csp->expected_content_length != byte_count))
4121 log_error(LOG_LEVEL_CONNECT,
4122 "Received %llu bytes while expecting %llu.",
4123 byte_count, csp->expected_content_length);
4124 mark_server_socket_tainted(csp);
4128 #ifdef FEATURE_HTTPS_INSPECTION
4129 if (client_use_ssl(csp))
4131 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" 200 %llu",
4132 csp->ip_addr_str, http->gpc, http->hostport, http->path,
4133 http->version, csp->content_length);
4138 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
4139 csp->ip_addr_str, http->ocmd, csp->content_length);
4141 csp->server_connection.timestamp = time(NULL);
4145 /*********************************************************************
4149 * Description : Once a connection from the client has been accepted,
4150 * this function is called (via serve()) to handle the
4151 * main business of the communication. This function
4152 * returns after dealing with a single request. It can
4153 * be called multiple times with the same client socket
4154 * if the client is keeping the connection alive.
4156 * The decision whether or not a client connection will
4157 * be kept alive is up to the caller which also must
4158 * close the client socket when done.
4160 * FIXME: chat is nearly thousand lines long.
4164 * 1 : csp = Current client state (buffers, headers, etc...)
4166 * Returns : Nothing.
4168 *********************************************************************/
4169 static void chat(struct client_state *csp)
4171 const struct forward_spec *fwd;
4172 struct http_request *http;
4173 /* Skeleton for HTTP response, if we should intercept the request */
4174 struct http_response *rsp;
4175 #ifdef FEATURE_HTTPS_INSPECTION
4176 int use_ssl_tunnel = 0;
4181 if (receive_client_request(csp) != JB_ERR_OK)
4186 #if defined(FEATURE_STATISTICS) && defined(MUTEX_LOCKS_AVAILABLE)
4187 privoxy_mutex_lock(&block_statistics_mutex);
4188 number_of_requests_received++;
4189 privoxy_mutex_unlock(&block_statistics_mutex);
4192 if (parse_client_request(csp) != JB_ERR_OK)
4197 #ifdef FEATURE_HTTPS_INSPECTION
4199 * Setting flags to use old solution with SSL tunnel and to disable
4200 * certificate verification.
4202 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION)
4203 && !cgi_page_requested(csp->http->host))
4208 if (http->ssl && (csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS))
4210 csp->dont_verify_certificate = 1;
4215 * build the http request to send to the server
4216 * we have to do one of the following:
4218 * create = use the original HTTP request to create a new
4219 * HTTP request that has either the path component
4220 * without the http://domainspec (w/path) or the
4221 * full orininal URL (w/url)
4222 * Note that the path and/or the HTTP version may
4223 * have been altered by now.
4225 * SSL proxy = Open a socket to the host:port of the server
4226 * and create TLS/SSL connection with server and
4227 * with client. Then behave like mediator between
4228 * client and server over TLS/SSL.
4230 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
4231 * with request to a parent proxy. Note that we'll be sending
4232 * forwarding the CFAIL message ourselves if connecting to the parent
4233 * fails, but we won't send a CSUCCEED message if it works,
4234 * since that would result in a double message (ours and the
4235 * parent's). After sending the request to the parent, we
4236 * must parse answer and send it to client. If connection
4237 * with server is established, we do TLS/SSL proxy. Otherwise
4238 * we send parent response to client and close connections.
4240 * here's the matrix:
4243 * +--------+--------+
4245 * 0 | create | SSL |
4246 * | w/path | proxy |
4247 * Forwarding +--------+--------+
4249 * 1 | create | proxy |
4250 * | w/url |+forward|
4251 * +--------+--------+
4255 #ifdef FEATURE_HTTPS_INSPECTION
4257 * Presetting SSL client and server flags
4259 if (http->ssl && !use_ssl_tunnel)
4261 http->client_ssl = 1;
4262 http->server_ssl = 1;
4266 http->client_ssl = 0;
4267 http->server_ssl = 0;
4271 #ifdef FEATURE_HTTPS_INSPECTION
4273 * Log the request unless we're https inspecting
4274 * in which case we don't have the path yet and
4275 * will log the request later.
4277 if (!client_use_ssl(csp))
4280 log_error(LOG_LEVEL_REQUEST, "%s%s", http->hostport, http->path);
4283 if (http->ssl && connect_port_is_forbidden(csp))
4285 const char *acceptable_connect_ports =
4286 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
4287 assert(NULL != acceptable_connect_ports);
4288 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
4289 "limit-connect{%s} doesn't allow CONNECT requests to %s",
4290 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
4291 csp->action->flags |= ACTION_BLOCK;
4293 #ifdef FEATURE_HTTPS_INSPECTION
4294 http->client_ssl = 0;
4295 http->server_ssl = 0;
4300 * We have a request. Check if one of the crunchers wants it
4301 * unless the client wants to use TLS/SSL in which case we
4302 * haven't setup the TLS context yet and will send the crunch
4306 #ifdef FEATURE_HTTPS_INSPECTION
4307 !client_use_ssl(csp) &&
4309 crunch_response_triggered(csp, crunchers_all))
4312 * Yes. The client got the crunch response and we're done here.
4317 #ifdef FEATURE_HTTPS_INSPECTION
4318 if (client_use_ssl(csp) && !use_ssl_tunnel)
4322 * Creating a SSL proxy.
4324 * By sending the CSUCCEED message we're lying to the client as
4325 * the connection hasn't actually been established yet. We don't
4326 * establish the connection until we have seen and parsed the
4327 * encrypted client headers.
4329 if (write_socket_delayed(csp->cfd, CSUCCEED,
4330 strlen(CSUCCEED), get_write_delay(csp)) != 0)
4332 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
4336 ret = create_client_ssl_connection(csp);
4339 log_error(LOG_LEVEL_ERROR,
4340 "Failed to open a secure connection with the client");
4343 if (JB_ERR_OK != process_encrypted_request_headers(csp))
4345 close_client_ssl_connection(csp);
4349 * We have an encrypted request. Check if one of the crunchers now
4350 * wants it (for example because the previously invisible path was
4351 * required to match).
4353 if (crunch_response_triggered(csp, crunchers_all))
4356 * Yes. The client got the crunch response and we're done here.
4363 /* If we need to apply client body filters, buffer the whole request now. */
4364 if (csp->expected_client_content_length != 0 &&
4365 client_body_filters_enabled(csp->action) && can_filter_request_body(csp))
4367 int content_modified;
4368 size_t modified_content_length;
4370 #ifdef FEATURE_HTTPS_INSPECTION
4371 if (client_use_ssl(csp) && read_https_request_body(csp))
4373 log_error(LOG_LEVEL_ERROR,
4374 "Failed to buffer the encrypted request body to apply filters");
4375 log_error(LOG_LEVEL_CLF,
4376 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, csp->http->cmd);
4378 ssl_send_data_delayed(&(csp->ssl_client_attr),
4379 (const unsigned char *)CLIENT_BODY_BUFFER_ERROR_RESPONSE,
4380 strlen(CLIENT_BODY_BUFFER_ERROR_RESPONSE),
4381 get_write_delay(csp));
4387 if (read_http_request_body(csp))
4389 log_error(LOG_LEVEL_ERROR,
4390 "Failed to buffer the request body to apply filters");
4391 log_error(LOG_LEVEL_CLF,
4392 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, csp->http->cmd);
4394 write_socket_delayed(csp->cfd, CLIENT_BODY_BUFFER_ERROR_RESPONSE,
4395 strlen(CLIENT_BODY_BUFFER_ERROR_RESPONSE), get_write_delay(csp));
4399 modified_content_length = csp->expected_client_content_length;
4400 content_modified = execute_client_body_filters(csp,
4401 &modified_content_length);
4402 if ((content_modified == 1) &&
4403 (modified_content_length != csp->expected_client_content_length) &&
4404 update_client_headers(csp, modified_content_length))
4406 /* XXX: Send error response */
4407 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
4410 csp->expected_client_content_length = 0;
4413 log_applied_actions(csp->action);
4415 /* decide how to route the HTTP request */
4416 fwd = forward_url(csp, http);
4418 freez(csp->headers->first->str);
4419 build_request_line(csp, fwd, &csp->headers->first->str);
4421 if (fwd->forward_host)
4423 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
4424 fwd->forward_host, fwd->forward_port, http->hostport);
4428 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
4431 /* here we connect to the server, gateway, or the forwarder */
4433 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4434 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
4435 && socket_is_still_alive(csp->server_connection.sfd)
4436 && connection_destination_matches(&csp->server_connection, http, fwd))
4438 log_error(LOG_LEVEL_CONNECT,
4439 "Reusing server socket %d connected to %s. Total requests: %u.",
4440 csp->server_connection.sfd, csp->server_connection.host,
4441 csp->server_connection.requests_sent_total);
4445 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
4447 #ifdef FEATURE_CONNECTION_SHARING
4448 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING
4449 #ifdef FEATURE_HTTPS_INSPECTION
4450 && !server_use_ssl(csp)
4454 remember_connection(&csp->server_connection);
4457 #endif /* def FEATURE_CONNECTION_SHARING */
4459 log_error(LOG_LEVEL_CONNECT,
4460 "Closing server socket %d connected to %s. Total requests: %u.",
4461 csp->server_connection.sfd, csp->server_connection.host,
4462 csp->server_connection.requests_sent_total);
4463 close_socket(csp->server_connection.sfd);
4465 mark_connection_closed(&csp->server_connection);
4467 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4470 * Connecting to destination server
4472 csp->server_connection.sfd = forwarded_connect(fwd, http, csp);
4474 if (csp->server_connection.sfd == JB_INVALID_SOCKET)
4476 if (fwd->type != SOCKS_NONE)
4479 rsp = error_response(csp, "forwarding-failed");
4481 else if (errno == EINVAL)
4483 rsp = error_response(csp, "no-such-domain");
4487 rsp = error_response(csp, "connect-failed");
4490 /* Write the answer to the client */
4493 send_crunch_response(csp, rsp);
4497 * Temporary workaround to prevent already-read client
4498 * bodies from being parsed as new requests. For now we
4499 * err on the safe side and throw all the following
4500 * requests under the bus, even if no client body has been
4501 * buffered. A compliant client will repeat the dropped
4502 * requests on an untainted connection.
4504 * The proper fix is to discard the no longer needed
4505 * client body in the buffer (if there is one) and to
4506 * continue parsing the bytes that follow.
4508 #ifdef FEATURE_HTTPS_INSPECTION
4509 close_client_ssl_connection(csp);
4511 drain_and_close_socket(csp->cfd);
4512 csp->cfd = JB_INVALID_SOCKET;
4517 #ifdef FEATURE_HTTPS_INSPECTION
4519 * Creating TLS/SSL connections with destination server or parent
4520 * proxy. If forwarding is enabled, we must send client request to
4521 * parent proxy and receive, parse and resend parent proxy answer.
4523 if (http->ssl && !use_ssl_tunnel)
4525 if (fwd->forward_host != NULL)
4527 char server_response[BUFFER_SIZE];
4530 char *hdr = list_to_text(csp->headers);
4531 memset(server_response, 0, sizeof(server_response));
4535 log_error(LOG_LEVEL_FATAL,
4536 "Out of memory parsing client header");
4538 list_remove_all(csp->headers);
4541 * Sending client's CONNECT request to the parent proxy
4543 ret = write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
4549 log_error(LOG_LEVEL_CONNECT,
4550 "Sending request headers to: %s failed", http->hostport);
4551 mark_server_socket_tainted(csp);
4552 close_client_ssl_connection(csp);
4556 /* Waiting for parent proxy server response */
4557 len = read_socket(csp->server_connection.sfd, server_response,
4558 sizeof(server_response)-1);
4562 log_error(LOG_LEVEL_ERROR, "No response from parent proxy "
4563 "server on socket %d.", csp->server_connection.sfd);
4565 rsp = error_response(csp, "no-server-data");
4568 send_crunch_response(csp, rsp);
4570 mark_server_socket_tainted(csp);
4571 close_client_ssl_connection(csp);
4576 * Test if the connection to the destination server was
4577 * established successfully by the parent proxy.
4579 if (!tunnel_established_successfully(server_response, (unsigned int)len))
4581 log_error(LOG_LEVEL_ERROR,
4582 "The forwarder %s failed to establish a connection with %s",
4583 fwd->forward_host, http->host);
4584 rsp = error_response(csp, "connect-failed");
4587 send_crunch_response(csp, rsp);
4589 mark_server_socket_tainted(csp);
4590 close_client_ssl_connection(csp);
4593 } /* -END- if (fwd->forward_host != NULL) */
4596 * We can now create the TLS/SSL connection with the destination server.
4598 int ret = create_server_ssl_connection(csp);
4601 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4602 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4605 * If the server certificate is invalid, we must inform
4606 * the client and then close connection to the client.
4608 ssl_send_certificate_error(csp);
4609 close_client_and_server_ssl_connections(csp);
4612 if (csp->server_cert_verification_result == SSL_CERT_NOT_VERIFIED
4613 || csp->server_cert_verification_result == SSL_CERT_VALID)
4616 * The TLS/SSL connection wasn't created but an invalid
4617 * certificate wasn't detected. Report it as connection
4620 rsp = error_response(csp, "connect-failed");
4623 send_crunch_response(csp, rsp);
4625 close_client_and_server_ssl_connections(csp);
4629 }/* -END- if (http->ssl) */
4630 #endif /* def FEATURE_HTTPS_INSPECTION */
4632 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4633 save_connection_destination(csp->server_connection.sfd,
4634 http, fwd, &csp->server_connection);
4635 csp->server_connection.keep_alive_timeout =
4636 (unsigned)csp->config->keep_alive_timeout;
4638 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4640 csp->server_connection.requests_sent_total++;
4642 if ((fwd->type == SOCKS_5T) && (NULL == csp->headers->first))
4644 /* Client headers have been sent optimistically */
4645 assert(csp->headers->last == NULL);
4647 else if (http->ssl == 0 || (fwd->forward_host
4648 #ifdef FEATURE_HTTPS_INSPECTION
4653 if (send_http_request(csp))
4655 rsp = error_response(csp, "connect-failed");
4658 send_crunch_response(csp, rsp);
4666 * Using old solution with SSL tunnel or new solution with SSL proxy
4668 list_remove_all(csp->headers);
4669 #ifdef FEATURE_HTTPS_INSPECTION
4674 * We're running an SSL tunnel and we're not forwarding,
4675 * so just ditch the client headers, send the "connect succeeded"
4676 * message to the client, flush the rest, and get out of the way.
4678 if (write_socket_delayed(csp->cfd, CSUCCEED,
4679 strlen(CSUCCEED), get_write_delay(csp)))
4684 #ifdef FEATURE_HTTPS_INSPECTION
4688 * If server certificate has been verified and is invalid,
4689 * we must inform the client and then close the connection
4690 * with client and server.
4692 if (csp->server_cert_verification_result != SSL_CERT_VALID &&
4693 csp->server_cert_verification_result != SSL_CERT_NOT_VERIFIED)
4695 ssl_send_certificate_error(csp);
4696 close_client_and_server_ssl_connections(csp);
4699 if (send_https_request(csp))
4701 rsp = error_response(csp, "connect-failed");
4704 send_crunch_response(csp, rsp);
4706 close_client_and_server_ssl_connections(csp);
4710 #endif /* def FEATURE_HTTPS_INSPECTION */
4711 clear_iob(csp->client_iob);
4712 }/* -END- else ... if (http->ssl == 1) */
4714 log_error(LOG_LEVEL_CONNECT, "to %s successful", http->hostport);
4716 /* XXX: should the time start earlier for optimistically sent data? */
4717 csp->server_connection.request_sent = time(NULL);
4719 handle_established_connection(csp);
4720 freez(csp->receive_buffer);
4725 /*********************************************************************
4727 * Function : fuzz_server_response
4729 * Description : Treat the input as a whole server response.
4732 * 1 : csp = Current client state (buffers, headers, etc...)
4733 * 2 : fuzz_input_file = File to read the input from.
4737 *********************************************************************/
4738 extern int fuzz_server_response(struct client_state *csp, char *fuzz_input_file)
4740 static struct forward_spec fwd; /* Zero'd due to being static */
4743 if (strcmp(fuzz_input_file, "-") == 0)
4745 /* XXX: Doesn't work yet. */
4746 csp->server_connection.sfd = 0;
4750 csp->server_connection.sfd = open(fuzz_input_file, O_RDONLY);
4751 if (csp->server_connection.sfd == -1)
4753 log_error(LOG_LEVEL_FATAL, "Failed to open %s: %E",
4758 csp->content_type |= CT_GIF;
4759 csp->action->flags |= ACTION_DEANIMATE;
4760 csp->action->string[ACTION_STRING_DEANIMATE] = "last";
4762 csp->http->path = strdup_or_die("/");
4763 csp->http->host = strdup_or_die("fuzz.example.org");
4764 csp->http->hostport = strdup_or_die("fuzz.example.org:80");
4765 /* Prevent client socket monitoring */
4766 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4767 csp->flags |= CSP_FLAG_CHUNKED;
4769 csp->config->feature_flags |= RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE;
4770 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4772 csp->content_type |= CT_DECLARED|CT_GIF;
4774 csp->config->socket_timeout = 0;
4776 cgi_init_error_messages();
4778 handle_established_connection(csp);
4779 freez(csp->receive_buffer);
4786 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4787 /*********************************************************************
4789 * Function : prepare_csp_for_next_request
4791 * Description : Put the csp in a mostly vergin state.
4794 * 1 : csp = Current client state (buffers, headers, etc...)
4798 *********************************************************************/
4799 static void prepare_csp_for_next_request(struct client_state *csp)
4801 csp->content_type = 0;
4802 csp->content_length = 0;
4803 csp->expected_content_length = 0;
4804 csp->expected_client_content_length = 0;
4805 list_remove_all(csp->headers);
4806 clear_iob(csp->iob);
4807 freez(csp->error_message);
4808 free_http_request(csp->http);
4809 destroy_list(csp->headers);
4810 #ifdef FEATURE_HTTPS_INSPECTION
4811 destroy_list(csp->https_headers);
4813 destroy_list(csp->tags);
4814 #ifdef FEATURE_CLIENT_TAGS
4815 destroy_list(csp->client_tags);
4816 freez(csp->client_address);
4818 free_current_action(csp->action);
4819 if (NULL != csp->fwd)
4821 unload_forward_spec(csp->fwd);
4824 /* XXX: Store per-connection flags someplace else. */
4825 csp->flags = (CSP_FLAG_ACTIVE | CSP_FLAG_REUSED_CLIENT_CONNECTION);
4826 #ifdef FEATURE_TOGGLE
4827 if (global_toggle_state)
4828 #endif /* def FEATURE_TOGGLE */
4830 csp->flags |= CSP_FLAG_TOGGLED_ON;
4833 if (csp->client_iob->eod > csp->client_iob->cur)
4835 long bytes_to_shift = csp->client_iob->cur - csp->client_iob->buf;
4836 size_t data_length = (size_t)(csp->client_iob->eod - csp->client_iob->cur);
4838 assert(bytes_to_shift > 0);
4839 assert(data_length > 0);
4841 log_error(LOG_LEVEL_CONNECT, "Shifting %lu pipelined bytes by %ld bytes",
4842 data_length, bytes_to_shift);
4843 memmove(csp->client_iob->buf, csp->client_iob->cur, data_length);
4844 csp->client_iob->cur = csp->client_iob->buf;
4845 assert(csp->client_iob->eod == csp->client_iob->buf + bytes_to_shift + data_length);
4846 csp->client_iob->eod = csp->client_iob->buf + data_length;
4847 memset(csp->client_iob->eod, '\0', (size_t)bytes_to_shift);
4849 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
4854 * We mainly care about resetting client_iob->cur so we don't
4855 * waste buffer space at the beginning and don't mess up the
4856 * request restoration done by cgi_show_request().
4858 * Freeing the buffer itself isn't technically necessary,
4859 * but makes debugging more convenient.
4861 clear_iob(csp->client_iob);
4864 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
4867 /*********************************************************************
4871 * Description : This is little more than chat. We only "serve" to
4872 * to close (or remember) any socket that chat may have
4876 * 1 : csp = Current client state (buffers, headers, etc...)
4880 *********************************************************************/
4881 static void serve(struct client_state *csp)
4883 int config_file_change_detected = 0; /* Only used for debugging */
4884 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
4885 #ifdef FEATURE_CONNECTION_SHARING
4886 static int monitor_thread_running = 0;
4887 #endif /* def FEATURE_CONNECTION_SHARING */
4888 int continue_chatting = 0;
4890 log_error(LOG_LEVEL_CONNECT, "Accepted connection from %s on socket %d",
4891 csp->ip_addr_str, csp->cfd);
4895 unsigned int latency;
4897 #ifdef FEATURE_HTTPS_INSPECTION
4898 if (continue_chatting && client_use_ssl(csp))
4900 continue_https_chat(csp);
4909 * If the request has been crunched,
4910 * the calculated latency is zero.
4912 latency = (unsigned)(csp->server_connection.response_received -
4913 csp->server_connection.request_sent) / 2;
4915 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4916 && (csp->flags & CSP_FLAG_CRUNCHED)
4917 && (csp->expected_client_content_length != 0))
4919 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
4920 log_error(LOG_LEVEL_CONNECT,
4921 "Tainting client socket %d due to unread data.", csp->cfd);
4924 continue_chatting = (csp->config->feature_flags
4925 & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
4926 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4927 && (csp->cfd != JB_INVALID_SOCKET)
4928 && (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
4929 && ((csp->flags & CSP_FLAG_SERVER_CONTENT_LENGTH_SET)
4930 || (csp->flags & CSP_FLAG_CHUNKED));
4932 if (!(csp->flags & CSP_FLAG_CRUNCHED)
4933 && (csp->server_connection.sfd != JB_INVALID_SOCKET))
4935 if (!(csp->flags & CSP_FLAG_SERVER_KEEP_ALIVE_TIMEOUT_SET))
4937 csp->server_connection.keep_alive_timeout = csp->config->default_server_timeout;
4939 if (!(csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
4940 || (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED)
4941 || !socket_is_still_alive(csp->server_connection.sfd)
4942 || !(latency < csp->server_connection.keep_alive_timeout))
4944 log_error(LOG_LEVEL_CONNECT,
4945 "Closing server socket %d connected to %s. "
4946 "Keep-alive: %u. Tainted: %u. Socket alive: %u. Timeout: %u.",
4947 csp->server_connection.sfd, (csp->server_connection.host != NULL) ?
4948 csp->server_connection.host : csp->http->host,
4949 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
4950 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
4951 socket_is_still_alive(csp->server_connection.sfd),
4952 csp->server_connection.keep_alive_timeout);
4953 #ifdef FEATURE_CONNECTION_SHARING
4954 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
4956 forget_connection(csp->server_connection.sfd);
4958 #endif /* def FEATURE_CONNECTION_SHARING */
4959 #ifdef FEATURE_HTTPS_INSPECTION
4960 close_server_ssl_connection(csp);
4962 close_socket(csp->server_connection.sfd);
4963 mark_connection_closed(&csp->server_connection);
4964 #ifdef FEATURE_HTTPS_INSPECTION
4965 if (continue_chatting && client_use_ssl(csp))
4968 * Close the client socket as well as Privoxy currently
4969 * can't establish a new server connection when the client
4970 * socket is reused and would drop the connection in
4971 * continue_https_chat() anyway.
4973 continue_chatting = 0;
4974 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
4975 log_error(LOG_LEVEL_CONNECT,
4976 "Client socket %d is no longer usable. "
4977 "The server socket has been closed.", csp->cfd);
4983 if (continue_chatting && any_loaded_file_changed(csp))
4985 continue_chatting = 0;
4986 config_file_change_detected = 1;
4988 #ifdef FEATURE_HTTPS_INSPECTION
4989 if (continue_chatting && client_use_ssl(csp) &&
4990 csp->ssl_with_client_is_opened == 0)
4992 continue_chatting = 0;
4993 log_error(LOG_LEVEL_CONNECT, "Client socket %d is no longer usable. "
4994 "The TLS session has been terminated.", csp->cfd);
4998 if (continue_chatting)
5000 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
5001 && socket_is_still_alive(csp->cfd))
5003 log_error(LOG_LEVEL_CONNECT, "Client request %d has been "
5004 "pipelined on socket %d and the socket is still alive.",
5005 csp->requests_received_total+1, csp->cfd);
5006 prepare_csp_for_next_request(csp);
5010 if (0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE))
5012 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5014 log_error(LOG_LEVEL_CONNECT,
5015 "Waiting for the next client request on socket %d. "
5016 "Keeping the server socket %d to %s open.",
5017 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
5021 log_error(LOG_LEVEL_CONNECT,
5022 "Waiting for the next client request on socket %d. "
5023 "No server socket to keep open.", csp->cfd);
5027 if ((csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE)
5028 && data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout)
5029 && socket_is_still_alive(csp->cfd))
5031 log_error(LOG_LEVEL_CONNECT,
5032 "Data arrived in time on client socket %d. Requests so far: %u",
5033 csp->cfd, csp->requests_received_total);
5034 prepare_csp_for_next_request(csp);
5038 #ifdef FEATURE_CONNECTION_SHARING
5039 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5040 && (csp->server_connection.sfd != JB_INVALID_SOCKET)
5041 && (socket_is_still_alive(csp->server_connection.sfd))
5042 #ifdef FEATURE_HTTPS_INSPECTION
5043 && !server_use_ssl(csp)
5047 time_t time_open = time(NULL) - csp->server_connection.timestamp;
5049 if (csp->server_connection.keep_alive_timeout < time_open - (time_t)latency)
5054 remember_connection(&csp->server_connection);
5055 csp->server_connection.sfd = JB_INVALID_SOCKET;
5056 drain_and_close_socket(csp->cfd);
5057 csp->cfd = JB_INVALID_SOCKET;
5058 privoxy_mutex_lock(&connection_reuse_mutex);
5059 if (!monitor_thread_running)
5061 monitor_thread_running = 1;
5062 privoxy_mutex_unlock(&connection_reuse_mutex);
5063 wait_for_alive_connections();
5064 privoxy_mutex_lock(&connection_reuse_mutex);
5065 monitor_thread_running = 0;
5067 privoxy_mutex_unlock(&connection_reuse_mutex);
5069 #endif /* def FEATURE_CONNECTION_SHARING */
5073 else if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5075 log_error(LOG_LEVEL_CONNECT,
5076 "Closing server socket %d connected to %s. Keep-alive: %u. "
5077 "Tainted: %u. Socket alive: %u. Timeout: %u. "
5078 "Configuration file change detected: %u",
5079 csp->server_connection.sfd, csp->server_connection.host,
5080 0 != (csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE),
5081 0 != (csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED),
5082 socket_is_still_alive(csp->server_connection.sfd),
5083 csp->server_connection.keep_alive_timeout,
5084 config_file_change_detected);
5086 } while (continue_chatting);
5090 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
5092 if (csp->cfd != JB_INVALID_SOCKET)
5094 log_error(LOG_LEVEL_CONNECT, "Closing client socket %d. "
5095 "Keep-alive: %u. Socket alive: %u. Data available: %u. "
5096 "Configuration file change detected: %u. Requests received: %u.",
5097 csp->cfd, 0 != (csp->flags & CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE),
5098 socket_is_still_alive(csp->cfd), data_is_available(csp->cfd, 0),
5099 config_file_change_detected, csp->requests_received_total);
5100 #ifdef FEATURE_HTTPS_INSPECTION
5101 close_client_ssl_connection(csp);
5103 drain_and_close_socket(csp->cfd);
5106 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
5108 #ifdef FEATURE_CONNECTION_SHARING
5109 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
5111 forget_connection(csp->server_connection.sfd);
5113 #endif /* def FEATURE_CONNECTION_SHARING */
5115 #ifdef FEATURE_HTTPS_INSPECTION
5116 close_server_ssl_connection(csp);
5117 #endif /* def FEATURE_HTTPS_INSPECTION */
5119 close_socket(csp->server_connection.sfd);
5122 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
5123 mark_connection_closed(&csp->server_connection);
5126 free_csp_resources(csp);
5128 csp->flags &= ~CSP_FLAG_ACTIVE;
5134 /*********************************************************************
5136 * Function : server_thread
5138 * Description : We only exist to call `serve' in a threaded environment.
5141 * 1 : data = Current client state (buffers, headers, etc...)
5143 * Returns : Always 0.
5145 *********************************************************************/
5146 static int32 server_thread(void *data)
5148 serve((struct client_state *) data);
5155 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5156 /*********************************************************************
5160 * Description : Print usage info & exit.
5162 * Parameters : Pointer to argv[0] for identifying ourselves
5166 *********************************************************************/
5167 static void usage(const char *name)
5169 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n"
5170 "Usage: %s [--config-test] "
5173 #endif /* defined(unix) */
5176 "[--no-daemon] [--pidfile pidfile] [--pre-chroot-nslookup hostname] [--user user[.group]] "
5177 #endif /* defined(unix) */
5178 "[--version] [configfile]\n",
5182 show_fuzz_usage(name);
5185 printf("Aborting\n");
5190 #endif /* #if !defined(_WIN32) || defined(_WIN_CONSOLE) */
5193 #ifdef MUTEX_LOCKS_AVAILABLE
5194 /*********************************************************************
5196 * Function : privoxy_mutex_lock
5198 * Description : Locks a mutex.
5201 * 1 : mutex = The mutex to lock.
5203 * Returns : Void. May exit in case of errors.
5205 *********************************************************************/
5206 void privoxy_mutex_lock(privoxy_mutex_t *mutex)
5208 #ifdef FEATURE_PTHREAD
5209 int err = pthread_mutex_lock(mutex);
5212 if (mutex != &log_mutex)
5214 log_error(LOG_LEVEL_FATAL,
5215 "Mutex locking failed: %s.\n", strerror(err));
5220 EnterCriticalSection(mutex);
5221 #endif /* def FEATURE_PTHREAD */
5225 /*********************************************************************
5227 * Function : privoxy_mutex_unlock
5229 * Description : Unlocks a mutex.
5232 * 1 : mutex = The mutex to unlock.
5234 * Returns : Void. May exit in case of errors.
5236 *********************************************************************/
5237 void privoxy_mutex_unlock(privoxy_mutex_t *mutex)
5239 #ifdef FEATURE_PTHREAD
5240 int err = pthread_mutex_unlock(mutex);
5243 if (mutex != &log_mutex)
5245 log_error(LOG_LEVEL_FATAL,
5246 "Mutex unlocking failed: %s.\n", strerror(err));
5251 LeaveCriticalSection(mutex);
5252 #endif /* def FEATURE_PTHREAD */
5256 /*********************************************************************
5258 * Function : privoxy_mutex_init
5260 * Description : Prepares a mutex.
5263 * 1 : mutex = The mutex to initialize.
5265 * Returns : Void. May exit in case of errors.
5267 *********************************************************************/
5268 static void privoxy_mutex_init(privoxy_mutex_t *mutex)
5270 #ifdef FEATURE_PTHREAD
5271 int err = pthread_mutex_init(mutex, 0);
5274 printf("Fatal error. Mutex initialization failed: %s.\n",
5279 InitializeCriticalSection(mutex);
5280 #endif /* def FEATURE_PTHREAD */
5282 #endif /* def MUTEX_LOCKS_AVAILABLE */
5284 /*********************************************************************
5286 * Function : initialize_mutexes
5288 * Description : Prepares mutexes if mutex support is available.
5292 * Returns : Void, exits in case of errors.
5294 *********************************************************************/
5295 static void initialize_mutexes(void)
5297 #ifdef MUTEX_LOCKS_AVAILABLE
5299 * Prepare global mutex semaphores
5302 #ifdef FEATURE_HTTPS_INSPECTION
5303 privoxy_mutex_init(&certificate_mutex);
5304 privoxy_mutex_init(&ssl_init_mutex);
5307 privoxy_mutex_init(&log_mutex);
5308 privoxy_mutex_init(&log_init_mutex);
5309 privoxy_mutex_init(&connection_reuse_mutex);
5310 #ifdef FEATURE_EXTERNAL_FILTERS
5311 privoxy_mutex_init(&external_filter_mutex);
5313 #ifdef FEATURE_CLIENT_TAGS
5314 privoxy_mutex_init(&client_tags_mutex);
5316 #ifdef FEATURE_STATISTICS
5317 privoxy_mutex_init(&block_statistics_mutex);
5319 #ifdef FEATURE_EXTENDED_STATISTICS
5320 privoxy_mutex_init(&filter_statistics_mutex);
5321 privoxy_mutex_init(&block_reason_statistics_mutex);
5325 * XXX: The assumptions below are a bit naive
5326 * and can cause locks that aren't necessary.
5328 * For example older FreeBSD versions (< 6.x?)
5329 * have no gethostbyname_r, but gethostbyname is
5332 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
5333 privoxy_mutex_init(&resolver_mutex);
5334 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
5336 * XXX: should we use a single mutex for
5337 * localtime() and gmtime() as well?
5339 #ifndef HAVE_GMTIME_R
5340 privoxy_mutex_init(&gmtime_mutex);
5341 #endif /* ndef HAVE_GMTIME_R */
5343 #ifndef HAVE_LOCALTIME_R
5344 privoxy_mutex_init(&localtime_mutex);
5345 #endif /* ndef HAVE_GMTIME_R */
5347 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
5348 privoxy_mutex_init(&rand_mutex);
5349 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
5351 #endif /* def MUTEX_LOCKS_AVAILABLE */
5354 /*********************************************************************
5358 * Description : Load the config file and start the listen loop.
5359 * This function is a lot more *sane* with the `load_config'
5360 * and `listen_loop' functions; although it stills does
5361 * a *little* too much for my taste.
5364 * 1 : argc = Number of parameters (including $0).
5365 * 2 : argv = Array of (char *)'s to the parameters.
5367 * Returns : 1 if : can't open config file, unrecognized directive,
5368 * stats requested in multi-thread mode, can't open the
5369 * log file, can't open the jar file, listen port is invalid,
5370 * any load fails, and can't bind port.
5372 * Else main never returns, the process must be signaled
5373 * to terminate execution. Or, on Windows, use the
5374 * "File", "Exit" menu option.
5376 *********************************************************************/
5378 int real_main(int argc, char **argv)
5380 int main(int argc, char **argv)
5384 int do_config_test = 0;
5385 #ifndef HAVE_ARC4RANDOM
5386 unsigned int random_seed;
5389 struct passwd *pw = NULL;
5390 struct group *grp = NULL;
5392 char *pre_chroot_nslookup_to_load_resolver = NULL;
5395 char *fuzz_input_type = NULL;
5396 char *fuzz_input_file = NULL;
5403 #if !defined(_WIN32)
5410 /* Prepare mutexes if supported and necessary. */
5411 initialize_mutexes();
5413 /* Enable logging until further notice. */
5417 * Parse the command line arguments
5419 * XXX: simply printing usage information in case of
5420 * invalid arguments isn't particularly user friendly.
5422 while (++argc_pos < argc)
5425 /* Check to see if the service must be installed or uninstalled */
5426 if (strncmp(argv[argc_pos], "--install", 9) == 0)
5428 const char *pName = argv[argc_pos] + 9;
5431 exit((install_service(pName)) ? 0 : 1);
5433 else if (strncmp(argv[argc_pos], "--uninstall", 11) == 0)
5435 const char *pName = argv[argc_pos] + 11;
5438 exit((uninstall_service(pName)) ? 0 : 1);
5440 else if (strcmp(argv[argc_pos], "--service") == 0)
5442 bRunAsService = TRUE;
5443 w32_set_service_cwd();
5444 atexit(w32_service_exit_notify);
5447 #endif /* defined(_WIN32) */
5450 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
5452 if (strcmp(argv[argc_pos], "--help") == 0)
5457 else if (strcmp(argv[argc_pos], "--version") == 0)
5459 printf("Privoxy version " VERSION " (" HOME_PAGE_URL ")\n");
5465 else if (strcmp(argv[argc_pos], "--no-daemon") == 0)
5467 set_debug_level(LOG_LEVEL_FATAL | LOG_LEVEL_ERROR | LOG_LEVEL_INFO);
5471 else if (strcmp(argv[argc_pos], "--pidfile") == 0)
5473 if (++argc_pos == argc) usage(argv[0]);
5474 pidfile = strdup_or_die(argv[argc_pos]);
5477 else if (strcmp(argv[argc_pos], "--user") == 0)
5482 if (++argc_pos == argc) usage(argv[argc_pos]);
5484 user_arg = strdup_or_die(argv[argc_pos]);
5485 group_name = strchr(user_arg, '.');
5486 if (NULL != group_name)
5488 /* Nul-terminate the user name */
5491 /* Skip the former delimiter to actually reach the group name */
5494 grp = getgrnam(group_name);
5497 log_error(LOG_LEVEL_FATAL, "Group '%s' not found.", group_name);
5500 pw = getpwnam(user_arg);
5503 log_error(LOG_LEVEL_FATAL, "User '%s' not found.", user_arg);
5509 else if (strcmp(argv[argc_pos], "--pre-chroot-nslookup") == 0)
5511 if (++argc_pos == argc) usage(argv[0]);
5512 pre_chroot_nslookup_to_load_resolver = strdup_or_die(argv[argc_pos]);
5515 else if (strcmp(argv[argc_pos], "--chroot") == 0)
5519 #endif /* defined(unix) */
5521 else if (strcmp(argv[argc_pos], "--config-test") == 0)
5526 else if (strcmp(argv[argc_pos], "--fuzz") == 0)
5529 if (argc < argc_pos + 2) usage(argv[0]);
5530 fuzz_input_type = argv[argc_pos];
5532 fuzz_input_file = argv[argc_pos];
5534 else if (strcmp(argv[argc_pos], "--stfu") == 0)
5536 set_debug_level(LOG_LEVEL_STFU);
5539 else if (argc_pos + 1 != argc)
5542 * This is neither the last command line
5543 * option, nor was it recognized before,
5544 * therefore it must be invalid.
5550 #endif /* defined(_WIN32) && !defined(_WIN_CONSOLE) */
5552 configfile = argv[argc_pos];
5555 } /* -END- while (more arguments) */
5557 show_version(Argv[0]);
5560 if (*configfile != '/')
5562 char cwd[BUFFER_SIZE];
5564 size_t abs_file_size;
5566 /* make config-filename absolute here */
5567 if (NULL == getcwd(cwd, sizeof(cwd)))
5569 perror("failed to get current working directory");
5573 basedir = strdup_or_die(cwd);
5575 abs_file_size = strlen(cwd) + strlen(configfile) + 5;
5576 abs_file = malloc_or_die(abs_file_size);
5577 strlcpy(abs_file, basedir, abs_file_size);
5578 strlcat(abs_file, "/", abs_file_size);
5579 strlcat(abs_file, configfile, abs_file_size);
5580 configfile = abs_file;
5582 #endif /* defined unix */
5586 clients->next = NULL;
5588 /* XXX: factor out initialising after the next stable release. */
5593 #ifndef HAVE_ARC4RANDOM
5594 random_seed = (unsigned int)time(NULL);
5596 srandom(random_seed);
5599 #endif /* ifdef HAVE_RANDOM */
5600 #endif /* ifndef HAVE_ARC4RANDOM */
5603 * Unix signal handling
5605 * Catch the abort, interrupt and terminate signals for a graceful exit
5606 * Catch the hangup signal so the errlog can be reopened.
5608 * Ignore the broken pipe signal as connection failures
5609 * are handled when and where they occur without relying
5612 #if !defined(_WIN32)
5615 const int catched_signals[] = { SIGTERM, SIGINT, SIGHUP };
5617 for (idx = 0; idx < SZ(catched_signals); idx++)
5619 #ifdef sun /* FIXME: Is it safe to check for HAVE_SIGSET instead? */
5620 if (sigset(catched_signals[idx], sig_handler) == SIG_ERR)
5622 if (signal(catched_signals[idx], sig_handler) == SIG_ERR)
5623 #endif /* ifdef sun */
5625 log_error(LOG_LEVEL_FATAL, "Can't set signal-handler for signal %d: %E", catched_signals[idx]);
5629 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
5631 log_error(LOG_LEVEL_FATAL, "Can't set ignore-handler for SIGPIPE: %E");
5635 #else /* ifdef _WIN32 */
5636 # ifdef _WIN_CONSOLE
5638 * We *are* in a windows console app.
5639 * Print a verbose messages about FAQ's and such
5641 printf("%s", win32_blurb);
5642 # endif /* def _WIN_CONSOLE */
5643 #endif /* def _WIN32 */
5646 if (fuzz_input_type != NULL)
5648 exit(process_fuzzed_input(fuzz_input_type, fuzz_input_file));
5650 log_error(LOG_LEVEL_FATAL,
5651 "When compiled with fuzzing support, Privoxy should only be used for fuzzing. "
5652 "Various data structures are static which is unsafe when using threads.");
5657 exit(NULL == load_config());
5660 /* Initialize the CGI subsystem */
5661 cgi_init_error_messages();
5664 * If running on unix and without the --no-daemon
5665 * option, become a daemon. I.e. fork, detach
5666 * from tty and get process group leadership
5675 if (pid < 0) /* error */
5680 else if (pid != 0) /* parent */
5685 * must check for errors
5686 * child died due to missing files aso
5689 wpid = waitpid(pid, &status, WNOHANG);
5701 * stderr (fd 2) will be closed later on,
5702 * when the config file has been parsed.
5708 * Reserve fd 0 and 1 to prevent abort() and friends
5709 * from sending stuff to the clients or servers.
5711 fd = open("/dev/null", O_RDONLY);
5714 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5718 if (dup2(fd, 0) == -1)
5720 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
5724 fd = open("/dev/null", O_WRONLY);
5727 log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
5731 if (dup2(fd, 1) == -1)
5733 log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
5738 #ifdef FEATURE_EXTERNAL_FILTERS
5739 for (fd = 0; fd < 3; fd++)
5741 mark_socket_for_close_on_execute(fd);
5745 if (chdir("/") != 0)
5747 log_error(LOG_LEVEL_FATAL, "Failed to cd into '/': %E");
5750 } /* -END- if (daemon_mode) */
5753 * As soon as we have written the PID file, we can switch
5754 * to the user and group ID indicated by the --user option
5756 if (pidfile != NULL)
5758 write_pid_file(pidfile);
5762 if (setgid((NULL != grp) ? grp->gr_gid : pw->pw_gid))
5764 log_error(LOG_LEVEL_FATAL, "Cannot setgid(): Insufficient permissions.");
5768 if (setgroups(1, &grp->gr_gid))
5770 log_error(LOG_LEVEL_FATAL, "setgroups() failed: %E");
5773 else if (initgroups(pw->pw_name, pw->pw_gid))
5775 log_error(LOG_LEVEL_FATAL, "initgroups() failed: %E");
5781 log_error(LOG_LEVEL_FATAL, "Home directory for %s undefined", pw->pw_name);
5783 /* Read the time zone file from /etc before doing chroot. */
5785 if (NULL != pre_chroot_nslookup_to_load_resolver
5786 && '\0' != pre_chroot_nslookup_to_load_resolver[0])
5788 /* Initialize resolver library. */
5789 (void) resolve_hostname_to_ip(pre_chroot_nslookup_to_load_resolver);
5791 if (chroot(pw->pw_dir) < 0)
5793 log_error(LOG_LEVEL_FATAL, "Cannot chroot to %s", pw->pw_dir);
5797 log_error(LOG_LEVEL_FATAL, "Cannot chdir /");
5800 if (setuid(pw->pw_uid))
5802 log_error(LOG_LEVEL_FATAL, "Cannot setuid(): Insufficient permissions.");
5806 char putenv_dummy[64];
5808 strlcpy(putenv_dummy, "HOME=/", sizeof(putenv_dummy));
5809 if (putenv(putenv_dummy) != 0)
5811 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): HOME");
5814 snprintf(putenv_dummy, sizeof(putenv_dummy), "USER=%s", pw->pw_name);
5815 if (putenv(putenv_dummy) != 0)
5817 log_error(LOG_LEVEL_FATAL, "Cannot putenv(): USER");
5823 log_error(LOG_LEVEL_FATAL, "Cannot chroot without --user argument.");
5826 #endif /* defined unix */
5829 /* This will be FALSE unless the command line specified --service
5833 /* Yup, so now we must attempt to establish a connection
5834 * with the service dispatcher. This will only work if this
5835 * process was launched by the service control manager to
5836 * actually run as a service. If this isn't the case, i've
5837 * known it take around 30 seconds or so for the call to return.
5840 /* The StartServiceCtrlDispatcher won't return until the service is stopping */
5841 if (w32_start_service_ctrl_dispatcher(w32ServiceDispatchTable))
5843 /* Service has run, and at this point is now being stopped, so just return */
5848 printf("Warning: Failed to connect to Service Control Dispatcher\nwhen starting as a service!\n");
5850 /* An error occurred. Usually it's because --service was wrongly specified
5851 * and we were unable to connect to the Service Control Dispatcher because
5852 * it wasn't expecting us and is therefore not listening.
5854 * For now, just continue below to call the listen_loop function.
5857 #endif /* def _WIN32 */
5867 /*********************************************************************
5869 * Function : bind_port_helper
5871 * Description : Bind the listen port. Handles logging, and aborts
5875 * 1 : haddr = Host address to bind to. Use NULL to bind to
5877 * 2 : hport = Specifies port to bind to.
5878 * 3 : backlog = Listen backlog.
5880 * Returns : Port that was opened.
5882 *********************************************************************/
5883 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog)
5888 result = bind_port(haddr, hport, backlog, &bfd);
5892 const char *bind_address = (NULL != haddr) ? haddr : "INADDR_ANY";
5896 log_error(LOG_LEVEL_FATAL,
5897 "can't bind to %s:%d: There may be another Privoxy "
5898 "or some other proxy running on port %d",
5899 bind_address, hport, hport);
5903 log_error(LOG_LEVEL_FATAL,
5904 "can't bind to %s:%d: The hostname is not resolvable",
5905 bind_address, hport);
5909 log_error(LOG_LEVEL_FATAL, "can't bind to %s:%d: %E",
5910 bind_address, hport);
5914 /* shouldn't get here */
5915 return JB_INVALID_SOCKET;
5920 if (bfd >= FD_SETSIZE)
5922 log_error(LOG_LEVEL_FATAL,
5923 "Bind socket number too high to use select(): %d >= %d",
5931 log_error(LOG_LEVEL_INFO, "Listening on port %d on all IP addresses",
5936 log_error(LOG_LEVEL_INFO, "Listening on port %d on IP address %s",
5944 /*********************************************************************
5946 * Function : bind_ports_helper
5948 * Description : Bind the listen ports. Handles logging, and aborts
5952 * 1 : config = Privoxy configuration. Specifies ports
5954 * 2 : sockets = Preallocated array of opened sockets
5955 * corresponding to specification in config.
5956 * All non-opened sockets will be set to
5957 * JB_INVALID_SOCKET.
5959 * Returns : Nothing. Inspect sockets argument.
5961 *********************************************************************/
5962 static void bind_ports_helper(struct configuration_spec * config,
5963 jb_socket sockets[])
5967 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
5969 if (config->hport[i])
5971 sockets[i] = bind_port_helper(config->haddr[i],
5972 config->hport[i], config->listen_backlog);
5973 #if defined(FEATURE_ACCEPT_FILTER) && defined(SO_ACCEPTFILTER)
5974 if (config->enable_accept_filter && sockets[i] != JB_INVALID_SOCKET)
5976 struct accept_filter_arg af_options;
5977 bzero(&af_options, sizeof(af_options));
5978 strlcpy(af_options.af_name, "httpready", sizeof(af_options.af_name));
5979 if (setsockopt(sockets[i], SOL_SOCKET, SO_ACCEPTFILTER, &af_options,
5980 sizeof(af_options)))
5982 log_error(LOG_LEVEL_ERROR,
5983 "Enabling accept filter for socket %d failed: %E", sockets[i]);
5990 sockets[i] = JB_INVALID_SOCKET;
5993 config->need_bind = 0;
5997 /*********************************************************************
5999 * Function : close_ports_helper
6001 * Description : Close listenings ports.
6004 * 1 : sockets = Array of opened and non-opened sockets to
6005 * close. All sockets will be set to
6006 * JB_INVALID_SOCKET.
6008 * Returns : Nothing.
6010 *********************************************************************/
6011 static void close_ports_helper(jb_socket sockets[])
6015 for (i = 0; i < MAX_LISTENING_SOCKETS; i++)
6017 if (JB_INVALID_SOCKET != sockets[i])
6019 close_socket(sockets[i]);
6021 sockets[i] = JB_INVALID_SOCKET;
6027 /* Without this simple workaround we get this compiler warning from _beginthread
6028 * warning C4028: formal parameter 1 different from declaration
6030 void w32_service_listen_loop(void *p)
6034 #endif /* def _WIN32 */
6037 /*********************************************************************
6039 * Function : listen_loop
6041 * Description : bind the listen port and enter a "FOREVER" listening loop.
6047 *********************************************************************/
6048 static void listen_loop(void)
6050 struct client_states *csp_list = NULL;
6051 struct client_state *csp = NULL;
6052 jb_socket bfds[MAX_LISTENING_SOCKETS];
6053 struct configuration_spec *config;
6054 unsigned int active_threads = 0;
6055 #if defined(FEATURE_PTHREAD)
6056 pthread_attr_t attrs;
6058 pthread_attr_init(&attrs);
6059 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED);
6062 config = load_config();
6064 #ifdef FEATURE_CONNECTION_SHARING
6066 * XXX: Should be relocated once it no
6067 * longer needs to emit log messages.
6069 initialize_reusable_connections();
6070 #endif /* def FEATURE_CONNECTION_SHARING */
6072 bind_ports_helper(config, bfds);
6074 #ifdef FEATURE_GRACEFUL_TERMINATION
6075 while (!g_terminate)
6080 #if !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__)
6081 while (waitpid(-1, NULL, WNOHANG) > 0)
6083 /* zombie children */
6085 #endif /* !defined(FEATURE_PTHREAD) && !defined(_WIN32) && !defined(__BEOS__) */
6088 * Free data that was used by died threads
6090 active_threads = sweep();
6094 * Re-open the errlog after HUP signal
6096 if (received_hup_signal)
6098 if (NULL != config->logfile)
6100 init_error_log(Argv[0], config->logfile);
6102 received_hup_signal = 0;
6106 csp_list = zalloc_or_die(sizeof(*csp_list));
6107 csp = &csp_list->csp;
6109 log_error(LOG_LEVEL_CONNECT,
6110 "Waiting for the next client connection. Currently active threads: %u",
6114 * This config may be outdated, but for accept_connection()
6115 * it's fresh enough.
6117 csp->config = config;
6119 if (!accept_connection(csp, bfds))
6121 log_error(LOG_LEVEL_CONNECT, "accept failed: %E");
6126 csp->flags |= CSP_FLAG_ACTIVE;
6127 csp->server_connection.sfd = JB_INVALID_SOCKET;
6129 csp->config = config = load_config();
6131 if (config->need_bind)
6134 * Since we were listening to the "old port", we will not see
6135 * a "listen" param change until the next request. So, at
6136 * least 1 more request must be made for us to find the new
6137 * setting. I am simply closing the old socket and binding the
6140 * Which-ever is correct, we will serve 1 more page via the
6141 * old settings. This should probably be a "show-status"
6142 * request. This should not be a so common of an operation
6143 * that this will hurt people's feelings.
6146 close_ports_helper(bfds);
6148 bind_ports_helper(config, bfds);
6151 #ifdef FEATURE_TOGGLE
6152 if (global_toggle_state)
6153 #endif /* def FEATURE_TOGGLE */
6155 csp->flags |= CSP_FLAG_TOGGLED_ON;
6158 if (run_loader(csp))
6160 log_error(LOG_LEVEL_FATAL, "a loader failed - must exit");
6161 /* Never get here - LOG_LEVEL_FATAL causes program exit */
6165 if (block_acl(NULL,csp))
6167 log_error(LOG_LEVEL_CONNECT,
6168 "Connection from %s on %s (socket %d) dropped due to ACL",
6169 csp->ip_addr_str, csp->listen_addr_str, csp->cfd);
6170 close_socket(csp->cfd);
6171 freez(csp->ip_addr_str);
6172 freez(csp->listen_addr_str);
6176 #endif /* def FEATURE_ACL */
6178 if ((0 != config->max_client_connections)
6179 && (active_threads >= config->max_client_connections))
6181 log_error(LOG_LEVEL_ERROR,
6182 "Rejecting connection from %s. Maximum number of connections reached.",
6184 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6185 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6186 close_socket(csp->cfd);
6187 freez(csp->ip_addr_str);
6188 freez(csp->listen_addr_str);
6193 /* add it to the list of clients */
6194 csp_list->next = clients->next;
6195 clients->next = csp_list;
6197 if (config->multi_threaded)
6201 /* this is a switch () statement in the C preprocessor - ugh */
6202 #undef SELECTED_ONE_OPTION
6204 /* Use Pthreads in preference to native code */
6205 #if defined(FEATURE_PTHREAD) && !defined(SELECTED_ONE_OPTION)
6206 #define SELECTED_ONE_OPTION
6208 pthread_t the_thread;
6211 ret = pthread_create(&the_thread, &attrs,
6212 (void * (*)(void *))serve, csp);
6213 child_id = ret ? -1 : 0;
6217 #if defined(_WIN32) && !defined(SELECTED_ONE_OPTION)
6218 #define SELECTED_ONE_OPTION
6219 child_id = _beginthread(
6220 (void (*)(void *))serve,
6225 #if defined(__BEOS__) && !defined(SELECTED_ONE_OPTION)
6226 #define SELECTED_ONE_OPTION
6228 thread_id tid = spawn_thread
6229 (server_thread, "server", B_NORMAL_PRIORITY, csp);
6231 if ((tid >= 0) && (resume_thread(tid) == B_OK))
6233 child_id = (int) tid;
6242 #if !defined(SELECTED_ONE_OPTION)
6245 /* This block is only needed when using fork().
6246 * When using threads, the server thread was
6247 * created and run by the call to _beginthread().
6249 if (child_id == 0) /* child */
6252 #ifdef FEATURE_TOGGLE
6253 int inherited_toggle_state = global_toggle_state;
6254 #endif /* def FEATURE_TOGGLE */
6259 * If we've been toggled or we've blocked the request, tell Mom
6262 #ifdef FEATURE_TOGGLE
6263 if (inherited_toggle_state != global_toggle_state)
6265 rc |= RC_FLAG_TOGGLED;
6267 #endif /* def FEATURE_TOGGLE */
6269 #ifdef FEATURE_STATISTICS
6270 if (csp->flags & CSP_FLAG_REJECTED)
6272 rc |= RC_FLAG_BLOCKED;
6274 #endif /* ndef FEATURE_STATISTICS */
6278 else if (child_id > 0) /* parent */
6280 /* in a fork()'d environment, the parent's
6281 * copy of the client socket and the CSP
6285 #if !defined(_WIN32) && !defined(__CYGWIN__)
6287 wait(&child_status);
6290 * Evaluate child's return code: If the child has
6291 * - been toggled, toggle ourselves
6292 * - blocked its request, bump up the stats counter
6295 #ifdef FEATURE_TOGGLE
6296 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_TOGGLED))
6298 global_toggle_state = !global_toggle_state;
6300 #endif /* def FEATURE_TOGGLE */
6302 #ifdef FEATURE_STATISTICS
6304 if (WIFEXITED(child_status) && (WEXITSTATUS(child_status) & RC_FLAG_BLOCKED))
6308 #endif /* def FEATURE_STATISTICS */
6310 #endif /* !defined(_WIN32) && defined(__CYGWIN__) */
6311 close_socket(csp->cfd);
6312 csp->flags &= ~CSP_FLAG_ACTIVE;
6316 #undef SELECTED_ONE_OPTION
6317 /* end of cpp switch () */
6322 * Spawning the child failed, assume it's because
6323 * there are too many children running already.
6324 * XXX: If you assume ...
6326 log_error(LOG_LEVEL_ERROR,
6327 "Unable to take any additional connections: %E. Active threads: %u",
6329 write_socket_delayed(csp->cfd, TOO_MANY_CONNECTIONS_RESPONSE,
6330 strlen(TOO_MANY_CONNECTIONS_RESPONSE), get_write_delay(csp));
6331 close_socket(csp->cfd);
6332 csp->flags &= ~CSP_FLAG_ACTIVE;
6341 #if defined(FEATURE_PTHREAD)
6342 pthread_attr_destroy(&attrs);
6345 /* NOTREACHED unless FEATURE_GRACEFUL_TERMINATION is defined */
6347 #ifdef FEATURE_GRACEFUL_TERMINATION
6349 log_error(LOG_LEVEL_INFO, "Graceful termination requested.");
6351 close_ports_helper(bfds);
6353 unload_current_config_file();
6354 unload_current_actions_file();
6355 unload_current_re_filterfile();
6356 #ifdef FEATURE_TRUST
6357 unload_current_trust_file();
6360 if (config->multi_threaded)
6367 } while ((clients->next != NULL) && (--i > 0));
6371 log_error(LOG_LEVEL_ERROR, "Graceful termination failed "
6372 "- still some live clients after 1 minute wait.");
6382 #ifdef FEATURE_HTTPS_INSPECTION
6384 * Only release TLS backed resources if there
6385 * are no active connections left.
6387 if (clients->next == NULL)
6393 log_error(LOG_LEVEL_INFO, "Exiting gracefully.");
6395 #if defined(_WIN32) && !defined(_WIN_CONSOLE)
6396 /* Cleanup - remove taskbar icon etc. */
6401 #endif /* FEATURE_GRACEFUL_TERMINATION */