1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/jcc.c,v $
5 * Purpose : Main file. Contains main() method, main loop, and
6 * the main connection-handling function.
8 * Copyright : Written by and Copyright (C) 2001-2020 the
9 * Privoxy team. https://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
65 # if !defined (__OS2__)
67 # include <sys/wait.h>
68 # endif /* ndef __OS2__ */
69 # include <sys/time.h>
70 # include <sys/stat.h>
71 # include <sys/ioctl.h>
74 #include <sys/termios.h>
85 # include <socket.h> /* BeOS has select() for sockets only. */
86 # include <OS.h> /* declarations for threads and stuff. */
89 # if defined(__EMX__) || defined(__OS2__)
90 # include <sys/select.h> /* OS/2/EMX needs a little help with select */
102 #endif /* def __GLIBC__ */
107 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
108 #endif /* HAVE_POLL */
115 #ifdef FEATURE_HTTPS_INSPECTION
121 #include "miscutil.h"
123 #include "jbsockets.h"
128 #include "urlmatch.h"
129 #ifdef FEATURE_CLIENT_TAGS
130 #include "client-tags.h"
134 struct client_states clients[1];
135 struct file_list files[1];
137 #ifdef FEATURE_STATISTICS
138 int urls_read = 0; /* total nr of urls read inc rejected */
139 int urls_rejected = 0; /* total nr of urls rejected */
140 #endif /* def FEATURE_STATISTICS */
142 #ifdef FEATURE_GRACEFUL_TERMINATION
146 #if !defined(_WIN32) && !defined(__OS2__)
147 static void sig_handler(int the_signal);
149 static int client_protocol_is_unsupported(const struct client_state *csp, char *req);
150 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
151 static jb_err get_server_headers(struct client_state *csp);
152 static const char *crunch_reason(const struct http_response *rsp);
153 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
154 static char *get_request_line(struct client_state *csp);
155 static jb_err receive_client_request(struct client_state *csp);
156 static jb_err parse_client_request(struct client_state *csp);
157 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
158 static jb_err change_request_destination(struct client_state *csp);
159 static void chat(struct client_state *csp);
160 static void serve(struct client_state *csp);
161 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
162 static void usage(const char *myname);
164 static void initialize_mutexes(void);
165 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
166 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
167 static void close_ports_helper(jb_socket sockets[]);
168 static void listen_loop(void);
169 static void serve(struct client_state *csp);
172 static int32 server_thread(void *data);
173 #endif /* def __BEOS__ */
176 #define sleep(N) Sleep(((N) * 1000))
180 #define sleep(N) DosSleep(((N) * 100))
184 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
185 void show_fuzz_usage(const char *name);
188 #ifdef MUTEX_LOCKS_AVAILABLE
190 * XXX: Does the locking stuff really belong in this file?
192 privoxy_mutex_t log_mutex;
193 privoxy_mutex_t log_init_mutex;
194 privoxy_mutex_t connection_reuse_mutex;
196 privoxy_mutex_t certificate_mutex;
197 privoxy_mutex_t rng_mutex;
199 #ifdef FEATURE_EXTERNAL_FILTERS
200 privoxy_mutex_t external_filter_mutex;
202 #ifdef FEATURE_CLIENT_TAGS
203 privoxy_mutex_t client_tags_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.\r\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.\r\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.\r\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.\r\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.\r\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.\r\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.\r\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.\r\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.\r\n";
291 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
292 "HTTP/1.1 417 Expecting too much\r\n"
293 "Content-Type: text/plain\r\n"
294 "Connection: close\r\n\r\n"
295 "Privoxy detected an unsupported Expect header value.\r\n";
297 /* A function to crunch a response */
298 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
300 /* Crunch function flags */
301 #define CF_NO_FLAGS 0
302 /* Cruncher applies to forced requests as well */
303 #define CF_IGNORE_FORCE 1
304 /* Crunched requests are counted for the block statistics */
305 #define CF_COUNT_AS_REJECT 2
307 /* A crunch function and its flags */
310 const crunch_func_ptr cruncher;
314 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
316 /* Complete list of cruncher functions */
317 static const struct cruncher crunchers_all[] = {
318 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
319 { block_url, CF_COUNT_AS_REJECT },
321 { trust_url, CF_COUNT_AS_REJECT },
322 #endif /* def FEATURE_TRUST */
323 { redirect_url, CF_NO_FLAGS },
324 { dispatch_cgi, CF_IGNORE_FORCE},
328 /* Light version, used after tags are applied */
329 static const struct cruncher crunchers_light[] = {
330 { block_url, CF_COUNT_AS_REJECT },
331 { redirect_url, CF_NO_FLAGS },
337 * XXX: Don't we really mean
343 #if !defined(_WIN32) && !defined(__OS2__)
344 /*********************************************************************
346 * Function : sig_handler
348 * Description : Signal handler for different signals.
349 * Exit gracefully on TERM and INT
350 * or set a flag that will cause the errlog
351 * to be reopened by the main thread on HUP.
354 * 1 : the_signal = the signal cause this function to call
358 *********************************************************************/
359 static void sig_handler(int the_signal)
365 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
377 received_hup_signal = 1;
383 * We shouldn't be here, unless we catch signals
384 * in main() that we can't handle here!
386 log_error(LOG_LEVEL_FATAL, "sig_handler: exiting on unexpected signal %d", the_signal);
394 /*********************************************************************
396 * Function : get_write_delay
398 * Description : Parse the delay-response parameter.
401 * 1 : csp = Current client state (buffers, headers, etc...)
403 * Returns : Number of milliseconds to delay writes.
405 *********************************************************************/
406 static unsigned int get_write_delay(const struct client_state *csp)
412 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
416 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
418 delay = (unsigned)strtol(newval, &endptr, 0);
421 log_error(LOG_LEVEL_FATAL,
422 "Invalid delay-response{} parameter: '%s'", newval);
430 /*********************************************************************
432 * Function : client_protocol_is_unsupported
434 * Description : Checks if the client used a known unsupported
435 * protocol and deals with it by sending an error
439 * 1 : csp = Current client state (buffers, headers, etc...)
440 * 2 : req = the first request line send by the client
442 * Returns : TRUE if an error response has been generated, or
443 * FALSE if the request doesn't look invalid.
445 *********************************************************************/
446 static int client_protocol_is_unsupported(const struct client_state *csp, char *req)
449 * If it's a FTP or gopher request, we don't support it.
451 * These checks are better than nothing, but they might
452 * not work in all configurations and some clients might
453 * have problems digesting the answer.
455 * They should, however, never cause more problems than
456 * Privoxy's old behaviour (returning the misleading HTML
459 * "Could not resolve http://(ftp|gopher)://example.org").
461 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
463 const char *response = NULL;
464 const char *protocol = NULL;
466 if (!strncmpic(req, "GET ftp://", 10))
468 response = FTP_RESPONSE;
473 response = GOPHER_RESPONSE;
476 log_error(LOG_LEVEL_ERROR,
477 "%s tried to use Privoxy as %s proxy: %s",
478 csp->ip_addr_str, protocol, req);
479 log_error(LOG_LEVEL_CLF,
480 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
482 write_socket_delayed(csp->cfd, response, strlen(response),
483 get_write_delay(csp));
492 /*********************************************************************
494 * Function : client_has_unsupported_expectations
496 * Description : Checks if the client used an unsupported expectation
497 * in which case an error message is delivered.
500 * 1 : csp = Current client state (buffers, headers, etc...)
502 * Returns : TRUE if an error response has been generated, or
503 * FALSE if the request doesn't look invalid.
505 *********************************************************************/
506 static int client_has_unsupported_expectations(const struct client_state *csp)
508 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
510 log_error(LOG_LEVEL_ERROR,
511 "Rejecting request from client %s with unsupported Expect header value",
513 log_error(LOG_LEVEL_CLF,
514 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
515 write_socket_delayed(csp->cfd,
516 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
517 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
518 get_write_delay(csp));
528 /*********************************************************************
530 * Function : get_request_destination_elsewhere
532 * Description : If the client's request was redirected into
533 * Privoxy without the client's knowledge,
534 * the request line lacks the destination host.
536 * This function tries to get it elsewhere,
537 * provided accept-intercepted-requests is enabled.
539 * "Elsewhere" currently only means "Host: header",
540 * but in the future we may ask the redirecting
541 * packet filter to look the destination up.
543 * If the destination stays unknown, an error
544 * response is send to the client and headers
545 * are freed so that chat() can return directly.
548 * 1 : csp = Current client state (buffers, headers, etc...)
549 * 2 : headers = a header list
551 * Returns : JB_ERR_OK if the destination is now known, or
552 * JB_ERR_PARSE if it isn't.
554 *********************************************************************/
555 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
559 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
561 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
562 " Privoxy isn't configured to accept intercepted requests.",
563 csp->ip_addr_str, csp->http->cmd);
564 /* XXX: Use correct size */
565 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
566 csp->ip_addr_str, csp->http->cmd);
568 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
569 get_write_delay(csp));
570 destroy_list(headers);
574 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
576 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
577 /* Split the domain we just got for pattern matching */
578 init_domain_components(csp->http);
585 /* We can't work without destination. Go spread the news.*/
587 req = list_to_text(headers);
589 /* XXX: Use correct size */
590 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
591 csp->ip_addr_str, csp->http->cmd);
592 log_error(LOG_LEVEL_ERROR,
593 "Privoxy was unable to get the destination for %s's request:\n%s\n%s",
594 csp->ip_addr_str, csp->http->cmd, req);
597 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
598 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
599 destroy_list(headers);
604 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
605 * to get the destination IP address, use it as host directly
606 * or do a reverse DNS lookup first.
611 /*********************************************************************
613 * Function : get_server_headers
615 * Description : Parses server headers in iob and fills them
616 * into csp->headers so that they can later be
620 * 1 : csp = Current client state (buffers, headers, etc...)
622 * Returns : JB_ERR_OK if everything went fine, or
623 * JB_ERR_PARSE if the headers were incomplete.
625 *********************************************************************/
626 static jb_err get_server_headers(struct client_state *csp)
628 int continue_hack_in_da_house = 0;
631 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
636 * continue hack in da house. Ignore the ending of
637 * this head and continue enlisting header lines.
638 * The reason is described below.
640 enlist(csp->headers, "");
641 continue_hack_in_da_house = 0;
644 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
647 * It's a bodyless continue response, don't
648 * stop header parsing after reaching its end.
650 * As a result Privoxy will concatenate the
651 * next response's head and parse and deliver
652 * the headers as if they belonged to one request.
654 * The client will separate them because of the
655 * empty line between them.
657 * XXX: What we're doing here is clearly against
658 * the intended purpose of the continue header,
659 * and under some conditions (HTTP/1.0 client request)
660 * it's a standard violation.
662 * Anyway, "sort of against the spec" is preferable
663 * to "always getting confused by Continue responses"
664 * (Privoxy's behaviour before this hack was added)
666 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
667 continue_hack_in_da_house = 1;
669 else if (*header == '\0')
672 * If the header is empty, but the Continue hack
673 * isn't active, we can assume that we reached the
674 * end of the buffer before we hit the end of the
677 * Inform the caller an let it decide how to handle it.
682 if (JB_ERR_MEMORY == enlist(csp->headers, header))
685 * XXX: Should we quit the request and return a
686 * out of memory error page instead?
688 log_error(LOG_LEVEL_ERROR,
689 "Out of memory while enlisting server headers. %s lost.",
699 /*********************************************************************
701 * Function : crunch_reason
703 * Description : Translates the crunch reason code into a string.
706 * 1 : rsp = a http_response
708 * Returns : A string with the crunch reason or an error description.
710 *********************************************************************/
711 static const char *crunch_reason(const struct http_response *rsp)
713 char * reason = NULL;
718 return "Internal error while searching for crunch reason";
721 switch (rsp->crunch_reason)
724 reason = "Unsupported HTTP feature";
730 reason = "Untrusted";
733 reason = "Redirected";
739 reason = "DNS failure";
741 case FORWARDING_FAILED:
742 reason = "Forwarding failed";
745 reason = "Connection failure";
748 reason = "Out of memory (may mask other reasons)";
750 case CONNECTION_TIMEOUT:
751 reason = "Connection timeout";
754 reason = "No server data received";
757 reason = "No reason recorded";
765 /*********************************************************************
767 * Function : log_applied_actions
769 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
773 * 1 : actions = Current action spec to log
777 *********************************************************************/
778 static void log_applied_actions(const struct current_action_spec *actions)
781 * The conversion to text requires lots of memory allocations so
782 * we only do the conversion if the user is actually interested.
784 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
786 char *actions_as_text = actions_to_line_of_text(actions);
787 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
788 freez(actions_as_text);
793 /*********************************************************************
795 * Function : send_crunch_response
797 * Description : Delivers already prepared response for
798 * intercepted requests, logs the interception
799 * and frees the response.
802 * 1 : csp = Current client state (buffers, headers, etc...)
803 * 2 : rsp = Fully prepared response. Will be freed on exit.
807 *********************************************************************/
808 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
810 const struct http_request *http = csp->http;
814 assert(rsp->head != NULL);
818 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
822 * Extract the status code from the actual head
823 * that will be send to the client. It is the only
824 * way to get it right for all requests, including
825 * the fixed ones for out-of-memory problems.
827 * A head starts like this: 'HTTP/1.1 200...'
831 status_code[0] = rsp->head[9];
832 status_code[1] = rsp->head[10];
833 status_code[2] = rsp->head[11];
834 status_code[3] = '\0';
836 /* Log that the request was crunched and why. */
837 log_applied_actions(csp->action);
838 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
839 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %u",
840 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
842 /* Write the answer to the client */
843 #ifdef FEATURE_HTTPS_INSPECTION
844 if (client_use_ssl(csp))
846 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
847 (const unsigned char *)rsp->head, rsp->head_length) < 0)
848 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
849 (const unsigned char *)rsp->body, rsp->content_length) < 0))
851 /* There is nothing we can do about it. */
852 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
853 "for %s through client socket %d using TLS/SSL",
854 http->url, csp->cfd);
860 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
861 get_write_delay(csp))
862 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
863 get_write_delay(csp)))
865 /* There is nothing we can do about it. */
866 log_error(LOG_LEVEL_CONNECT,
867 "Couldn't deliver the error message for %s through client socket %d: %E",
868 http->url, csp->cfd);
872 /* Clean up and return */
873 if (cgi_error_memory() != rsp)
875 free_http_response(rsp);
881 /*********************************************************************
883 * Function : crunch_response_triggered
885 * Description : Checks if the request has to be crunched,
886 * and delivers the crunch response if necessary.
889 * 1 : csp = Current client state (buffers, headers, etc...)
890 * 2 : crunchers = list of cruncher functions to run
892 * Returns : TRUE if the request was answered with a crunch response
895 *********************************************************************/
896 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
898 struct http_response *rsp = NULL;
899 const struct cruncher *c;
902 * If CGI request crunching is disabled,
903 * check the CGI dispatcher out of order to
904 * prevent unintentional blocks or redirects.
906 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
907 && (NULL != (rsp = dispatch_cgi(csp))))
909 /* Deliver, log and free the interception response. */
910 send_crunch_response(csp, rsp);
911 csp->flags |= CSP_FLAG_CRUNCHED;
915 for (c = crunchers; c->cruncher != NULL; c++)
918 * Check the cruncher if either Privoxy is toggled
919 * on and the request isn't forced, or if the cruncher
920 * applies to forced requests as well.
922 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
923 !(csp->flags & CSP_FLAG_FORCED)) ||
924 (c->flags & CF_IGNORE_FORCE))
926 rsp = c->cruncher(csp);
929 /* Deliver, log and free the interception response. */
930 send_crunch_response(csp, rsp);
931 csp->flags |= CSP_FLAG_CRUNCHED;
932 #ifdef FEATURE_STATISTICS
933 if (c->flags & CF_COUNT_AS_REJECT)
935 csp->flags |= CSP_FLAG_REJECTED;
937 #endif /* def FEATURE_STATISTICS */
948 /*********************************************************************
950 * Function : build_request_line
952 * Description : Builds the HTTP request line.
954 * If a HTTP forwarder is used it expects the whole URL,
955 * web servers only get the path.
958 * 1 : csp = Current client state (buffers, headers, etc...)
959 * 2 : fwd = The forwarding spec used for the request
960 * XXX: Should use http->fwd instead.
961 * 3 : request_line = The old request line which will be replaced.
963 * Returns : Nothing. Terminates in case of memory problems.
965 *********************************************************************/
966 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
968 struct http_request *http = csp->http;
971 * Downgrade http version from 1.1 to 1.0
972 * if +downgrade action applies.
974 if ((csp->action->flags & ACTION_DOWNGRADE)
975 && (!strcmpic(http->ver, "HTTP/1.1")))
978 http->ver = strdup_or_die("HTTP/1.0");
982 * Rebuild the request line.
984 freez(*request_line);
985 *request_line = strdup(http->gpc);
986 string_append(request_line, " ");
988 if (fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
990 string_append(request_line, http->url);
994 string_append(request_line, http->path);
996 string_append(request_line, " ");
997 string_append(request_line, http->ver);
999 if (*request_line == NULL)
1001 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1003 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1007 /*********************************************************************
1009 * Function : change_request_destination
1011 * Description : Parse a (rewritten) request line and regenerate
1012 * the http request data.
1015 * 1 : csp = Current client state (buffers, headers, etc...)
1017 * Returns : Forwards the parse_http_request() return code.
1018 * Terminates in case of memory problems.
1020 *********************************************************************/
1021 static jb_err change_request_destination(struct client_state *csp)
1023 struct http_request *http = csp->http;
1026 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1027 csp->headers->first->str);
1028 free_http_request(http);
1029 err = parse_http_request(csp->headers->first->str, http);
1030 if (JB_ERR_OK != err)
1032 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1033 jb_err_to_string(err));
1040 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1041 /*********************************************************************
1043 * Function : server_response_is_complete
1045 * Description : Determines whether we should stop reading
1046 * from the server socket.
1049 * 1 : csp = Current client state (buffers, headers, etc...)
1050 * 2 : content_length = Length of content received so far.
1052 * Returns : TRUE if the response is complete,
1055 *********************************************************************/
1056 static int server_response_is_complete(struct client_state *csp,
1057 unsigned long long content_length)
1059 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1061 if (!strcmpic(csp->http->gpc, "HEAD"))
1064 * "HEAD" implies no body, we are thus expecting
1065 * no content. XXX: incomplete "list" of methods?
1067 csp->expected_content_length = 0;
1068 content_length_known = TRUE;
1069 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1072 if (csp->http->status == 204 || csp->http->status == 304)
1075 * Expect no body. XXX: incomplete "list" of status codes?
1077 csp->expected_content_length = 0;
1078 content_length_known = TRUE;
1079 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1082 return (content_length_known && ((0 == csp->expected_content_length)
1083 || (csp->expected_content_length <= content_length)));
1087 #ifdef FEATURE_CONNECTION_SHARING
1088 /*********************************************************************
1090 * Function : wait_for_alive_connections
1092 * Description : Waits for alive connections to timeout.
1098 *********************************************************************/
1099 static void wait_for_alive_connections(void)
1101 int connections_alive = close_unusable_connections();
1103 while (0 < connections_alive)
1105 log_error(LOG_LEVEL_CONNECT,
1106 "Waiting for %d connections to timeout.",
1109 connections_alive = close_unusable_connections();
1112 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1115 #endif /* def FEATURE_CONNECTION_SHARING */
1118 /*********************************************************************
1120 * Function : save_connection_destination
1122 * Description : Remembers a connection for reuse later on.
1125 * 1 : sfd = Open socket to remember.
1126 * 2 : http = The destination for the connection.
1127 * 3 : fwd = The forwarder settings used.
1128 * 4 : server_connection = storage.
1132 *********************************************************************/
1133 void save_connection_destination(jb_socket sfd,
1134 const struct http_request *http,
1135 const struct forward_spec *fwd,
1136 struct reusable_connection *server_connection)
1138 assert(sfd != JB_INVALID_SOCKET);
1139 assert(NULL != http->host);
1141 server_connection->sfd = sfd;
1142 server_connection->host = strdup_or_die(http->host);
1143 server_connection->port = http->port;
1145 assert(NULL != fwd);
1146 assert(server_connection->gateway_host == NULL);
1147 assert(server_connection->gateway_port == 0);
1148 assert(server_connection->forwarder_type == 0);
1149 assert(server_connection->forward_host == NULL);
1150 assert(server_connection->forward_port == 0);
1152 server_connection->forwarder_type = fwd->type;
1153 if (NULL != fwd->gateway_host)
1155 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1159 server_connection->gateway_host = NULL;
1161 server_connection->gateway_port = fwd->gateway_port;
1163 if (NULL != fwd->forward_host)
1165 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1169 server_connection->forward_host = NULL;
1171 server_connection->forward_port = fwd->forward_port;
1175 /*********************************************************************
1177 * Function : verify_request_length
1179 * Description : Checks if we already got the whole client requests
1180 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1183 * Data that doesn't belong to the current request is
1184 * either thrown away to let the client retry on a clean
1185 * socket, or stashed to be dealt with after the current
1186 * request is served.
1189 * 1 : csp = Current client state (buffers, headers, etc...)
1193 *********************************************************************/
1194 static void verify_request_length(struct client_state *csp)
1196 unsigned long long buffered_request_bytes =
1197 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1199 if ((csp->expected_client_content_length != 0)
1200 && (buffered_request_bytes != 0))
1202 if (csp->expected_client_content_length >= buffered_request_bytes)
1204 csp->expected_client_content_length -= buffered_request_bytes;
1205 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1206 "to account for the %llu ones we already got.",
1207 csp->expected_client_content_length, buffered_request_bytes);
1211 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1212 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1213 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1214 "Marking the server socket tainted after throwing %llu bytes away.",
1215 buffered_request_bytes - csp->expected_client_content_length);
1216 csp->expected_client_content_length = 0;
1217 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1220 if (csp->expected_client_content_length == 0)
1222 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1226 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1227 && ((csp->client_iob->cur < csp->client_iob->eod)
1228 || (csp->expected_client_content_length != 0)))
1230 if (strcmpic(csp->http->gpc, "GET")
1231 && strcmpic(csp->http->gpc, "HEAD")
1232 && strcmpic(csp->http->gpc, "TRACE")
1233 && strcmpic(csp->http->gpc, "OPTIONS")
1234 && strcmpic(csp->http->gpc, "DELETE"))
1236 /* XXX: this is an incomplete hack */
1237 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1238 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1242 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1244 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1246 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1247 log_error(LOG_LEVEL_CONNECT,
1248 "Possible pipeline attempt detected. The connection will not "
1249 "be kept alive and we will only serve the first request.");
1250 /* Nuke the pipelined requests from orbit, just to be sure. */
1251 clear_iob(csp->client_iob);
1256 * Keep the pipelined data around for now, we'll deal with
1257 * it once we're done serving the current request.
1259 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1260 assert(csp->client_iob->eod >= csp->client_iob->cur);
1261 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1262 "%d bytes of pipelined data received.",
1263 (int)(csp->client_iob->eod - csp->client_iob->cur));
1269 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1270 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1273 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1276 /*********************************************************************
1278 * Function : mark_server_socket_tainted
1280 * Description : Makes sure we don't reuse a server socket
1281 * (if we didn't read everything the server sent
1282 * us reusing the socket would lead to garbage).
1285 * 1 : csp = Current client state (buffers, headers, etc...)
1289 *********************************************************************/
1290 static void mark_server_socket_tainted(struct client_state *csp)
1293 * For consistency we always mark the server socket
1294 * tainted, however, to reduce the log noise we only
1295 * emit a log message if the server socket could have
1296 * actually been reused.
1298 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1299 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1301 log_error(LOG_LEVEL_CONNECT,
1302 "Marking the server socket %d tainted.",
1303 csp->server_connection.sfd);
1305 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1308 /*********************************************************************
1310 * Function : get_request_line
1312 * Description : Read the client request line.
1315 * 1 : csp = Current client state (buffers, headers, etc...)
1317 * Returns : Pointer to request line or NULL in case of errors.
1319 *********************************************************************/
1320 static char *get_request_line(struct client_state *csp)
1322 char buf[BUFFER_SIZE];
1323 char *request_line = NULL;
1326 memset(buf, 0, sizeof(buf));
1328 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1331 * If there are multiple pipelined requests waiting,
1332 * the flag will be set again once the next request
1335 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1337 request_line = get_header(csp->client_iob);
1338 if ((NULL != request_line) && ('\0' != *request_line))
1340 return request_line;
1344 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1345 "received yet. Continuing reading from %d.", csp->cfd);
1353 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1355 !data_is_available(csp->cfd, csp->config->socket_timeout)
1358 if (socket_is_still_alive(csp->cfd))
1360 log_error(LOG_LEVEL_CONNECT,
1361 "No request line on socket %d received in time. Timeout: %d.",
1362 csp->cfd, csp->config->socket_timeout);
1363 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1364 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1365 get_write_delay(csp));
1369 log_error(LOG_LEVEL_CONNECT,
1370 "The client side of the connection on socket %d got "
1371 "closed without sending a complete request line.", csp->cfd);
1376 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1378 if (len <= 0) return NULL;
1381 * If there is no memory left for buffering the
1382 * request, there is nothing we can do but hang up
1384 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1389 request_line = get_header(csp->client_iob);
1391 } while ((NULL != request_line) && ('\0' == *request_line));
1393 return request_line;
1399 CHUNK_STATUS_MISSING_DATA,
1400 CHUNK_STATUS_BODY_COMPLETE,
1401 CHUNK_STATUS_PARSE_ERROR
1405 /*********************************************************************
1407 * Function : chunked_body_is_complete
1409 * Description : Figures out whether or not a chunked body is complete.
1411 * Currently it always starts at the beginning of the
1412 * buffer which is somewhat wasteful and prevents Privoxy
1413 * from starting to forward the correctly parsed chunks
1414 * as soon as theoretically possible.
1416 * Should be modified to work with a common buffer,
1417 * and allow the caller to skip already parsed chunks.
1419 * This would allow the function to be used for unbuffered
1420 * response bodies as well.
1423 * 1 : iob = Buffer with the body to check.
1424 * 2 : length = Length of complete body
1426 * Returns : Enum with the result of the check.
1428 *********************************************************************/
1429 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1431 unsigned int chunksize;
1437 * We need at least a single digit, followed by "\r\n",
1438 * followed by an unknown amount of data, followed by "\r\n".
1440 if (p + 5 > iob->eod)
1442 return CHUNK_STATUS_MISSING_DATA;
1444 if (sscanf(p, "%x", &chunksize) != 1)
1446 return CHUNK_STATUS_PARSE_ERROR;
1450 * We want at least a single digit, followed by "\r\n",
1451 * followed by the specified amount of data, followed by "\r\n".
1453 if (p + chunksize + 5 > iob->eod)
1455 return CHUNK_STATUS_MISSING_DATA;
1458 /* Skip chunk-size. */
1459 p = strstr(p, "\r\n");
1462 return CHUNK_STATUS_PARSE_ERROR;
1464 /* Move beyond the chunkdata. */
1467 /* There should be another "\r\n" to skip */
1468 if (memcmp(p, "\r\n", 2))
1470 return CHUNK_STATUS_PARSE_ERROR;
1473 } while (chunksize > 0U);
1475 *length = (size_t)(p - iob->cur);
1476 assert(*length <= (size_t)(iob->eod - iob->cur));
1477 assert(p <= iob->eod);
1479 return CHUNK_STATUS_BODY_COMPLETE;
1484 /*********************************************************************
1486 * Function : receive_chunked_client_request_body
1488 * Description : Read the chunk-encoded client request body.
1489 * Failures are dealt with.
1492 * 1 : csp = Current client state (buffers, headers, etc...)
1494 * Returns : JB_ERR_OK or JB_ERR_PARSE
1496 *********************************************************************/
1497 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1500 enum chunk_status status;
1502 while (CHUNK_STATUS_MISSING_DATA ==
1503 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1505 char buf[BUFFER_SIZE];
1508 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1510 log_error(LOG_LEVEL_ERROR,
1511 "Timeout while waiting for the client body.");
1514 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1517 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1520 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1525 if (status != CHUNK_STATUS_BODY_COMPLETE)
1527 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1528 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1529 log_error(LOG_LEVEL_CLF,
1530 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1531 return JB_ERR_PARSE;
1533 log_error(LOG_LEVEL_CONNECT,
1534 "Chunked client body completely read. Length: %d", body_length);
1535 csp->expected_client_content_length = body_length;
1543 /*********************************************************************
1545 * Function : fuzz_chunked_transfer_encoding
1547 * Description : Treat the fuzzed input as chunked transfer encoding
1548 * to check and dechunk.
1551 * 1 : csp = Used to store the data.
1552 * 2 : fuzz_input_file = File to read the input from.
1554 * Returns : Result of dechunking
1556 *********************************************************************/
1557 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1560 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1561 enum chunk_status status;
1563 status = chunked_body_is_complete(csp->iob, &length);
1564 if (CHUNK_STATUS_BODY_COMPLETE != status)
1566 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1569 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1574 /*********************************************************************
1576 * Function : fuzz_client_request
1578 * Description : Try to get a client request from the fuzzed input.
1581 * 1 : csp = Current client state (buffers, headers, etc...)
1582 * 2 : fuzz_input_file = File to read the input from.
1584 * Returns : Result of fuzzing.
1586 *********************************************************************/
1587 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1592 csp->ip_addr_str = "fuzzer";
1594 if (strcmp(fuzz_input_file, "-") != 0)
1596 log_error(LOG_LEVEL_FATAL,
1597 "Fuzzed client requests can currenty only be read from stdin (-).");
1599 err = receive_client_request(csp);
1600 if (err != JB_ERR_OK)
1604 err = parse_client_request(csp);
1605 if (err != JB_ERR_OK)
1613 #endif /* def FUZZ */
1616 #ifdef FEATURE_FORCE_LOAD
1617 /*********************************************************************
1619 * Function : force_required
1621 * Description : Checks a request line to see if it contains
1622 * the FORCE_PREFIX. If it does, it is removed
1623 * unless enforcing requests has beend disabled.
1626 * 1 : request_line = HTTP request line
1628 * Returns : TRUE if force is required, FALSE otherwise.
1630 *********************************************************************/
1631 static int force_required(const struct client_state *csp, char *request_line)
1635 p = strstr(request_line, "http://");
1639 p += strlen("http://");
1643 /* Intercepted request usually don't specify the protocol. */
1647 /* Go to the beginning of the path */
1652 * If the path is missing the request line is invalid and we
1653 * are done here. The client-visible rejection happens later on.
1658 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1660 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1662 /* XXX: Should clean more carefully */
1663 strclean(request_line, FORCE_PREFIX);
1664 log_error(LOG_LEVEL_FORCE,
1665 "Enforcing request: \"%s\".", request_line);
1669 log_error(LOG_LEVEL_FORCE,
1670 "Ignored force prefix in request: \"%s\".", request_line);
1676 #endif /* def FEATURE_FORCE_LOAD */
1679 /*********************************************************************
1681 * Function : receive_client_request
1683 * Description : Read the client's request (more precisely the
1684 * client headers) and answer it if necessary.
1687 * 1 : csp = Current client state (buffers, headers, etc...)
1689 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1691 *********************************************************************/
1692 static jb_err receive_client_request(struct client_state *csp)
1694 char buf[BUFFER_SIZE];
1697 struct http_request *http;
1701 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1702 struct list header_list;
1703 struct list *headers = &header_list;
1705 /* We don't care if the arriving data is a valid HTTP request or not. */
1706 csp->requests_received_total++;
1710 memset(buf, 0, sizeof(buf));
1712 req = get_request_line(csp);
1715 mark_server_socket_tainted(csp);
1716 return JB_ERR_PARSE;
1718 assert(*req != '\0');
1720 if (client_protocol_is_unsupported(csp, req))
1722 return JB_ERR_PARSE;
1725 #ifdef FEATURE_FORCE_LOAD
1726 if (force_required(csp, req))
1728 csp->flags |= CSP_FLAG_FORCED;
1730 #endif /* def FEATURE_FORCE_LOAD */
1732 err = parse_http_request(req, http);
1734 if (JB_ERR_OK != err)
1736 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1737 get_write_delay(csp));
1738 /* XXX: Use correct size */
1739 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1740 log_error(LOG_LEVEL_ERROR,
1741 "Couldn't parse request line received from %s: %s",
1742 csp->ip_addr_str, jb_err_to_string(err));
1744 free_http_request(http);
1745 return JB_ERR_PARSE;
1748 /* grab the rest of the client's headers */
1752 p = get_header(csp->client_iob);
1756 /* There are no additional headers to read. */
1763 * We didn't receive a complete header
1764 * line yet, get the rest of it.
1766 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1768 log_error(LOG_LEVEL_ERROR,
1769 "Stopped grabbing the client headers.");
1770 destroy_list(headers);
1771 return JB_ERR_PARSE;
1774 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1777 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1778 destroy_list(headers);
1779 return JB_ERR_PARSE;
1782 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1785 * If there is no memory left for buffering the
1786 * request, there is nothing we can do but hang up
1788 destroy_list(headers);
1789 return JB_ERR_MEMORY;
1794 if (!strncmpic(p, "Transfer-Encoding:", 18))
1797 * XXX: should be called through sed()
1798 * but currently can't.
1800 client_transfer_encoding(csp, &p);
1803 * We were able to read a complete
1804 * header and can finally enlist it.
1811 if (http->host == NULL)
1814 * If we still don't know the request destination,
1815 * the request is invalid or the client uses
1816 * Privoxy without its knowledge.
1818 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1821 * Our attempts to get the request destination
1822 * elsewhere failed or Privoxy is configured
1823 * to only accept proxy requests.
1825 * An error response has already been send
1826 * and we're done here.
1828 return JB_ERR_PARSE;
1832 #ifdef FEATURE_CLIENT_TAGS
1833 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1834 set_client_address(csp, headers);
1835 get_tag_list_for_client(csp->client_tags, csp->client_address);
1839 * Determine the actions for this URL
1841 #ifdef FEATURE_TOGGLE
1842 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1844 /* Most compatible set of actions (i.e. none) */
1845 init_current_action(csp->action);
1848 #endif /* ndef FEATURE_TOGGLE */
1850 get_url_actions(csp, http);
1853 enlist(csp->headers, http->cmd);
1855 /* Append the previously read headers */
1856 err = list_append_list_unique(csp->headers, headers);
1857 destroy_list(headers);
1864 /*********************************************************************
1866 * Function : parse_client_request
1868 * Description : Parses the client's request and decides what to do
1871 * Note that since we're not using select() we could get
1872 * blocked here if a client connected, then didn't say
1876 * 1 : csp = Current client state (buffers, headers, etc...)
1878 * Returns : JB_ERR_OK or JB_ERR_PARSE
1880 *********************************************************************/
1881 static jb_err parse_client_request(struct client_state *csp)
1883 struct http_request *http = csp->http;
1886 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1887 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1888 && (!strcmpic(csp->http->ver, "HTTP/1.1"))
1889 && (csp->http->ssl == 0))
1891 /* Assume persistence until further notice */
1892 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1895 if (csp->http->ssl == 0)
1898 * This whole block belongs to chat() but currently
1899 * has to be executed before sed().
1901 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1903 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1905 return JB_ERR_PARSE;
1910 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1912 verify_request_length(csp);
1916 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1918 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1920 err = sed(csp, FILTER_CLIENT_HEADERS);
1921 if (JB_ERR_OK != err)
1923 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1925 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1926 csp->ip_addr_str, csp->http->cmd);
1927 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1928 return JB_ERR_PARSE;
1930 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1932 /* Check request line for rewrites. */
1933 if ((NULL == csp->headers->first->str)
1934 || (strcmp(http->cmd, csp->headers->first->str) &&
1935 (JB_ERR_OK != change_request_destination(csp))))
1938 * A header filter broke the request line - bail out.
1940 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1941 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1942 /* XXX: Use correct size */
1943 log_error(LOG_LEVEL_CLF,
1944 "%s - - [%T] \"Invalid request generated\" 500 0", csp->ip_addr_str);
1945 log_error(LOG_LEVEL_ERROR,
1946 "Invalid request line after applying header filters.");
1947 free_http_request(http);
1949 return JB_ERR_PARSE;
1952 if (client_has_unsupported_expectations(csp))
1954 return JB_ERR_PARSE;
1962 /*********************************************************************
1964 * Function : send_http_request
1966 * Description : Sends the HTTP headers from the client request
1967 * and all the body data that has already been received.
1970 * 1 : csp = Current client state (buffers, headers, etc...)
1972 * Returns : 0 on success, anything else is an error.
1974 *********************************************************************/
1975 static int send_http_request(struct client_state *csp)
1980 hdr = list_to_text(csp->headers);
1983 /* FIXME Should handle error properly */
1984 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
1986 list_remove_all(csp->headers);
1989 * Write the client's (modified) header to the server
1990 * (along with anything else that may be in the buffer)
1992 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
1997 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
1998 csp->http->hostport);
2000 else if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2001 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2004 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2005 csp->http->hostport);
2008 return write_failure;
2013 #ifdef FEATURE_HTTPS_INSPECTION
2014 /*********************************************************************
2016 * Function : receive_and_send_encrypted_post_data
2018 * Description : Reads remaining POST data from the client and sends
2022 * 1 : csp = Current client state (buffers, headers, etc...)
2024 * Returns : 0 on success, anything else is an error.
2026 *********************************************************************/
2027 static jb_err receive_and_send_encrypted_post_data(struct client_state *csp)
2029 unsigned char buf[BUFFER_SIZE];
2032 while (is_ssl_pending(&(csp->mbedtls_client_attr.ssl)))
2034 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl), buf, sizeof(buf));
2041 /* XXX: Does this actually happen? */
2044 log_error(LOG_LEVEL_HEADER, "Forwarding %d bytes of encrypted POST data",
2046 len = ssl_send_data(&(csp->mbedtls_server_attr.ssl), buf, (size_t)len);
2051 if (csp->expected_client_content_length != 0)
2053 if (csp->expected_client_content_length >= len)
2055 csp->expected_client_content_length -= (unsigned)len;
2060 log_error(LOG_LEVEL_HEADER, "Done forwarding encrypted POST data");
2067 /*********************************************************************
2069 * Function : send_https_request
2071 * Description : Sends the HTTP headers from the client request
2072 * and all the body data that has already been received.
2075 * 1 : csp = Current client state (buffers, headers, etc...)
2077 * Returns : 0 on success, anything else is an error.
2079 *********************************************************************/
2080 static int send_https_request(struct client_state *csp)
2086 hdr = list_to_text(csp->https_headers);
2089 /* FIXME Should handle error properly */
2090 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2092 list_remove_all(csp->https_headers);
2095 * Write the client's (modified) header to the server
2096 * (along with anything else that may be in the buffer)
2098 ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2099 (const unsigned char *)hdr, strlen(hdr));
2104 log_error(LOG_LEVEL_CONNECT,
2105 "Failed sending encrypted request headers to: %s: %E",
2106 csp->http->hostport);
2107 mark_server_socket_tainted(csp);
2108 close_client_and_server_ssl_connections(csp);
2112 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2113 && ((flushed = ssl_flush_socket(&(csp->mbedtls_server_attr.ssl),
2114 csp->client_iob)) < 0))
2116 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2117 csp->http->hostport);
2122 if (csp->expected_client_content_length != 0)
2124 if (csp->expected_client_content_length < flushed)
2126 log_error(LOG_LEVEL_ERROR,
2127 "Flushed %d bytes of request body while only expecting %llu",
2128 flushed, csp->expected_client_content_length);
2129 csp->expected_client_content_length = 0;
2133 log_error(LOG_LEVEL_CONNECT,
2134 "Flushed %d bytes of request body while expecting %llu",
2135 flushed, csp->expected_client_content_length);
2136 csp->expected_client_content_length -= (unsigned)flushed;
2137 if (receive_and_send_encrypted_post_data(csp))
2145 log_error(LOG_LEVEL_CONNECT,
2146 "Flushed %d bytes of request body", flushed);
2150 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2157 /*********************************************************************
2159 * Function : receive_encrypted_request
2161 * Description : Receives an encrypted request.
2164 * 1 : csp = Current client state (buffers, headers, etc...)
2166 * Returns : JB_ERR_OK on success,
2167 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2169 *********************************************************************/
2170 static jb_err receive_encrypted_request(struct client_state *csp)
2172 char buf[BUFFER_SIZE];
2178 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2179 if (!data_is_available(csp->cfd, (int)csp->config->keep_alive_timeout))
2181 log_error(LOG_LEVEL_CONNECT,
2182 "Socket %d timed out while waiting for client headers", csp->cfd);
2183 return JB_ERR_PARSE;
2185 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2186 (unsigned char *)buf, sizeof(buf));
2189 return JB_ERR_PARSE;
2191 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2193 return JB_ERR_MEMORY;
2195 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2196 } while (p == NULL);
2198 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2204 /*********************************************************************
2206 * Function : process_encrypted_request
2208 * Description : Receives and parses an encrypted request.
2211 * 1 : csp = Current client state (buffers, headers, etc...)
2213 * Returns : JB_ERR_OK on success,
2214 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2216 *********************************************************************/
2217 static jb_err process_encrypted_request(struct client_state *csp)
2222 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2223 struct list header_list;
2224 struct list *headers = &header_list;
2226 err = receive_encrypted_request(csp);
2227 if (err != JB_ERR_OK)
2229 /* XXX: Also used for JB_ERR_MEMORY */
2230 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2231 (const unsigned char *)CHEADER, strlen(CHEADER));
2235 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2236 request_line = get_header(csp->client_iob);
2237 if (request_line == NULL)
2239 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2240 (const unsigned char *)CHEADER, strlen(CHEADER));
2241 return JB_ERR_PARSE;
2243 assert(*request_line != '\0');
2245 if (client_protocol_is_unsupported(csp, request_line))
2247 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2248 (const unsigned char *)CHEADER, strlen(CHEADER));
2249 return JB_ERR_PARSE;
2252 #ifdef FEATURE_FORCE_LOAD
2253 if (force_required(csp, request_line))
2255 csp->flags |= CSP_FLAG_FORCED;
2257 #endif /* def FEATURE_FORCE_LOAD */
2259 free_http_request(csp->http);
2261 err = parse_http_request(request_line, csp->http);
2262 /* XXX: Restore ssl setting. This is ugly */
2263 csp->http->client_ssl = 1;
2264 csp->http->server_ssl = 1;
2266 freez(request_line);
2267 if (JB_ERR_OK != err)
2269 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2270 (const unsigned char *)CHEADER, strlen(CHEADER));
2271 /* XXX: Use correct size */
2272 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2273 log_error(LOG_LEVEL_ERROR,
2274 "Couldn't parse request line received from %s: %s",
2275 csp->ip_addr_str, jb_err_to_string(err));
2277 free_http_request(csp->http);
2278 return JB_ERR_PARSE;
2281 /* Parse the rest of the client's headers. */
2285 p = get_header(csp->client_iob);
2289 /* There are no additional headers to read. */
2296 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2299 * Our attempts to get the request destination
2302 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2303 (const unsigned char *)CHEADER, strlen(CHEADER));
2304 return JB_ERR_PARSE;
2307 #ifndef FEATURE_EXTENDED_HOST_PATTERNS
2308 /* Split the domain we just got for pattern matching */
2309 init_domain_components(csp->http);
2312 #ifdef FEATURE_TOGGLE
2313 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2316 /* Determine the actions for this URL */
2317 get_url_actions(csp, csp->http);
2320 enlist(csp->https_headers, csp->http->cmd);
2322 /* Append the previously read headers */
2323 err = list_append_list_unique(csp->https_headers, headers);
2324 destroy_list(headers);
2325 if (JB_ERR_OK != err)
2327 /* XXX: Send error message */
2331 /* XXX: Work around crash */
2332 csp->error_message = NULL;
2334 /* XXX: Why do this here? */
2337 err = sed_https(csp);
2338 if (JB_ERR_OK != err)
2340 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2341 (const unsigned char *)CHEADER, strlen(CHEADER));
2342 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2344 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2345 csp->ip_addr_str, csp->http->cmd);
2346 return JB_ERR_PARSE;
2349 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2350 log_applied_actions(csp->action);
2358 /*********************************************************************
2360 * Function : handle_established_connection
2362 * Description : Shuffle data between client and server once the
2363 * connection has been established.
2366 * 1 : csp = Current client state (buffers, headers, etc...)
2368 * Returns : Nothing.
2370 *********************************************************************/
2371 static void handle_established_connection(struct client_state *csp)
2377 struct pollfd poll_fds[2];
2381 struct timeval timeout;
2384 int ms_iis5_hack = 0;
2385 unsigned long long byte_count = 0;
2386 struct http_request *http;
2387 long len = 0; /* for buffer sizes (and negative error codes) */
2388 int buffer_and_filter_content = 0;
2389 unsigned int write_delay;
2390 #ifdef FEATURE_HTTPS_INSPECTION
2392 int use_ssl_tunnel = 0;
2393 csp->dont_verify_certificate = 0;
2396 * Preset flags informing if SSL connections with server or client
2397 * are opened or closed
2399 csp->ssl_with_server_is_opened = 0;
2400 csp->ssl_with_client_is_opened = 0;
2402 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
2404 /* Pass encrypted content without filtering. */
2409 /* Skeleton for HTTP response, if we should intercept the request */
2410 struct http_response *rsp;
2411 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2412 int watch_client_socket;
2415 csp->receive_buffer_size = csp->config->receive_buffer_size;
2416 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
2417 if (csp->receive_buffer == NULL)
2419 log_error(LOG_LEVEL_ERROR,
2420 "Out of memory. Failed to allocate the receive buffer.");
2421 rsp = cgi_error_memory();
2422 send_crunch_response(csp, rsp);
2429 maxfd = (csp->cfd > csp->server_connection.sfd) ?
2430 csp->cfd : csp->server_connection.sfd;
2433 /* pass data between the client and server
2434 * until one or the other shuts down the connection.
2439 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2440 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
2442 write_delay = get_write_delay(csp);
2449 * FD_ZERO here seems to point to an errant macro which crashes.
2450 * So do this by hand for now...
2452 memset(&rfds,0x00,sizeof(fd_set));
2456 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2457 if (!watch_client_socket)
2459 maxfd = csp->server_connection.sfd;
2462 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2464 FD_SET(csp->cfd, &rfds);
2467 FD_SET(csp->server_connection.sfd, &rfds);
2468 #endif /* ndef HAVE_POLL */
2470 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2471 if ((csp->flags & CSP_FLAG_CHUNKED)
2472 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
2473 && ((csp->iob->eod - csp->iob->cur) >= 5)
2474 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
2477 * XXX: This check should be obsolete now,
2478 * but let's wait a while to be sure.
2480 log_error(LOG_LEVEL_CONNECT,
2481 "Looks like we got the last chunk together with "
2482 "the server headers but didn't detect it earlier. "
2483 "We better stop reading.");
2484 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
2485 csp->expected_content_length = byte_count;
2486 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2488 if (server_body && server_response_is_complete(csp, byte_count))
2490 if (csp->expected_content_length == byte_count)
2492 log_error(LOG_LEVEL_CONNECT,
2493 "Done reading from server. Content length: %llu as expected. "
2494 "Bytes most recently read: %d.",
2499 log_error(LOG_LEVEL_CONNECT,
2500 "Done reading from server. Expected content length: %llu. "
2501 "Actual content length: %llu. Bytes most recently read: %d.",
2502 csp->expected_content_length, byte_count, len);
2506 * XXX: Should not jump around, handle_established_connection()
2507 * is complicated enough already.
2511 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2513 #ifdef FEATURE_HTTPS_INSPECTION
2515 * Test if some data from client or destination server are pending
2516 * on TLS/SSL. We must work with them preferably. TLS/SSL data can
2517 * be pending because of maximal fragment size.
2519 int read_ssl_server = 0;
2520 int read_ssl_client = 0;
2522 if (client_use_ssl(csp))
2524 read_ssl_client = is_ssl_pending(&(csp->mbedtls_client_attr.ssl)) != 0;
2527 if (server_use_ssl(csp))
2529 read_ssl_server = is_ssl_pending(&(csp->mbedtls_server_attr.ssl)) != 0;
2532 if (!read_ssl_server && !read_ssl_client)
2536 poll_fds[0].fd = csp->cfd;
2537 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2538 if (!watch_client_socket)
2541 * Ignore incoming data, but still watch out
2542 * for disconnects etc. These flags are always
2543 * implied anyway but explicitly setting them
2546 poll_fds[0].events = POLLERR|POLLHUP;
2551 poll_fds[0].events = POLLIN;
2553 poll_fds[1].fd = csp->server_connection.sfd;
2554 poll_fds[1].events = POLLIN;
2555 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
2557 timeout.tv_sec = csp->config->socket_timeout;
2558 timeout.tv_usec = 0;
2559 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
2560 #endif /* def HAVE_POLL */
2562 /*server or client not responding in timeout */
2565 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
2566 csp->config->socket_timeout, http->url);
2567 if ((byte_count == 0) && (http->ssl == 0))
2569 send_crunch_response(csp, error_response(csp, "connection-timeout"));
2571 mark_server_socket_tainted(csp);
2572 #ifdef FEATURE_HTTPS_INSPECTION
2573 close_client_and_server_ssl_connections(csp);
2580 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
2582 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
2584 mark_server_socket_tainted(csp);
2585 #ifdef FEATURE_HTTPS_INSPECTION
2586 close_client_and_server_ssl_connections(csp);
2591 #ifdef FEATURE_HTTPS_INSPECTION
2594 /* set FD if some data are pending on TLS/SSL connections */
2598 if (read_ssl_client)
2601 poll_fds[0].fd = csp->cfd;
2602 poll_fds[0].events = POLLIN;
2604 FD_SET(csp->cfd, &rfds);
2609 if (read_ssl_server)
2612 poll_fds[1].fd = csp->server_connection.sfd;
2613 poll_fds[1].events = POLLIN;
2615 FD_SET(csp->server_connection.sfd, &rfds);
2622 * This is the body of the browser's request,
2623 * just read and write it.
2625 * Receives data from browser and sends it to server
2627 * XXX: Make sure the client doesn't use pipelining
2628 * behind Privoxy's back.
2631 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
2633 log_error(LOG_LEVEL_CONNECT,
2634 "The client socket %d has become unusable while "
2635 "the server socket %d is still open.",
2636 csp->cfd, csp->server_connection.sfd);
2637 mark_server_socket_tainted(csp);
2641 if (poll_fds[0].revents != 0)
2643 if (FD_ISSET(csp->cfd, &rfds))
2644 #endif /* def HAVE_POLL*/
2646 int max_bytes_to_read = (int)csp->receive_buffer_size;
2648 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2649 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
2651 if (data_is_available(csp->cfd, 0))
2654 * If the next request is already waiting, we have
2655 * to stop select()ing the client socket. Otherwise
2656 * we would always return right away and get nothing
2659 watch_client_socket = 0;
2660 log_error(LOG_LEVEL_CONNECT,
2661 "Stop watching client socket %d. "
2662 "There's already another request waiting.",
2667 * If the client socket is set, but there's no data
2668 * available on the socket, the client went fishing
2669 * and continuing talking to the server makes no sense.
2671 log_error(LOG_LEVEL_CONNECT,
2672 "The client closed socket %d while "
2673 "the server socket %d is still open.",
2674 csp->cfd, csp->server_connection.sfd);
2675 mark_server_socket_tainted(csp);
2678 if (csp->expected_client_content_length != 0)
2680 if (csp->expected_client_content_length < csp->receive_buffer_size)
2682 max_bytes_to_read = (int)csp->expected_client_content_length;
2684 log_error(LOG_LEVEL_CONNECT,
2685 "Waiting for up to %d bytes from the client.",
2688 assert(max_bytes_to_read <= csp->receive_buffer_size);
2689 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2691 #ifdef FEATURE_HTTPS_INSPECTION
2693 * Reading data from standard or secured connection (HTTP/HTTPS)
2695 if (client_use_ssl(csp))
2698 * Receiving HTTP request from client over TLS/SSL and sending
2699 * it to server over TLS/SSL.
2701 len = ssl_recv_data(&(csp->mbedtls_client_attr.ssl),
2702 (unsigned char *)csp->receive_buffer, (size_t)max_bytes_to_read);
2706 mark_server_socket_tainted(csp);
2710 ret = ssl_send_data(&(csp->mbedtls_server_attr.ssl),
2711 (const unsigned char *)csp->receive_buffer, (size_t)len);
2715 log_error(LOG_LEVEL_ERROR,
2716 "Send request over TLS/SSL to: %s failed", http->host);
2717 mark_server_socket_tainted(csp);
2718 close_client_and_server_ssl_connections(csp);
2723 #endif /* def FEATURE_HTTPS_INSPECTION */
2725 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
2729 /* XXX: not sure if this is necessary. */
2730 mark_server_socket_tainted(csp);
2731 break; /* "game over, man" */
2734 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2735 if (csp->expected_client_content_length != 0)
2737 assert(len <= max_bytes_to_read);
2738 csp->expected_client_content_length -= (unsigned)len;
2739 log_error(LOG_LEVEL_CONNECT,
2740 "Expected client content length set to %llu "
2741 "after reading %d bytes.",
2742 csp->expected_client_content_length, len);
2743 if (csp->expected_client_content_length == 0)
2745 log_error(LOG_LEVEL_CONNECT,
2746 "Done reading from the client.");
2747 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
2750 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2752 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
2754 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
2755 mark_server_socket_tainted(csp);
2756 #ifdef FEATURE_HTTPS_INSPECTION
2757 close_client_and_server_ssl_connections(csp);
2766 * The server wants to talk. It could be the header or the body.
2767 * If `hdr' is null, then it's the header otherwise it's the body.
2768 * FIXME: Does `hdr' really mean `host'? No.
2771 if (poll_fds[1].revents != 0)
2773 if (FD_ISSET(csp->server_connection.sfd, &rfds))
2774 #endif /* HAVE_POLL */
2776 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2778 * If we are buffering content, we don't want to eat up to
2779 * buffer-limit bytes if the client no longer cares about them.
2780 * If we aren't buffering, however, a dead client socket will be
2781 * noticed pretty much right away anyway, so we can reduce the
2782 * overhead by skipping the check.
2784 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
2787 log_error(LOG_LEVEL_CONNECT,
2788 "The server still wants to talk, but the client may already have hung up on us.");
2790 log_error(LOG_LEVEL_CONNECT,
2791 "The server still wants to talk, but the client hung up on us.");
2792 mark_server_socket_tainted(csp);
2793 #ifdef FEATURE_HTTPS_INSPECTION
2794 close_client_and_server_ssl_connections(csp);
2797 #endif /* def _WIN32 */
2799 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2801 #ifdef FEATURE_HTTPS_INSPECTION
2803 * Reading data from standard or secured connection (HTTP/HTTPS)
2805 if (server_use_ssl(csp))
2807 len = ssl_recv_data(&(csp->mbedtls_server_attr.ssl),
2808 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
2813 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
2814 (int)csp->receive_buffer_size);
2819 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
2821 if ((http->ssl && (csp->fwd == NULL))
2822 #ifdef FEATURE_HTTPS_INSPECTION
2828 * Just hang up. We already confirmed the client's CONNECT
2829 * request with status code 200 and unencrypted content is
2830 * no longer welcome.
2832 log_error(LOG_LEVEL_ERROR,
2833 "CONNECT already confirmed. Unable to tell the client about the problem.");
2836 else if (byte_count)
2839 * Just hang up. We already transmitted the original headers
2840 * and parts of the original content and therefore missed the
2841 * chance to send an error message (without risking data corruption).
2843 * XXX: we could retry with a fancy range request here.
2845 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
2846 "Unable to tell the client about the problem.");
2847 mark_server_socket_tainted(csp);
2848 #ifdef FEATURE_HTTPS_INSPECTION
2849 close_client_and_server_ssl_connections(csp);
2854 * XXX: Consider handling the cases above the same.
2856 mark_server_socket_tainted(csp);
2860 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2861 if (csp->flags & CSP_FLAG_CHUNKED)
2863 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
2865 /* XXX: this is a temporary hack */
2866 log_error(LOG_LEVEL_CONNECT,
2867 "Looks like we reached the end of the last chunk. "
2868 "We better stop reading.");
2869 csp->expected_content_length = byte_count + (unsigned long long)len;
2870 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
2874 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
2877 * This is guaranteed by allocating with zalloc_or_die()
2878 * and never (intentionally) writing to the last byte.
2880 * csp->receive_buffer_size is the size of the part of the
2881 * buffer we intentionally write to, but we actually
2882 * allocated csp->receive_buffer_size+1 bytes so the assertion
2883 * stays within the allocated range.
2885 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
2888 * Add a trailing zero to let be able to use string operations.
2889 * XXX: do we still need this with filter_popups gone?
2891 assert(len <= csp->receive_buffer_size);
2892 csp->receive_buffer[len] = '\0';
2895 * Normally, this would indicate that we've read
2896 * as much as the server has sent us and we can
2897 * close the client connection. However, Microsoft
2898 * in its wisdom has released IIS/5 with a bug that
2899 * prevents it from sending the trailing \r\n in
2900 * a 302 redirect header (and possibly other headers).
2901 * To work around this if we've haven't parsed
2902 * a full header we'll append a trailing \r\n
2903 * and see if this now generates a valid one.
2905 * This hack shouldn't have any impacts. If we've
2906 * already transmitted the header or if this is a
2907 * SSL connection, then we won't bother with this
2908 * hack. So we only work on partially received
2909 * headers. If we append a \r\n and this still
2910 * doesn't generate a valid header, then we won't
2911 * transmit anything to the client.
2916 if (server_body || (http->ssl
2917 #ifdef FEATURE_HTTPS_INSPECTION
2923 * If we have been buffering up the document,
2924 * now is the time to apply content modification
2925 * and send the result to the client.
2927 if (buffer_and_filter_content)
2929 p = execute_content_filters(csp);
2931 * If content filtering fails, use the original
2932 * buffer and length.
2933 * (see p != NULL ? p : csp->iob->cur below)
2937 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
2939 #ifdef FEATURE_COMPRESSION
2940 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
2941 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
2943 char *compressed_content = compress_buffer(p,
2944 (size_t *)&csp->content_length, csp->config->compression_level);
2945 if (compressed_content != NULL)
2948 p = compressed_content;
2949 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
2954 if (JB_ERR_OK != update_server_headers(csp))
2956 log_error(LOG_LEVEL_FATAL,
2957 "Failed to update server headers. after filtering.");
2960 hdr = list_to_text(csp->headers);
2963 /* FIXME Should handle error properly */
2964 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
2967 #ifdef FEATURE_HTTPS_INSPECTION
2969 * Sending data with standard or secured connection (HTTP/HTTPS)
2971 if (client_use_ssl(csp))
2973 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2974 (const unsigned char *)hdr, strlen(hdr)) < 0)
2975 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
2976 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
2977 csp->content_length) < 0))
2979 log_error(LOG_LEVEL_ERROR, "write modified content to "
2980 "client over TLS/SSL failed");
2983 mark_server_socket_tainted(csp);
2984 close_client_and_server_ssl_connections(csp);
2989 #endif /* def FEATURE_HTTPS_INSPECTION */
2991 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
2992 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
2993 (size_t)csp->content_length, write_delay))
2995 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
2998 mark_server_socket_tainted(csp);
2999 #ifdef FEATURE_HTTPS_INSPECTION
3000 close_client_and_server_ssl_connections(csp);
3010 break; /* "game over, man" */
3014 * This is NOT the body, so
3015 * Let's pretend the server just sent us a blank line.
3017 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3018 len = (int)strlen(csp->receive_buffer);
3021 * Now, let the normal header parsing algorithm below do its
3022 * job. If it fails, we'll exit instead of continuing.
3029 * If we're in the body of the server document, just write it to
3030 * the client, unless we need to buffer the body for later
3031 * content-filtering.
3033 if (server_body || (http->ssl
3034 #ifdef FEATURE_HTTPS_INSPECTION
3039 if (buffer_and_filter_content)
3042 * If there is no memory left for buffering the content, or the buffer limit
3043 * has been reached, switch to non-filtering mode, i.e. make & write the
3044 * header, flush the iob and buf, and get out of the way.
3046 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3051 log_error(LOG_LEVEL_INFO,
3052 "Flushing header and buffers. Stepping back from filtering.");
3054 hdr = list_to_text(csp->headers);
3058 * Memory is too tight to even generate the header.
3059 * Send our static "Out-of-memory" page.
3061 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3062 rsp = cgi_error_memory();
3063 send_crunch_response(csp, rsp);
3064 mark_server_socket_tainted(csp);
3065 #ifdef FEATURE_HTTPS_INSPECTION
3066 close_client_and_server_ssl_connections(csp);
3070 hdrlen = strlen(hdr);
3072 #ifdef FEATURE_HTTPS_INSPECTION
3074 * Sending data with standard or secured connection (HTTP/HTTPS)
3076 if (client_use_ssl(csp))
3078 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3079 (const unsigned char *)hdr, hdrlen) < 0)
3080 || ((flushed = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3082 || (ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3083 (const unsigned char *)csp->receive_buffer, (size_t)len) < 0))
3085 log_error(LOG_LEVEL_CONNECT,
3086 "Flush header and buffers to client failed");
3088 mark_server_socket_tainted(csp);
3089 close_client_and_server_ssl_connections(csp);
3094 #endif /* def FEATURE_HTTPS_INSPECTION */
3096 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3097 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3098 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3101 log_error(LOG_LEVEL_CONNECT,
3102 "Flush header and buffers to client failed: %E");
3104 mark_server_socket_tainted(csp);
3105 #ifdef FEATURE_HTTPS_INSPECTION
3106 close_client_and_server_ssl_connections(csp);
3113 * Reset the byte_count to the amount of bytes
3114 * we just flushed. len will be added a few lines below,
3115 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3117 byte_count = (unsigned long long)flushed;
3119 buffer_and_filter_content = 0;
3125 #ifdef FEATURE_HTTPS_INSPECTION
3127 * Sending data with standard or secured connection (HTTP/HTTPS)
3129 if (client_use_ssl(csp))
3131 ret = ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3132 (const unsigned char *)csp->receive_buffer, (size_t)len);
3135 log_error(LOG_LEVEL_ERROR,
3136 "Sending data to client failed");
3137 mark_server_socket_tainted(csp);
3138 close_client_and_server_ssl_connections(csp);
3143 #endif /* def FEATURE_HTTPS_INSPECTION */
3145 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3146 (size_t)len, write_delay))
3148 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3149 mark_server_socket_tainted(csp);
3150 #ifdef FEATURE_HTTPS_INSPECTION
3151 close_client_and_server_ssl_connections(csp);
3157 byte_count += (unsigned long long)len;
3163 * We're still looking for the end of the server's header.
3164 * Buffer up the data we just read. If that fails, there's
3165 * little we can do but send our static out-of-memory page.
3167 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3169 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3170 rsp = cgi_error_memory();
3171 send_crunch_response(csp, rsp);
3172 mark_server_socket_tainted(csp);
3173 #ifdef FEATURE_HTTPS_INSPECTION
3174 close_client_and_server_ssl_connections(csp);
3179 /* Convert iob into something sed() can digest */
3180 if (JB_ERR_PARSE == get_server_headers(csp))
3185 * Well, we tried our MS IIS/5 hack and it didn't work.
3186 * The header is incomplete and there isn't anything
3187 * we can do about it.
3189 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3190 "Applying the MS IIS5 hack didn't help.");
3191 log_error(LOG_LEVEL_CLF,
3192 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3193 #ifdef FEATURE_HTTPS_INSPECTION
3195 * Sending data with standard or secured connection (HTTP/HTTPS)
3197 if (client_use_ssl(csp))
3199 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3200 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3201 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3204 #endif /* def FEATURE_HTTPS_INSPECTION */
3206 write_socket_delayed(csp->cfd,
3207 INVALID_SERVER_HEADERS_RESPONSE,
3208 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3210 mark_server_socket_tainted(csp);
3211 #ifdef FEATURE_HTTPS_INSPECTION
3212 close_client_and_server_ssl_connections(csp);
3219 * Since we have to wait for more from the server before
3220 * we can parse the headers we just continue here.
3222 log_error(LOG_LEVEL_CONNECT,
3223 "Continuing buffering server headers from socket %d. "
3224 "Bytes most recently read: %d.", csp->cfd, len);
3231 * Account for the content bytes we
3232 * might have gotten with the headers.
3234 assert(csp->iob->eod >= csp->iob->cur);
3235 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3238 /* Did we actually get anything? */
3239 if (NULL == csp->headers->first)
3241 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3243 log_error(LOG_LEVEL_ERROR,
3244 "No server or forwarder response received on socket %d. "
3245 "Closing client socket %d without sending data.",
3246 csp->server_connection.sfd, csp->cfd);
3247 log_error(LOG_LEVEL_CLF,
3248 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3252 log_error(LOG_LEVEL_ERROR,
3253 "No server or forwarder response received on socket %d.",
3254 csp->server_connection.sfd);
3255 send_crunch_response(csp, error_response(csp, "no-server-data"));
3257 free_http_request(http);
3258 mark_server_socket_tainted(csp);
3259 #ifdef FEATURE_HTTPS_INSPECTION
3260 close_client_and_server_ssl_connections(csp);
3265 if (!csp->headers->first->str)
3267 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3269 assert(csp->headers->first->str);
3271 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&
3272 strncmpic(csp->headers->first->str, "ICY", 3))
3275 * It doesn't look like a HTTP (or Shoutcast) response:
3276 * tell the client and log the problem.
3278 if (strlen(csp->headers->first->str) > 30)
3280 csp->headers->first->str[30] = '\0';
3282 log_error(LOG_LEVEL_ERROR,
3283 "Invalid server or forwarder response. Starts with: %s",
3284 csp->headers->first->str);
3285 log_error(LOG_LEVEL_CLF,
3286 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3287 #ifdef FEATURE_HTTPS_INSPECTION
3289 * Sending data with standard or secured connection (HTTP/HTTPS)
3291 if (client_use_ssl(csp))
3293 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3294 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3295 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3298 #endif /* def FEATURE_HTTPS_INSPECTION */
3300 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3301 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3303 free_http_request(http);
3304 mark_server_socket_tainted(csp);
3305 #ifdef FEATURE_HTTPS_INSPECTION
3306 close_client_and_server_ssl_connections(csp);
3312 * We have now received the entire server header,
3313 * filter it and send the result to the client
3315 if (JB_ERR_OK != sed(csp, FILTER_SERVER_HEADERS))
3317 log_error(LOG_LEVEL_CLF,
3318 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3319 #ifdef FEATURE_HTTPS_INSPECTION
3321 * Sending data with standard or secured connection (HTTP/HTTPS)
3323 if (client_use_ssl(csp))
3325 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3326 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3327 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3332 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3333 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3335 free_http_request(http);
3336 mark_server_socket_tainted(csp);
3337 #ifdef FEATURE_HTTPS_INSPECTION
3338 close_client_and_server_ssl_connections(csp);
3342 hdr = list_to_text(csp->headers);
3345 /* FIXME Should handle error properly */
3346 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3349 if ((csp->flags & CSP_FLAG_CHUNKED)
3350 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3351 && ((csp->iob->eod - csp->iob->cur) >= 5)
3352 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3354 log_error(LOG_LEVEL_CONNECT,
3355 "Looks like we got the last chunk together with "
3356 "the server headers. We better stop reading.");
3357 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3358 csp->expected_content_length = byte_count;
3359 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3362 csp->server_connection.response_received = time(NULL);
3364 if (crunch_response_triggered(csp, crunchers_light))
3367 * One of the tags created by a server-header
3368 * tagger triggered a crunch. We already
3369 * delivered the crunch response to the client
3370 * and are done here after cleaning up.
3373 mark_server_socket_tainted(csp);
3374 #ifdef FEATURE_HTTPS_INSPECTION
3375 close_client_and_server_ssl_connections(csp);
3380 /* Buffer and pcrs filter this if appropriate. */
3381 buffer_and_filter_content = content_requires_filtering(csp);
3383 if (!buffer_and_filter_content)
3386 * Write the server's (modified) header to
3387 * the client (along with anything else that
3388 * may be in the buffer). Use standard or secured
3391 #ifdef FEATURE_HTTPS_INSPECTION
3392 if (client_use_ssl(csp))
3394 if ((ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3395 (const unsigned char *)hdr, strlen(hdr)) < 0)
3396 || (len = ssl_flush_socket(&(csp->mbedtls_client_attr.ssl),
3399 log_error(LOG_LEVEL_CONNECT, "Write header to client failed");
3402 * The write failed, so don't bother mentioning it
3403 * to the client... it probably can't hear us anyway.
3406 mark_server_socket_tainted(csp);
3407 #ifdef FEATURE_HTTPS_INSPECTION
3408 close_client_and_server_ssl_connections(csp);
3414 #endif /* def FEATURE_HTTPS_INSPECTION */
3416 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3417 || ((len = flush_iob(csp->cfd, csp->iob, write_delay)) < 0))
3419 log_error(LOG_LEVEL_ERROR,
3420 "write header to client failed");
3422 * The write failed, so don't bother mentioning it
3423 * to the client... it probably can't hear us anyway.
3426 mark_server_socket_tainted(csp);
3427 #ifdef FEATURE_HTTPS_INSPECTION
3428 close_client_and_server_ssl_connections(csp);
3435 /* we're finished with the server's header */
3441 * If this was a MS IIS/5 hack then it means the server
3442 * has already closed the connection. Nothing more to read.
3447 log_error(LOG_LEVEL_ERROR,
3448 "Closed server connection detected. "
3449 "Applying the MS IIS5 hack didn't help.");
3450 log_error(LOG_LEVEL_CLF,
3451 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3452 #ifdef FEATURE_HTTPS_INSPECTION
3454 * Sending data with standard or secured connection (HTTP/HTTPS)
3456 if (client_use_ssl(csp))
3458 ssl_send_data(&(csp->mbedtls_client_attr.ssl),
3459 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3460 strlen(INVALID_SERVER_HEADERS_RESPONSE));
3463 #endif /* def FEATURE_HTTPS_INSPECTION */
3465 write_socket_delayed(csp->cfd, INVALID_SERVER_HEADERS_RESPONSE,
3466 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3468 mark_server_socket_tainted(csp);
3469 #ifdef FEATURE_HTTPS_INSPECTION
3470 close_client_and_server_ssl_connections(csp);
3477 mark_server_socket_tainted(csp);
3478 #ifdef FEATURE_HTTPS_INSPECTION
3479 close_client_and_server_ssl_connections(csp);
3481 return; /* huh? we should never get here */
3483 #ifdef FEATURE_HTTPS_INSPECTION
3484 close_client_and_server_ssl_connections(csp);
3486 if (csp->content_length == 0)
3489 * If Privoxy didn't recalculate the Content-Length,
3490 * byte_count is still correct.
3492 csp->content_length = byte_count;
3495 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3496 if ((csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3497 && (csp->expected_content_length != byte_count))
3499 log_error(LOG_LEVEL_CONNECT,
3500 "Received %llu bytes while expecting %llu.",
3501 byte_count, csp->expected_content_length);
3502 mark_server_socket_tainted(csp);
3506 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 200 %llu",
3507 csp->ip_addr_str, http->ocmd, csp->content_length);
3509 csp->server_connection.timestamp = time(NULL);
3513 /*********************************************************************
3517 * Description : Once a connection from the client has been accepted,
3518 * this function is called (via serve()) to handle the
3519 * main business of the communication. This function
3520 * returns after dealing with a single request. It can
3521 * be called multiple times with the same client socket
3522 * if the client is keeping the connection alive.
3524 * The decision whether or not a client connection will
3525 * be kept alive is up to the caller which also must
3526 * close the client socket when done.
3528 * FIXME: chat is nearly thousand lines long.
3532 * 1 : csp = Current client state (buffers, headers, etc...)
3534 * Returns : Nothing.
3536 *********************************************************************/
3537 static void chat(struct client_state *csp)
3539 const struct forward_spec *fwd;
3540 struct http_request *http;
3541 /* Skeleton for HTTP response, if we should intercept the request */
3542 struct http_response *rsp;
3543 #ifdef FEATURE_HTTPS_INSPECTION
3544 int use_ssl_tunnel = 0;
3549 if (receive_client_request(csp) != JB_ERR_OK)
3553 if (parse_client_request(csp) != JB_ERR_OK)
3558 /* decide how to route the HTTP request */
3559 fwd = forward_url(csp, http);
3562 log_error(LOG_LEVEL_FATAL, "gateway spec is NULL!?!? This can't happen!");
3563 /* Never get here - LOG_LEVEL_FATAL causes program exit */
3567 #ifdef FEATURE_HTTPS_INSPECTION
3569 * Setting flags to use old solution with SSL tunnel and to disable
3570 * certificates verification.
3572 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3577 if (http->ssl && csp->action->flags & ACTION_IGNORE_CERTIFICATE_ERRORS)
3579 csp->dont_verify_certificate = 1;
3584 * build the http request to send to the server
3585 * we have to do one of the following:
3587 * create = use the original HTTP request to create a new
3588 * HTTP request that has either the path component
3589 * without the http://domainspec (w/path) or the
3590 * full orininal URL (w/url)
3591 * Note that the path and/or the HTTP version may
3592 * have been altered by now.
3594 * SSL proxy = Open a socket to the host:port of the server
3595 * and create TLS/SSL connection with server and
3596 * with client. Then behave like mediator between
3597 * client and server over TLS/SSL.
3599 * SSL proxy = Pass the request unchanged if forwarding a CONNECT
3600 * with request to a parent proxy. Note that we'll be sending
3601 * forwarding the CFAIL message ourselves if connecting to the parent
3602 * fails, but we won't send a CSUCCEED message if it works,
3603 * since that would result in a double message (ours and the
3604 * parent's). After sending the request to the parent, we
3605 * must parse answer and send it to client. If connection
3606 * with server is established, we do TLS/SSL proxy. Otherwise
3607 * we send parent response to client and close connections.
3609 * here's the matrix:
3612 * +--------+--------+
3614 * 0 | create | SSL |
3615 * | w/path | proxy |
3616 * Forwarding +--------+--------+
3618 * 1 | create | proxy |
3619 * | w/url |+forward|
3620 * +--------+--------+
3624 #ifdef FEATURE_HTTPS_INSPECTION
3626 * Presetting SSL client and server flags
3628 if (http->ssl && !use_ssl_tunnel)
3630 http->client_ssl = 1;
3631 http->server_ssl = 1;
3635 http->client_ssl = 0;
3636 http->server_ssl = 0;
3640 if (http->ssl && connect_port_is_forbidden(csp))
3642 const char *acceptable_connect_ports =
3643 csp->action->string[ACTION_STRING_LIMIT_CONNECT];
3644 assert(NULL != acceptable_connect_ports);
3645 log_error(LOG_LEVEL_INFO, "Request from %s marked for blocking. "
3646 "limit-connect{%s} doesn't allow CONNECT requests to %s",
3647 csp->ip_addr_str, acceptable_connect_ports, csp->http->hostport);
3648 csp->action->flags |= ACTION_BLOCK;
3650 #ifdef FEATURE_HTTPS_INSPECTION
3651 http->client_ssl = 0;
3652 http->server_ssl = 0;
3657 freez(csp->headers->first->str);
3658 build_request_line(csp, fwd, &csp->headers->first->str);
3661 * We have a request. Check if one of the crunchers wants it
3662 * unless the client wants to use TLS/SSL in which case we
3663 * haven't setup the TLS context yet and will send the crunch
3667 #ifdef FEATURE_HTTPS_INSPECTION
3668 !client_use_ssl(csp) &&
3670 crunch_response_triggered(csp, crunchers_all))
3673 * Yes. The client got the crunch response and we're done here.
3678 log_applied_actions(csp->action);
3679 log_error(LOG_LEVEL_GPC, "%s%s", http->hostport, http->path);
3681 if (fwd->forward_host)
3683 log_error(LOG_LEVEL_CONNECT, "via [%s]:%d to: %s",
3684 fwd->forward_host, fwd->forward_port, http->hostport);
3688 log_error(LOG_LEVEL_CONNECT, "to %s", http->hostport);
3691 /* here we connect to the server, gateway, or the forwarder */
3693 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3694 if ((csp->server_connection.sfd != JB_INVALID_SOCKET)
3695 && socket_is_still_alive(csp->server_connection.sfd)
3696 && connection_destination_matches(&csp->server_connection, http, fwd))
3698 log_error(LOG_LEVEL_CONNECT,
3699 "Reusing server socket %d connected to %s. Total requests: %u.",
3700 csp->server_connection.sfd, csp->server_connection.host,
3701 csp->server_connection.requests_sent_total);
3705 if (csp->server_connection.sfd != JB_INVALID_SOCKET)
3707 #ifdef FEATURE_CONNECTION_SHARING
3708 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
3710 remember_connection(&csp->server_connection);
3713 #endif /* def FEATURE_CONNECTION_SHARING */
3715 log_error(LOG_LEVEL_CONNECT,
3716 "Closing server socket %d connected to %s. Total requests: %u.",
3717 csp->server_connection.sfd, csp->server_connection.host,
3718 csp->server_connection.requests_sent_total);
3719 close_socket(csp->server_connection.sfd);
3721 mark_connection_closed(&csp->server_connection);
3723 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3724 #ifdef FEATURE_HTTPS_INSPECTION
3725 if (http->ssl && !use_ssl_tunnel)
3729 * Creating an SSL proxy. If forwarding is disabled, we must send
3730 * CSUCCEED mesage to client. Then TLS/SSL connection with client
3734 if (fwd->forward_host == NULL)
3737 * We're lying to the client as the connection hasn't actually
3738 * been established yet. We don't establish the connection until
3739 * we have seen and parsed the encrypted client headers.
3741 if (write_socket_delayed(csp->cfd, CSUCCEED,
3742 strlen(CSUCCEED), get_write_delay(csp)) != 0)
3744 log_error(LOG_LEVEL_ERROR, "Sending SUCCEED to client failed");
3749 ret = create_client_ssl_connection(csp);
3752 log_error(LOG_LEVEL_ERROR,
3753 "Can't open secure connection with client");
3754 close_client_ssl_connection(csp); /* XXX: Is this needed? */
3757 if (JB_ERR_OK != process_encrypted_request(csp))
3759 log_error(LOG_LEVEL_ERROR, "Failed to parse encrypted request.");
3760 close_client_ssl_connection(csp);
3764 * We have an encrypted request. Check if one of the crunchers now
3765 * wants it (for example because the previously invisible path was
3766 * required to match).
3768 if (crunch_response_triggered(csp, crunchers_all))
3771 * Yes. The client got the crunch response and we're done here.
3773 close_client_ssl_connection(csp);