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-2021 the
9 * Privoxy team. https://www.privoxy.org/
11 * Based on the Internet Junkbuster originally written
12 * by and Copyright (C) 1997 Anonymous Coders and
13 * Junkbusters Corporation. http://www.junkbusters.com
15 * This program is free software; you can redistribute it
16 * and/or modify it under the terms of the GNU General
17 * Public License as published by the Free Software
18 * Foundation; either version 2 of the License, or (at
19 * your option) any later version.
21 * This program is distributed in the hope that it will
22 * be useful, but WITHOUT ANY WARRANTY; without even the
23 * implied warranty of MERCHANTABILITY or FITNESS FOR A
24 * PARTICULAR PURPOSE. See the GNU General Public
25 * License for more details.
27 * The GNU General Public License should be included with
28 * this file. If not, you can view it at
29 * http://www.gnu.org/copyleft/gpl.html
30 * or write to the Free Software Foundation, Inc., 59
31 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
33 *********************************************************************/
39 #include <sys/types.h>
48 # ifndef FEATURE_PTHREAD
52 # include <winsock2.h>
55 # endif /* ndef FEATURE_PTHREAD */
60 # endif /* ndef _WIN_CONSOLE */
61 # include "w32svrapi.h"
63 #else /* ifndef _WIN32 */
66 # include <sys/wait.h>
67 # include <sys/time.h>
68 # include <sys/stat.h>
69 # include <sys/ioctl.h>
72 #include <sys/termios.h>
83 # include <socket.h> /* BeOS has select() for sockets only. */
84 # include <OS.h> /* declarations for threads and stuff. */
92 #endif /* def __GLIBC__ */
97 #warning poll() appears to be unavailable. Your platform will become unsupported in the future.
98 #endif /* HAVE_POLL */
105 #ifdef FEATURE_HTTPS_INSPECTION
111 #include "miscutil.h"
113 #include "jbsockets.h"
118 #include "urlmatch.h"
119 #ifdef FEATURE_CLIENT_TAGS
120 #include "client-tags.h"
124 struct client_states clients[1];
125 struct file_list files[1];
127 #ifdef FEATURE_STATISTICS
128 int urls_read = 0; /* total nr of urls read inc rejected */
129 int urls_rejected = 0; /* total nr of urls rejected */
130 #endif /* def FEATURE_STATISTICS */
132 #ifdef FEATURE_GRACEFUL_TERMINATION
137 static void sig_handler(int the_signal);
139 static int client_protocol_is_unsupported(struct client_state *csp, char *req);
140 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers);
141 static jb_err get_server_headers(struct client_state *csp);
142 static const char *crunch_reason(const struct http_response *rsp);
143 static void send_crunch_response(struct client_state *csp, struct http_response *rsp);
144 static char *get_request_line(struct client_state *csp);
145 static jb_err receive_client_request(struct client_state *csp);
146 static jb_err parse_client_request(struct client_state *csp);
147 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line);
148 static jb_err change_request_destination(struct client_state *csp);
149 static void handle_established_connection(struct client_state *csp);
150 static void chat(struct client_state *csp);
151 static void serve(struct client_state *csp);
152 #if !defined(_WIN32) || defined(_WIN_CONSOLE)
153 static void usage(const char *myname);
155 static void initialize_mutexes(void);
156 static jb_socket bind_port_helper(const char *haddr, int hport, int backlog);
157 static void bind_ports_helper(struct configuration_spec *config, jb_socket sockets[]);
158 static void close_ports_helper(jb_socket sockets[]);
159 static void listen_loop(void);
160 static void serve(struct client_state *csp);
163 static int32 server_thread(void *data);
164 #endif /* def __BEOS__ */
167 #define sleep(N) Sleep(((N) * 1000))
171 int process_fuzzed_input(char *fuzz_input_type, char *fuzz_input_file);
172 void show_fuzz_usage(const char *name);
175 #ifdef MUTEX_LOCKS_AVAILABLE
177 * XXX: Does the locking stuff really belong in this file?
179 privoxy_mutex_t log_mutex;
180 privoxy_mutex_t log_init_mutex;
181 privoxy_mutex_t connection_reuse_mutex;
183 #ifdef FEATURE_HTTPS_INSPECTION
184 privoxy_mutex_t certificate_mutex;
185 privoxy_mutex_t ssl_init_mutex;
188 #ifdef FEATURE_EXTERNAL_FILTERS
189 privoxy_mutex_t external_filter_mutex;
191 #ifdef FEATURE_CLIENT_TAGS
192 privoxy_mutex_t client_tags_mutex;
194 #ifdef FEATURE_EXTENDED_STATISTICS
195 privoxy_mutex_t filter_statistics_mutex;
196 privoxy_mutex_t block_statistics_mutex;
199 #if !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R)
200 privoxy_mutex_t resolver_mutex;
201 #endif /* !defined(HAVE_GETHOSTBYADDR_R) || !defined(HAVE_GETHOSTBYNAME_R) */
203 #ifndef HAVE_GMTIME_R
204 privoxy_mutex_t gmtime_mutex;
205 #endif /* ndef HAVE_GMTIME_R */
207 #ifndef HAVE_LOCALTIME_R
208 privoxy_mutex_t localtime_mutex;
209 #endif /* ndef HAVE_GMTIME_R */
211 #if !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM)
212 privoxy_mutex_t rand_mutex;
213 #endif /* !defined(HAVE_ARC4RANDOM) && !defined(HAVE_RANDOM) */
215 #endif /* def MUTEX_LOCKS_AVAILABLE */
218 const char *basedir = NULL;
219 const char *pidfile = NULL;
220 static int received_hup_signal = 0;
221 #endif /* defined unix */
223 /* HTTP snipplets. */
224 static const char CSUCCEED[] =
225 "HTTP/1.1 200 Connection established\r\n\r\n";
227 static const char CHEADER[] =
228 "HTTP/1.1 400 Invalid header received from client\r\n"
229 "Content-Type: text/plain\r\n"
230 "Connection: close\r\n\r\n"
231 "Invalid header received from client.\r\n";
233 static const char FTP_RESPONSE[] =
234 "HTTP/1.1 400 Invalid request received from client\r\n"
235 "Content-Type: text/plain\r\n"
236 "Connection: close\r\n\r\n"
237 "Invalid request. Privoxy doesn't support FTP.\r\n";
239 static const char GOPHER_RESPONSE[] =
240 "HTTP/1.1 400 Invalid request received from client\r\n"
241 "Content-Type: text/plain\r\n"
242 "Connection: close\r\n\r\n"
243 "Invalid request. Privoxy doesn't support gopher.\r\n";
245 /* XXX: should be a template */
246 static const char MISSING_DESTINATION_RESPONSE[] =
247 "HTTP/1.1 400 Bad request received from client\r\n"
248 "Content-Type: text/plain\r\n"
249 "Connection: close\r\n\r\n"
250 "Bad request. Privoxy was unable to extract the destination.\r\n";
252 /* XXX: should be a template */
253 static const char INVALID_SERVER_HEADERS_RESPONSE[] =
254 "HTTP/1.1 502 Server or forwarder response invalid\r\n"
255 "Content-Type: text/plain\r\n"
256 "Connection: close\r\n\r\n"
257 "Bad response. The server or forwarder response doesn't look like HTTP.\r\n";
259 /* XXX: should be a template */
260 static const char MESSED_UP_REQUEST_RESPONSE[] =
261 "HTTP/1.1 400 Malformed request after rewriting\r\n"
262 "Content-Type: text/plain\r\n"
263 "Connection: close\r\n\r\n"
264 "Bad request. Messed up with header filters.\r\n";
266 static const char TOO_MANY_CONNECTIONS_RESPONSE[] =
267 "HTTP/1.1 503 Too many open connections\r\n"
268 "Content-Type: text/plain\r\n"
269 "Connection: close\r\n\r\n"
270 "Maximum number of open connections reached.\r\n";
272 static const char CLIENT_CONNECTION_TIMEOUT_RESPONSE[] =
273 "HTTP/1.1 504 Connection timeout\r\n"
274 "Content-Type: text/plain\r\n"
275 "Connection: close\r\n\r\n"
276 "The connection timed out because the client request didn't arrive in time.\r\n";
278 static const char CLIENT_BODY_PARSE_ERROR_RESPONSE[] =
279 "HTTP/1.1 400 Failed reading client body\r\n"
280 "Content-Type: text/plain\r\n"
281 "Connection: close\r\n\r\n"
282 "Failed parsing or buffering the chunk-encoded client body.\r\n";
284 static const char UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE[] =
285 "HTTP/1.1 417 Expecting too much\r\n"
286 "Content-Type: text/plain\r\n"
287 "Connection: close\r\n\r\n"
288 "Privoxy detected an unsupported Expect header value.\r\n";
290 /* A function to crunch a response */
291 typedef struct http_response *(*crunch_func_ptr)(struct client_state *);
293 /* Crunch function flags */
294 #define CF_NO_FLAGS 0
295 /* Cruncher applies to forced requests as well */
296 #define CF_IGNORE_FORCE 1
297 /* Crunched requests are counted for the block statistics */
298 #define CF_COUNT_AS_REJECT 2
300 /* A crunch function and its flags */
303 const crunch_func_ptr cruncher;
307 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[]);
309 /* Complete list of cruncher functions */
310 static const struct cruncher crunchers_all[] = {
311 { direct_response, CF_COUNT_AS_REJECT|CF_IGNORE_FORCE},
312 { block_url, CF_COUNT_AS_REJECT },
314 { trust_url, CF_COUNT_AS_REJECT },
315 #endif /* def FEATURE_TRUST */
316 { redirect_url, CF_NO_FLAGS },
317 { dispatch_cgi, CF_IGNORE_FORCE},
321 /* Light version, used after tags are applied */
322 static const struct cruncher crunchers_light[] = {
323 { block_url, CF_COUNT_AS_REJECT },
324 { redirect_url, CF_NO_FLAGS },
330 * XXX: Don't we really mean
337 /*********************************************************************
339 * Function : sig_handler
341 * Description : Signal handler for different signals.
342 * Exit gracefully on TERM and INT
343 * or set a flag that will cause the errlog
344 * to be reopened by the main thread on HUP.
347 * 1 : the_signal = the signal cause this function to call
351 *********************************************************************/
352 static void sig_handler(int the_signal)
358 log_error(LOG_LEVEL_INFO, "exiting by signal %d .. bye", the_signal);
370 received_hup_signal = 1;
376 * We shouldn't be here, unless we catch signals
377 * in main() that we can't handle here!
379 log_error(LOG_LEVEL_FATAL,
380 "sig_handler: exiting on unexpected signal %d", the_signal);
388 /*********************************************************************
390 * Function : get_write_delay
392 * Description : Parse the delay-response parameter.
395 * 1 : csp = Current client state (buffers, headers, etc...)
397 * Returns : Number of milliseconds to delay writes.
399 *********************************************************************/
400 static unsigned int get_write_delay(const struct client_state *csp)
406 if ((csp->action->flags & ACTION_DELAY_RESPONSE) == 0)
410 newval = csp->action->string[ACTION_STRING_DELAY_RESPONSE];
412 delay = (unsigned)strtol(newval, &endptr, 0);
415 log_error(LOG_LEVEL_FATAL,
416 "Invalid delay-response{} parameter: '%s'", newval);
424 /*********************************************************************
426 * Function : client_protocol_is_unsupported
428 * Description : Checks if the client used a known unsupported
429 * protocol and deals with it by sending an error
433 * 1 : csp = Current client state (buffers, headers, etc...)
434 * 2 : req = the first request line send by the client
436 * Returns : TRUE if an error response has been generated, or
437 * FALSE if the request doesn't look invalid.
439 *********************************************************************/
440 static int client_protocol_is_unsupported(struct client_state *csp, char *req)
443 * If it's a FTP or gopher request, we don't support it.
445 * These checks are better than nothing, but they might
446 * not work in all configurations and some clients might
447 * have problems digesting the answer.
449 * They should, however, never cause more problems than
450 * Privoxy's old behaviour (returning the misleading HTML
453 * "Could not resolve http://(ftp|gopher)://example.org").
455 if (!strncmpic(req, "GET ftp://", 10) || !strncmpic(req, "GET gopher://", 13))
457 const char *response = NULL;
458 const char *protocol = NULL;
460 if (!strncmpic(req, "GET ftp://", 10))
462 response = FTP_RESPONSE;
467 response = GOPHER_RESPONSE;
470 log_error(LOG_LEVEL_ERROR,
471 "%s tried to use Privoxy as %s proxy: %s",
472 csp->ip_addr_str, protocol, req);
473 log_error(LOG_LEVEL_CLF,
474 "%s - - [%T] \"%s\" 400 0", csp->ip_addr_str, req);
477 #ifdef FEATURE_HTTPS_INSPECTION
478 if (client_use_ssl(csp))
480 ssl_send_data_delayed(&(csp->ssl_client_attr),
481 (const unsigned char *)response, strlen(response),
482 get_write_delay(csp));
487 write_socket_delayed(csp->cfd, response, strlen(response),
488 get_write_delay(csp));
498 /*********************************************************************
500 * Function : client_has_unsupported_expectations
502 * Description : Checks if the client used an unsupported expectation
503 * in which case an error message is delivered.
506 * 1 : csp = Current client state (buffers, headers, etc...)
508 * Returns : TRUE if an error response has been generated, or
509 * FALSE if the request doesn't look invalid.
511 *********************************************************************/
512 static int client_has_unsupported_expectations(const struct client_state *csp)
514 if ((csp->flags & CSP_FLAG_UNSUPPORTED_CLIENT_EXPECTATION))
516 log_error(LOG_LEVEL_ERROR,
517 "Rejecting request from client %s with unsupported Expect header value",
519 log_error(LOG_LEVEL_CLF,
520 "%s - - [%T] \"%s\" 417 0", csp->ip_addr_str, csp->http->cmd);
521 write_socket_delayed(csp->cfd,
522 UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE,
523 strlen(UNSUPPORTED_CLIENT_EXPECTATION_ERROR_RESPONSE),
524 get_write_delay(csp));
534 /*********************************************************************
536 * Function : get_request_destination_elsewhere
538 * Description : If the client's request was redirected into
539 * Privoxy without the client's knowledge,
540 * the request line lacks the destination host.
542 * This function tries to get it elsewhere,
543 * provided accept-intercepted-requests is enabled.
545 * "Elsewhere" currently only means "Host: header",
546 * but in the future we may ask the redirecting
547 * packet filter to look the destination up.
549 * If the destination stays unknown, an error
550 * response is send to the client and headers
551 * are freed so that chat() can return directly.
554 * 1 : csp = Current client state (buffers, headers, etc...)
555 * 2 : headers = a header list
557 * Returns : JB_ERR_OK if the destination is now known, or
558 * JB_ERR_PARSE if it isn't.
560 *********************************************************************/
561 static jb_err get_request_destination_elsewhere(struct client_state *csp, struct list *headers)
563 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ACCEPT_INTERCEPTED_REQUESTS))
565 log_error(LOG_LEVEL_ERROR, "%s's request: \'%s\' is invalid."
566 " Privoxy isn't configured to accept intercepted requests.",
567 csp->ip_addr_str, csp->http->cmd);
568 /* XXX: Use correct size */
569 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
570 csp->ip_addr_str, csp->http->cmd);
572 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
573 get_write_delay(csp));
574 destroy_list(headers);
578 else if (JB_ERR_OK == get_destination_from_headers(headers, csp->http))
580 /* Split the domain we just got for pattern matching */
581 init_domain_components(csp->http);
587 /* We can't work without destination. Go spread the news.*/
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: %s",
594 csp->ip_addr_str, csp->http->cmd);
596 write_socket_delayed(csp->cfd, MISSING_DESTINATION_RESPONSE,
597 strlen(MISSING_DESTINATION_RESPONSE), get_write_delay(csp));
598 destroy_list(headers);
603 * TODO: If available, use PF's ioctl DIOCNATLOOK as last resort
604 * to get the destination IP address, use it as host directly
605 * or do a reverse DNS lookup first.
610 /*********************************************************************
612 * Function : get_server_headers
614 * Description : Parses server headers in iob and fills them
615 * into csp->headers so that they can later be
619 * 1 : csp = Current client state (buffers, headers, etc...)
621 * Returns : JB_ERR_OK if everything went fine, or
622 * JB_ERR_PARSE if the headers were incomplete.
624 *********************************************************************/
625 static jb_err get_server_headers(struct client_state *csp)
627 int continue_hack_in_da_house = 0;
630 while (((header = get_header(csp->iob)) != NULL) || continue_hack_in_da_house)
635 * continue hack in da house. Ignore the ending of
636 * this head and continue enlisting header lines.
637 * The reason is described below.
639 enlist(csp->headers, "");
640 continue_hack_in_da_house = 0;
643 else if (0 == strncmpic(header, "HTTP/1.1 100", 12))
646 * It's a bodyless continue response, don't
647 * stop header parsing after reaching its end.
649 * As a result Privoxy will concatenate the
650 * next response's head and parse and deliver
651 * the headers as if they belonged to one request.
653 * The client will separate them because of the
654 * empty line between them.
656 * XXX: What we're doing here is clearly against
657 * the intended purpose of the continue header,
658 * and under some conditions (HTTP/1.0 client request)
659 * it's a standard violation.
661 * Anyway, "sort of against the spec" is preferable
662 * to "always getting confused by Continue responses"
663 * (Privoxy's behaviour before this hack was added)
665 log_error(LOG_LEVEL_HEADER, "Continue hack in da house.");
666 continue_hack_in_da_house = 1;
668 else if (*header == '\0')
671 * If the header is empty, but the Continue hack
672 * isn't active, we can assume that we reached the
673 * end of the buffer before we hit the end of the
676 * Inform the caller an let it decide how to handle it.
681 if (JB_ERR_MEMORY == enlist(csp->headers, header))
684 * XXX: Should we quit the request and return a
685 * out of memory error page instead?
687 log_error(LOG_LEVEL_ERROR,
688 "Out of memory while enlisting server headers. %s lost.",
698 /*********************************************************************
700 * Function : crunch_reason
702 * Description : Translates the crunch reason code into a string.
705 * 1 : rsp = a http_response
707 * Returns : A string with the crunch reason or an error description.
709 *********************************************************************/
710 static const char *crunch_reason(const struct http_response *rsp)
712 char * reason = NULL;
717 return "Internal error while searching for crunch reason";
720 switch (rsp->crunch_reason)
723 reason = "Unsupported HTTP feature";
729 reason = "Untrusted";
732 reason = "Redirected";
738 reason = "DNS failure";
740 case FORWARDING_FAILED:
741 reason = "Forwarding failed";
744 reason = "Connection failure";
747 reason = "Out of memory (may mask other reasons)";
749 case CONNECTION_TIMEOUT:
750 reason = "Connection timeout";
753 reason = "No server data received";
756 reason = "No reason recorded";
764 /*********************************************************************
766 * Function : log_applied_actions
768 * Description : Logs the applied actions if LOG_LEVEL_ACTIONS is
772 * 1 : actions = Current action spec to log
776 *********************************************************************/
777 static void log_applied_actions(const struct current_action_spec *actions)
780 * The conversion to text requires lots of memory allocations so
781 * we only do the conversion if the user is actually interested.
783 if (debug_level_is_enabled(LOG_LEVEL_ACTIONS))
785 char *actions_as_text = actions_to_line_of_text(actions);
786 log_error(LOG_LEVEL_ACTIONS, "%s", actions_as_text);
787 freez(actions_as_text);
792 /*********************************************************************
794 * Function : send_crunch_response
796 * Description : Delivers already prepared response for
797 * intercepted requests, logs the interception
798 * and frees the response.
801 * 1 : csp = Current client state (buffers, headers, etc...)
802 * 2 : rsp = Fully prepared response. Will be freed on exit.
806 *********************************************************************/
807 static void send_crunch_response(struct client_state *csp, struct http_response *rsp)
809 const struct http_request *http = csp->http;
813 assert(rsp->head != NULL);
817 log_error(LOG_LEVEL_FATAL, "NULL response in send_crunch_response.");
821 * Extract the status code from the actual head
822 * that will be send to the client. It is the only
823 * way to get it right for all requests, including
824 * the fixed ones for out-of-memory problems.
826 * A head starts like this: 'HTTP/1.1 200...'
830 status_code[0] = rsp->head[9];
831 status_code[1] = rsp->head[10];
832 status_code[2] = rsp->head[11];
833 status_code[3] = '\0';
835 /* Log that the request was crunched and why. */
836 log_applied_actions(csp->action);
837 #ifdef FEATURE_HTTPS_INSPECTION
838 if (client_use_ssl(csp))
840 log_error(LOG_LEVEL_CRUNCH, "%s: https://%s%s", crunch_reason(rsp),
841 http->hostport, http->path);
842 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s https://%s%s %s\" %s %lu",
843 csp->ip_addr_str, http->gpc, http->hostport, http->path,
844 http->version, status_code, rsp->content_length);
849 log_error(LOG_LEVEL_CRUNCH, "%s: %s", crunch_reason(rsp), http->url);
850 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" %s %lu",
851 csp->ip_addr_str, http->ocmd, status_code, rsp->content_length);
853 /* Write the answer to the client */
854 #ifdef FEATURE_HTTPS_INSPECTION
855 if (client_use_ssl(csp))
857 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
858 (const unsigned char *)rsp->head, rsp->head_length,
859 get_write_delay(csp)) < 0)
860 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
861 (const unsigned char *)rsp->body, rsp->content_length,
862 get_write_delay(csp)) < 0))
864 /* There is nothing we can do about it. */
865 log_error(LOG_LEVEL_CONNECT, "Couldn't deliver the error message "
866 "for https://%s%s through client socket %d using TLS/SSL",
867 http->hostport, http->url, csp->cfd);
873 if (write_socket_delayed(csp->cfd, rsp->head, rsp->head_length,
874 get_write_delay(csp))
875 || write_socket_delayed(csp->cfd, rsp->body, rsp->content_length,
876 get_write_delay(csp)))
878 /* There is nothing we can do about it. */
879 log_error(LOG_LEVEL_CONNECT,
880 "Couldn't deliver the error message for %s through client socket %d: %E",
881 http->url, csp->cfd);
885 /* Clean up and return */
886 if (cgi_error_memory() != rsp)
888 free_http_response(rsp);
894 /*********************************************************************
896 * Function : crunch_response_triggered
898 * Description : Checks if the request has to be crunched,
899 * and delivers the crunch response if necessary.
902 * 1 : csp = Current client state (buffers, headers, etc...)
903 * 2 : crunchers = list of cruncher functions to run
905 * Returns : TRUE if the request was answered with a crunch response
908 *********************************************************************/
909 static int crunch_response_triggered(struct client_state *csp, const struct cruncher crunchers[])
911 struct http_response *rsp = NULL;
912 const struct cruncher *c;
915 * If CGI request crunching is disabled,
916 * check the CGI dispatcher out of order to
917 * prevent unintentional blocks or redirects.
919 if (!(csp->config->feature_flags & RUNTIME_FEATURE_CGI_CRUNCHING)
920 && (NULL != (rsp = dispatch_cgi(csp))))
922 /* Deliver, log and free the interception response. */
923 send_crunch_response(csp, rsp);
924 csp->flags |= CSP_FLAG_CRUNCHED;
928 for (c = crunchers; c->cruncher != NULL; c++)
931 * Check the cruncher if either Privoxy is toggled
932 * on and the request isn't forced, or if the cruncher
933 * applies to forced requests as well.
935 if (((csp->flags & CSP_FLAG_TOGGLED_ON) &&
936 !(csp->flags & CSP_FLAG_FORCED)) ||
937 (c->flags & CF_IGNORE_FORCE))
939 rsp = c->cruncher(csp);
942 /* Deliver, log and free the interception response. */
943 send_crunch_response(csp, rsp);
944 csp->flags |= CSP_FLAG_CRUNCHED;
945 #ifdef FEATURE_STATISTICS
946 if (c->flags & CF_COUNT_AS_REJECT)
948 csp->flags |= CSP_FLAG_REJECTED;
950 #endif /* def FEATURE_STATISTICS */
961 /*********************************************************************
963 * Function : build_request_line
965 * Description : Builds the HTTP request line.
967 * If a HTTP forwarder is used it expects the whole URL,
968 * web servers only get the path.
971 * 1 : csp = Current client state (buffers, headers, etc...)
972 * 2 : fwd = The forwarding spec used for the request.
974 * 3 : request_line = The old request line which will be replaced.
976 * Returns : Nothing. Terminates in case of memory problems.
978 *********************************************************************/
979 static void build_request_line(struct client_state *csp, const struct forward_spec *fwd, char **request_line)
981 struct http_request *http = csp->http;
984 * Downgrade http version from 1.1 to 1.0
985 * if +downgrade action applies.
987 if ((csp->action->flags & ACTION_DOWNGRADE)
988 && (!strcmpic(http->version, "HTTP/1.1")))
990 freez(http->version);
991 http->version = strdup_or_die("HTTP/1.0");
995 * Rebuild the request line.
997 freez(*request_line);
998 *request_line = strdup(http->gpc);
999 string_append(request_line, " ");
1001 if (fwd != NULL && fwd->forward_host && fwd->type != FORWARD_WEBSERVER)
1003 string_append(request_line, http->url);
1007 string_append(request_line, http->path);
1009 string_append(request_line, " ");
1010 string_append(request_line, http->version);
1012 if (*request_line == NULL)
1014 log_error(LOG_LEVEL_FATAL, "Out of memory writing HTTP command");
1016 log_error(LOG_LEVEL_HEADER, "New HTTP Request-Line: %s", *request_line);
1020 /*********************************************************************
1022 * Function : change_request_destination
1024 * Description : Parse a (rewritten) request line and regenerate
1025 * the http request data.
1028 * 1 : csp = Current client state (buffers, headers, etc...)
1030 * Returns : Forwards the parse_http_request() return code.
1031 * Terminates in case of memory problems.
1033 *********************************************************************/
1034 static jb_err change_request_destination(struct client_state *csp)
1036 struct http_request *http = csp->http;
1039 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
1040 csp->headers->first->str);
1041 free_http_request(http);
1042 err = parse_http_request(csp->headers->first->str, http);
1043 if (JB_ERR_OK != err)
1045 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
1046 jb_err_to_string(err));
1048 if (http->ssl && strcmpic(csp->http->gpc, "CONNECT"))
1051 * A client header filter changed the request URL from
1052 * http:// to https:// which we currently don't support.
1054 log_error(LOG_LEVEL_ERROR, "Changing the request destination from http "
1055 "to https behind the client's back currently isn't supported.");
1056 return JB_ERR_PARSE;
1063 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1064 /*********************************************************************
1066 * Function : server_response_is_complete
1068 * Description : Determines whether we should stop reading
1069 * from the server socket.
1072 * 1 : csp = Current client state (buffers, headers, etc...)
1073 * 2 : content_length = Length of content received so far.
1075 * Returns : TRUE if the response is complete,
1078 *********************************************************************/
1079 static int server_response_is_complete(struct client_state *csp,
1080 unsigned long long content_length)
1082 int content_length_known = !!(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET);
1084 if (!strcmpic(csp->http->gpc, "HEAD"))
1087 * "HEAD" implies no body, we are thus expecting
1088 * no content. XXX: incomplete "list" of methods?
1090 csp->expected_content_length = 0;
1091 content_length_known = TRUE;
1092 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1095 if (csp->http->status == 204 || csp->http->status == 304)
1098 * Expect no body. XXX: incomplete "list" of status codes?
1100 csp->expected_content_length = 0;
1101 content_length_known = TRUE;
1102 csp->flags |= CSP_FLAG_SERVER_CONTENT_LENGTH_SET;
1105 return (content_length_known && ((0 == csp->expected_content_length)
1106 || (csp->expected_content_length <= content_length)));
1110 #ifdef FEATURE_CONNECTION_SHARING
1111 /*********************************************************************
1113 * Function : wait_for_alive_connections
1115 * Description : Waits for alive connections to timeout.
1121 *********************************************************************/
1122 static void wait_for_alive_connections(void)
1124 int connections_alive = close_unusable_connections();
1126 while (0 < connections_alive)
1128 log_error(LOG_LEVEL_CONNECT,
1129 "Waiting for %d connections to timeout.",
1132 connections_alive = close_unusable_connections();
1135 log_error(LOG_LEVEL_CONNECT, "No connections to wait for left.");
1138 #endif /* def FEATURE_CONNECTION_SHARING */
1141 /*********************************************************************
1143 * Function : save_connection_destination
1145 * Description : Remembers a connection for reuse later on.
1148 * 1 : sfd = Open socket to remember.
1149 * 2 : http = The destination for the connection.
1150 * 3 : fwd = The forwarder settings used.
1151 * 4 : server_connection = storage.
1155 *********************************************************************/
1156 void save_connection_destination(jb_socket sfd,
1157 const struct http_request *http,
1158 const struct forward_spec *fwd,
1159 struct reusable_connection *server_connection)
1161 assert(sfd != JB_INVALID_SOCKET);
1162 assert(NULL != http->host);
1164 server_connection->sfd = sfd;
1165 server_connection->host = strdup_or_die(http->host);
1166 server_connection->port = http->port;
1168 assert(NULL != fwd);
1169 assert(server_connection->gateway_host == NULL);
1170 assert(server_connection->gateway_port == 0);
1171 assert(server_connection->forwarder_type == 0);
1172 assert(server_connection->forward_host == NULL);
1173 assert(server_connection->forward_port == 0);
1175 server_connection->forwarder_type = fwd->type;
1176 if (NULL != fwd->gateway_host)
1178 server_connection->gateway_host = strdup_or_die(fwd->gateway_host);
1182 server_connection->gateway_host = NULL;
1184 server_connection->gateway_port = fwd->gateway_port;
1185 if (NULL != fwd->auth_username)
1187 server_connection->auth_username = strdup_or_die(fwd->auth_username);
1191 server_connection->auth_username = NULL;
1193 if (NULL != fwd->auth_password)
1195 server_connection->auth_password = strdup_or_die(fwd->auth_password);
1199 server_connection->auth_password = NULL;
1202 if (NULL != fwd->forward_host)
1204 server_connection->forward_host = strdup_or_die(fwd->forward_host);
1208 server_connection->forward_host = NULL;
1210 server_connection->forward_port = fwd->forward_port;
1212 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
1215 /*********************************************************************
1217 * Function : verify_request_length
1219 * Description : Checks if we already got the whole client requests
1220 * and sets CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ if
1223 * Data that doesn't belong to the current request is
1224 * either thrown away to let the client retry on a clean
1225 * socket, or stashed to be dealt with after the current
1226 * request is served.
1229 * 1 : csp = Current client state (buffers, headers, etc...)
1233 *********************************************************************/
1234 static void verify_request_length(struct client_state *csp)
1236 unsigned long long buffered_request_bytes =
1237 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1239 if ((csp->expected_client_content_length != 0)
1240 && (buffered_request_bytes != 0))
1242 if (csp->expected_client_content_length >= buffered_request_bytes)
1244 csp->expected_client_content_length -= buffered_request_bytes;
1245 log_error(LOG_LEVEL_CONNECT, "Reduced expected bytes to %llu "
1246 "to account for the %llu ones we already got.",
1247 csp->expected_client_content_length, buffered_request_bytes);
1251 assert(csp->client_iob->eod > csp->client_iob->cur + csp->expected_client_content_length);
1252 csp->client_iob->eod = csp->client_iob->cur + csp->expected_client_content_length;
1253 log_error(LOG_LEVEL_CONNECT, "Reducing expected bytes to 0. "
1254 "Marking the server socket tainted after throwing %llu bytes away.",
1255 buffered_request_bytes - csp->expected_client_content_length);
1256 csp->expected_client_content_length = 0;
1257 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1260 if (csp->expected_client_content_length == 0)
1262 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1266 if (!(csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ)
1267 && ((csp->client_iob->cur < csp->client_iob->eod)
1268 || (csp->expected_client_content_length != 0)))
1270 if (strcmpic(csp->http->gpc, "GET")
1271 && strcmpic(csp->http->gpc, "HEAD")
1272 && strcmpic(csp->http->gpc, "TRACE")
1273 && strcmpic(csp->http->gpc, "OPTIONS")
1274 && strcmpic(csp->http->gpc, "DELETE"))
1276 /* XXX: this is an incomplete hack */
1277 csp->flags &= ~CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1278 log_error(LOG_LEVEL_CONNECT, "There better be a request body.");
1282 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1284 if ((csp->config->feature_flags & RUNTIME_FEATURE_TOLERATE_PIPELINING) == 0)
1286 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1287 log_error(LOG_LEVEL_CONNECT,
1288 "Possible pipeline attempt detected. The connection will not "
1289 "be kept alive and we will only serve the first request.");
1290 /* Nuke the pipelined requests from orbit, just to be sure. */
1291 clear_iob(csp->client_iob);
1296 * Keep the pipelined data around for now, we'll deal with
1297 * it once we're done serving the current request.
1299 csp->flags |= CSP_FLAG_PIPELINED_REQUEST_WAITING;
1300 assert(csp->client_iob->eod >= csp->client_iob->cur);
1301 log_error(LOG_LEVEL_CONNECT, "Complete client request followed by "
1302 "%d bytes of pipelined data received.",
1303 (int)(csp->client_iob->eod - csp->client_iob->cur));
1309 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
1310 log_error(LOG_LEVEL_CONNECT, "Complete client request received.");
1315 /*********************************************************************
1317 * Function : mark_server_socket_tainted
1319 * Description : Makes sure we don't reuse a server socket
1320 * (if we didn't read everything the server sent
1321 * us reusing the socket would lead to garbage).
1324 * 1 : csp = Current client state (buffers, headers, etc...)
1328 *********************************************************************/
1329 static void mark_server_socket_tainted(struct client_state *csp)
1332 * For consistency we always mark the server socket
1333 * tainted, however, to reduce the log noise we only
1334 * emit a log message if the server socket could have
1335 * actually been reused.
1337 if ((csp->flags & CSP_FLAG_SERVER_CONNECTION_KEEP_ALIVE)
1338 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
1340 log_error(LOG_LEVEL_CONNECT,
1341 "Marking the server socket %d tainted.",
1342 csp->server_connection.sfd);
1344 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1347 /*********************************************************************
1349 * Function : get_request_line
1351 * Description : Read the client request line.
1354 * 1 : csp = Current client state (buffers, headers, etc...)
1356 * Returns : Pointer to request line or NULL in case of errors.
1358 *********************************************************************/
1359 static char *get_request_line(struct client_state *csp)
1361 char buf[BUFFER_SIZE];
1362 char *request_line = NULL;
1365 memset(buf, 0, sizeof(buf));
1367 if ((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) != 0)
1370 * If there are multiple pipelined requests waiting,
1371 * the flag will be set again once the next request
1374 csp->flags &= ~CSP_FLAG_PIPELINED_REQUEST_WAITING;
1376 request_line = get_header(csp->client_iob);
1377 if ((NULL != request_line) && ('\0' != *request_line))
1379 return request_line;
1383 log_error(LOG_LEVEL_CONNECT, "No complete request line "
1384 "received yet. Continuing reading from %d.", csp->cfd);
1392 0 == (csp->flags & CSP_FLAG_FUZZED_INPUT) &&
1394 !data_is_available(csp->cfd, csp->config->socket_timeout)
1397 if (socket_is_still_alive(csp->cfd))
1399 log_error(LOG_LEVEL_CONNECT,
1400 "No request line on socket %d received in time. Timeout: %d.",
1401 csp->cfd, csp->config->socket_timeout);
1402 write_socket_delayed(csp->cfd, CLIENT_CONNECTION_TIMEOUT_RESPONSE,
1403 strlen(CLIENT_CONNECTION_TIMEOUT_RESPONSE),
1404 get_write_delay(csp));
1408 log_error(LOG_LEVEL_CONNECT,
1409 "The client side of the connection on socket %d got "
1410 "closed without sending a complete request line.", csp->cfd);
1415 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1417 if (len <= 0) return NULL;
1420 * If there is no memory left for buffering the
1421 * request, there is nothing we can do but hang up
1423 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1428 request_line = get_header(csp->client_iob);
1430 } while ((NULL != request_line) && ('\0' == *request_line));
1432 return request_line;
1438 CHUNK_STATUS_MISSING_DATA,
1439 CHUNK_STATUS_BODY_COMPLETE,
1440 CHUNK_STATUS_PARSE_ERROR
1444 /*********************************************************************
1446 * Function : chunked_body_is_complete
1448 * Description : Figures out whether or not a chunked body is complete.
1450 * Currently it always starts at the beginning of the
1451 * buffer which is somewhat wasteful and prevents Privoxy
1452 * from starting to forward the correctly parsed chunks
1453 * as soon as theoretically possible.
1455 * Should be modified to work with a common buffer,
1456 * and allow the caller to skip already parsed chunks.
1458 * This would allow the function to be used for unbuffered
1459 * response bodies as well.
1462 * 1 : iob = Buffer with the body to check.
1463 * 2 : length = Length of complete body
1465 * Returns : Enum with the result of the check.
1467 *********************************************************************/
1468 static enum chunk_status chunked_body_is_complete(struct iob *iob, size_t *length)
1470 unsigned int chunksize;
1476 * We need at least a single digit, followed by "\r\n",
1477 * followed by an unknown amount of data, followed by "\r\n".
1479 if (p + 5 > iob->eod)
1481 return CHUNK_STATUS_MISSING_DATA;
1483 if (sscanf(p, "%x", &chunksize) != 1)
1485 return CHUNK_STATUS_PARSE_ERROR;
1489 * We want at least a single digit, followed by "\r\n",
1490 * followed by the specified amount of data, followed by "\r\n".
1492 if (p + chunksize + 5 > iob->eod)
1494 return CHUNK_STATUS_MISSING_DATA;
1497 /* Skip chunk-size. */
1498 p = strstr(p, "\r\n");
1501 return CHUNK_STATUS_PARSE_ERROR;
1503 /* Move beyond the chunkdata. */
1506 /* There should be another "\r\n" to skip */
1507 if (memcmp(p, "\r\n", 2))
1509 return CHUNK_STATUS_PARSE_ERROR;
1512 } while (chunksize > 0U);
1514 *length = (size_t)(p - iob->cur);
1515 assert(*length <= (size_t)(iob->eod - iob->cur));
1516 assert(p <= iob->eod);
1518 return CHUNK_STATUS_BODY_COMPLETE;
1523 /*********************************************************************
1525 * Function : receive_chunked_client_request_body
1527 * Description : Read the chunk-encoded client request body.
1528 * Failures are dealt with.
1531 * 1 : csp = Current client state (buffers, headers, etc...)
1533 * Returns : JB_ERR_OK or JB_ERR_PARSE
1535 *********************************************************************/
1536 static jb_err receive_chunked_client_request_body(struct client_state *csp)
1539 enum chunk_status status;
1541 while (CHUNK_STATUS_MISSING_DATA ==
1542 (status = chunked_body_is_complete(csp->client_iob, &body_length)))
1544 char buf[BUFFER_SIZE];
1547 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1549 log_error(LOG_LEVEL_ERROR,
1550 "Timeout while waiting for the client body.");
1553 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1556 log_error(LOG_LEVEL_ERROR, "Read the client body failed: %E");
1559 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1564 if (status != CHUNK_STATUS_BODY_COMPLETE)
1566 write_socket_delayed(csp->cfd, CLIENT_BODY_PARSE_ERROR_RESPONSE,
1567 strlen(CLIENT_BODY_PARSE_ERROR_RESPONSE), get_write_delay(csp));
1568 log_error(LOG_LEVEL_CLF,
1569 "%s - - [%T] \"Failed reading chunked client body\" 400 0", csp->ip_addr_str);
1570 return JB_ERR_PARSE;
1572 log_error(LOG_LEVEL_CONNECT,
1573 "Chunked client body completely read. Length: %lu", body_length);
1574 csp->expected_client_content_length = body_length;
1582 /*********************************************************************
1584 * Function : fuzz_chunked_transfer_encoding
1586 * Description : Treat the fuzzed input as chunked transfer encoding
1587 * to check and dechunk.
1590 * 1 : csp = Used to store the data.
1591 * 2 : fuzz_input_file = File to read the input from.
1593 * Returns : Result of dechunking
1595 *********************************************************************/
1596 extern int fuzz_chunked_transfer_encoding(struct client_state *csp, char *fuzz_input_file)
1599 size_t size = (size_t)(csp->iob->eod - csp->iob->cur);
1600 enum chunk_status status;
1602 status = chunked_body_is_complete(csp->iob, &length);
1603 if (CHUNK_STATUS_BODY_COMPLETE != status)
1605 log_error(LOG_LEVEL_INFO, "Chunked body is incomplete or invalid");
1608 return (JB_ERR_OK == remove_chunked_transfer_coding(csp->iob->cur, &size));
1613 /*********************************************************************
1615 * Function : fuzz_client_request
1617 * Description : Try to get a client request from the fuzzed input.
1620 * 1 : csp = Current client state (buffers, headers, etc...)
1621 * 2 : fuzz_input_file = File to read the input from.
1623 * Returns : Result of fuzzing.
1625 *********************************************************************/
1626 extern int fuzz_client_request(struct client_state *csp, char *fuzz_input_file)
1631 csp->ip_addr_str = "fuzzer";
1633 if (strcmp(fuzz_input_file, "-") != 0)
1635 log_error(LOG_LEVEL_FATAL,
1636 "Fuzzed client requests can currently only be read from stdin (-).");
1638 err = receive_client_request(csp);
1639 if (err != JB_ERR_OK)
1643 err = parse_client_request(csp);
1644 if (err != JB_ERR_OK)
1652 #endif /* def FUZZ */
1655 #ifdef FEATURE_FORCE_LOAD
1656 /*********************************************************************
1658 * Function : force_required
1660 * Description : Checks a request line to see if it contains
1661 * the FORCE_PREFIX. If it does, it is removed
1662 * unless enforcing requests has beend disabled.
1665 * 1 : request_line = HTTP request line
1667 * Returns : TRUE if force is required, FALSE otherwise.
1669 *********************************************************************/
1670 static int force_required(const struct client_state *csp, char *request_line)
1674 p = strstr(request_line, "http://");
1678 p += strlen("http://");
1682 /* Intercepted request usually don't specify the protocol. */
1686 /* Go to the beginning of the path */
1691 * If the path is missing the request line is invalid and we
1692 * are done here. The client-visible rejection happens later on.
1697 if (0 == strncmpic(p, FORCE_PREFIX, strlen(FORCE_PREFIX) - 1))
1699 if (!(csp->config->feature_flags & RUNTIME_FEATURE_ENFORCE_BLOCKS))
1701 /* XXX: Should clean more carefully */
1702 strclean(request_line, FORCE_PREFIX);
1703 log_error(LOG_LEVEL_FORCE,
1704 "Enforcing request: \"%s\".", request_line);
1708 log_error(LOG_LEVEL_FORCE,
1709 "Ignored force prefix in request: \"%s\".", request_line);
1715 #endif /* def FEATURE_FORCE_LOAD */
1718 /*********************************************************************
1720 * Function : receive_client_request
1722 * Description : Read the client's request (more precisely the
1723 * client headers) and answer it if necessary.
1726 * 1 : csp = Current client state (buffers, headers, etc...)
1728 * Returns : JB_ERR_OK, JB_ERR_PARSE or JB_ERR_MEMORY
1730 *********************************************************************/
1731 static jb_err receive_client_request(struct client_state *csp)
1733 char buf[BUFFER_SIZE];
1736 struct http_request *http;
1740 /* Temporary copy of the client's headers before they get enlisted in csp->headers */
1741 struct list header_list;
1742 struct list *headers = &header_list;
1744 /* We don't care if the arriving data is a valid HTTP request or not. */
1745 csp->requests_received_total++;
1749 memset(buf, 0, sizeof(buf));
1751 req = get_request_line(csp);
1754 mark_server_socket_tainted(csp);
1755 return JB_ERR_PARSE;
1757 assert(*req != '\0');
1759 if (client_protocol_is_unsupported(csp, req))
1761 return JB_ERR_PARSE;
1764 #ifdef FEATURE_FORCE_LOAD
1765 if (force_required(csp, req))
1767 csp->flags |= CSP_FLAG_FORCED;
1769 #endif /* def FEATURE_FORCE_LOAD */
1771 err = parse_http_request(req, http);
1773 if (JB_ERR_OK != err)
1775 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER),
1776 get_write_delay(csp));
1777 /* XXX: Use correct size */
1778 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
1779 log_error(LOG_LEVEL_ERROR,
1780 "Couldn't parse request line received from %s: %s",
1781 csp->ip_addr_str, jb_err_to_string(err));
1783 free_http_request(http);
1784 return JB_ERR_PARSE;
1787 /* grab the rest of the client's headers */
1791 p = get_header(csp->client_iob);
1795 /* There are no additional headers to read. */
1802 * We didn't receive a complete header
1803 * line yet, get the rest of it.
1805 if (!data_is_available(csp->cfd, csp->config->socket_timeout))
1807 log_error(LOG_LEVEL_ERROR,
1808 "Stopped grabbing the client headers.");
1809 destroy_list(headers);
1810 return JB_ERR_PARSE;
1813 len = read_socket(csp->cfd, buf, sizeof(buf) - 1);
1816 log_error(LOG_LEVEL_ERROR, "read from client failed: %E");
1817 destroy_list(headers);
1818 return JB_ERR_PARSE;
1821 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
1824 * If there is no memory left for buffering the
1825 * request, there is nothing we can do but hang up
1827 destroy_list(headers);
1828 return JB_ERR_MEMORY;
1833 if (!strncmpic(p, "Transfer-Encoding:", 18))
1836 * XXX: should be called through sed()
1837 * but currently can't.
1839 client_transfer_encoding(csp, &p);
1842 * We were able to read a complete
1843 * header and can finally enlist it.
1850 if (http->host == NULL)
1853 * If we still don't know the request destination,
1854 * the request is invalid or the client uses
1855 * Privoxy without its knowledge.
1857 if (JB_ERR_OK != get_request_destination_elsewhere(csp, headers))
1860 * Our attempts to get the request destination
1861 * elsewhere failed or Privoxy is configured
1862 * to only accept proxy requests.
1864 * An error response has already been sent
1865 * and we're done here.
1867 return JB_ERR_PARSE;
1871 #ifdef FEATURE_CLIENT_TAGS
1872 /* XXX: If the headers were enlisted sooner, passing csp would do. */
1873 set_client_address(csp, headers);
1874 get_tag_list_for_client(csp->client_tags, csp->client_address);
1878 * Determine the actions for this URL
1880 #ifdef FEATURE_TOGGLE
1881 if (!(csp->flags & CSP_FLAG_TOGGLED_ON))
1883 /* Most compatible set of actions (i.e. none) */
1884 init_current_action(csp->action);
1887 #endif /* ndef FEATURE_TOGGLE */
1889 get_url_actions(csp, http);
1892 enlist(csp->headers, http->cmd);
1894 /* Append the previously read headers */
1895 err = list_append_list_unique(csp->headers, headers);
1896 destroy_list(headers);
1903 /*********************************************************************
1905 * Function : parse_client_request
1907 * Description : Parses the client's request and decides what to do
1910 * Note that since we're not using select() we could get
1911 * blocked here if a client connected, then didn't say
1915 * 1 : csp = Current client state (buffers, headers, etc...)
1917 * Returns : JB_ERR_OK or JB_ERR_PARSE
1919 *********************************************************************/
1920 static jb_err parse_client_request(struct client_state *csp)
1922 struct http_request *http = csp->http;
1925 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
1926 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
1927 && (!strcmpic(csp->http->version, "HTTP/1.1"))
1928 && (csp->http->ssl == 0))
1930 /* Assume persistence until further notice */
1931 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
1933 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
1935 if (csp->http->ssl == 0)
1938 * This whole block belongs to chat() but currently
1939 * has to be executed before sed().
1941 if (csp->flags & CSP_FLAG_CHUNKED_CLIENT_BODY)
1943 if (receive_chunked_client_request_body(csp) != JB_ERR_OK)
1945 return JB_ERR_PARSE;
1950 csp->expected_client_content_length = get_expected_content_length(csp->headers);
1952 verify_request_length(csp);
1954 #ifndef FEATURE_HTTPS_INSPECTION
1957 csp->flags |= CSP_FLAG_SERVER_SOCKET_TAINTED;
1961 err = sed(csp, FILTER_CLIENT_HEADERS);
1962 if (JB_ERR_OK != err)
1964 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
1966 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
1967 csp->ip_addr_str, csp->http->cmd);
1968 write_socket_delayed(csp->cfd, CHEADER, strlen(CHEADER), get_write_delay(csp));
1969 return JB_ERR_PARSE;
1971 csp->flags |= CSP_FLAG_CLIENT_HEADER_PARSING_DONE;
1973 /* Check request line for rewrites. */
1974 if ((NULL == csp->headers->first->str)
1975 || (strcmp(http->cmd, csp->headers->first->str) &&
1976 (JB_ERR_OK != change_request_destination(csp))))
1979 * A header filter broke the request line - bail out.
1981 write_socket_delayed(csp->cfd, MESSED_UP_REQUEST_RESPONSE,
1982 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
1983 /* XXX: Use correct size */
1984 log_error(LOG_LEVEL_CLF,
1985 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
1986 log_error(LOG_LEVEL_ERROR,
1987 "Invalid request line after applying header filters.");
1988 free_http_request(http);
1990 return JB_ERR_PARSE;
1993 if (client_has_unsupported_expectations(csp))
1995 return JB_ERR_PARSE;
2003 /*********************************************************************
2005 * Function : read_http_request_body
2007 * Description : Reads remaining request body from the client.
2010 * 1 : csp = Current client state (buffers, headers, etc...)
2012 * Returns : 0 on success, anything else is an error.
2014 *********************************************************************/
2015 static int read_http_request_body(struct client_state *csp)
2017 size_t to_read = csp->expected_client_content_length;
2020 assert(to_read != 0);
2022 /* check if all data has been already read */
2023 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2028 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2029 to_read > 0 && data_is_available(csp->cfd, csp->config->socket_timeout);
2030 to_read -= (unsigned)len)
2032 char buf[BUFFER_SIZE];
2033 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2035 log_error(LOG_LEVEL_CONNECT,
2036 "Waiting for up to %d bytes of request body from the client.",
2038 len = read_socket(csp->cfd, buf, (int)max_bytes_to_read);
2041 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s: %E", csp->ip_addr_str);
2044 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2048 assert(to_read >= len);
2053 log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %d more bytes",
2054 csp->expected_client_content_length);
2057 log_error(LOG_LEVEL_CONNECT, "The last %d bytes of the request body have been read",
2058 csp->expected_client_content_length);
2063 /*********************************************************************
2065 * Function : update_client_headers
2067 * Description : Updates the HTTP headers from the client request.
2070 * 1 : csp = Current client state (buffers, headers, etc...)
2071 * 2 : new_content_length = new content length value to set
2073 * Returns : 0 on success, anything else is an error.
2075 *********************************************************************/
2076 static int update_client_headers(struct client_state *csp, size_t new_content_length)
2078 static const char content_length[] = "Content-Length:";
2080 struct list_entry *p;
2082 #ifndef FEATURE_HTTPS_INSPECTION
2083 for (p = csp->headers->first;
2085 for (p = csp->http->client_ssl ? csp->https_headers->first : csp->headers->first;
2087 !updated && (p != NULL); p = p->next)
2089 /* Header crunch()ed in previous run? -> ignore */
2095 /* Does the current parser handle this header? */
2096 if (0 == strncmpic(p->str, content_length, sizeof(content_length) - 1))
2098 updated = (JB_ERR_OK == header_adjust_content_length((char **)&(p->str), new_content_length));
2110 /*********************************************************************
2112 * Function : can_filter_request_body
2114 * Description : Checks if the current request body can be stored in
2115 * the client_iob without hitting buffer limit.
2118 * 1 : csp = Current client state (buffers, headers, etc...)
2120 * Returns : TRUE if the current request size do not exceed buffer limit
2123 *********************************************************************/
2124 static int can_filter_request_body(const struct client_state *csp)
2126 if (!can_add_to_iob(csp->client_iob, csp->config->buffer_limit,
2127 csp->expected_client_content_length))
2129 log_error(LOG_LEVEL_INFO,
2130 "Not filtering request body from %s: buffer limit %d will be exceeded "
2131 "(content length %d)", csp->ip_addr_str, csp->config->buffer_limit,
2132 csp->expected_client_content_length);
2139 /*********************************************************************
2141 * Function : send_http_request
2143 * Description : Sends the HTTP headers from the client request
2144 * and all the body data that has already been received.
2147 * 1 : csp = Current client state (buffers, headers, etc...)
2149 * Returns : 0 on success, anything else is an error.
2151 *********************************************************************/
2152 static int send_http_request(struct client_state *csp)
2156 const char *to_send;
2158 int filter_client_body = csp->expected_client_content_length != 0 &&
2159 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2161 if (filter_client_body)
2163 if (read_http_request_body(csp))
2167 to_send_len = csp->expected_client_content_length;
2168 to_send = execute_client_body_filters(csp, &to_send_len);
2169 if (to_send == NULL)
2171 /* just flush client_iob */
2172 filter_client_body = FALSE;
2174 else if (to_send_len != csp->expected_client_content_length &&
2175 update_client_headers(csp, to_send_len))
2177 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2180 csp->expected_client_content_length = 0;
2183 hdr = list_to_text(csp->headers);
2186 /* FIXME Should handle error properly */
2187 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2189 list_remove_all(csp->headers);
2192 * Write the client's (modified) header to the server
2193 * (along with anything else that may be in the buffer)
2195 write_failure = 0 != write_socket(csp->server_connection.sfd, hdr, strlen(hdr));
2200 log_error(LOG_LEVEL_CONNECT, "Failed sending request headers to: %s: %E",
2201 csp->http->hostport);
2205 if (filter_client_body)
2207 write_failure = 0 != write_socket(csp->server_connection.sfd, to_send, to_send_len);
2211 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s: %E",
2212 csp->http->hostport);
2217 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2218 && (flush_iob(csp->server_connection.sfd, csp->client_iob, 0) < 0))
2220 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2221 csp->http->hostport);
2228 #ifdef FEATURE_HTTPS_INSPECTION
2229 /*********************************************************************
2231 * Function : read_https_request_body
2233 * Description : Reads remaining request body from the client.
2236 * 1 : csp = Current client state (buffers, headers, etc...)
2238 * Returns : 0 on success, anything else is an error.
2240 *********************************************************************/
2241 static int read_https_request_body(struct client_state *csp)
2243 size_t to_read = csp->expected_client_content_length;
2246 assert(to_read != 0);
2248 /* check if all data has been already read */
2249 if (to_read <= (csp->client_iob->eod - csp->client_iob->cur))
2254 for (to_read -= (size_t)(csp->client_iob->eod - csp->client_iob->cur);
2255 to_read > 0 && (is_ssl_pending(&(csp->ssl_client_attr)) ||
2256 data_is_available(csp->cfd, csp->config->socket_timeout));
2257 to_read -= (unsigned)len)
2259 unsigned char buf[BUFFER_SIZE];
2260 size_t max_bytes_to_read = to_read < sizeof(buf) ? to_read : sizeof(buf);
2262 log_error(LOG_LEVEL_CONNECT,
2263 "Waiting for up to %d bytes of request body from the client.",
2265 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2266 (unsigned)max_bytes_to_read);
2269 log_error(LOG_LEVEL_CONNECT, "Failed receiving request body from %s", csp->ip_addr_str);
2272 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, (char *)buf, len))
2276 assert(to_read >= len);
2281 log_error(LOG_LEVEL_CONNECT, "Not enough request body has been read: expected %d more bytes", to_read);
2285 log_error(LOG_LEVEL_CONNECT, "The last %d bytes of the request body have been read",
2286 csp->expected_client_content_length);
2291 /*********************************************************************
2293 * Function : receive_and_send_encrypted_post_data
2295 * Description : Reads remaining request body from the client and sends
2299 * 1 : csp = Current client state (buffers, headers, etc...)
2301 * Returns : 0 on success, anything else is an error.
2303 *********************************************************************/
2304 static int receive_and_send_encrypted_post_data(struct client_state *csp)
2306 int content_length_known = csp->expected_client_content_length != 0;
2308 while (is_ssl_pending(&(csp->ssl_client_attr))
2309 || (content_length_known && csp->expected_client_content_length != 0))
2311 unsigned char buf[BUFFER_SIZE];
2313 int max_bytes_to_read = sizeof(buf);
2315 if (content_length_known && csp->expected_client_content_length < sizeof(buf))
2317 max_bytes_to_read = (int)csp->expected_client_content_length;
2319 log_error(LOG_LEVEL_CONNECT,
2320 "Waiting for up to %d bytes of request body from the client.",
2322 len = ssl_recv_data(&(csp->ssl_client_attr), buf,
2323 (unsigned)max_bytes_to_read);
2330 /* XXX: Does this actually happen? */
2333 log_error(LOG_LEVEL_CONNECT, "Forwarding %d bytes of encrypted request body",
2335 len = ssl_send_data(&(csp->ssl_server_attr), buf, (size_t)len);
2340 if (csp->expected_client_content_length != 0)
2342 if (csp->expected_client_content_length >= len)
2344 csp->expected_client_content_length -= (unsigned)len;
2346 if (csp->expected_client_content_length == 0)
2348 log_error(LOG_LEVEL_CONNECT, "Forwarded the last %d bytes", len);
2354 log_error(LOG_LEVEL_CONNECT, "Done forwarding encrypted request body");
2361 /*********************************************************************
2363 * Function : send_https_request
2365 * Description : Sends the HTTP headers from the client request
2366 * and all the body data that has already been received.
2369 * 1 : csp = Current client state (buffers, headers, etc...)
2371 * Returns : 0 on success, anything else is an error.
2373 *********************************************************************/
2374 static int send_https_request(struct client_state *csp)
2379 const char *to_send;
2381 int filter_client_body = csp->expected_client_content_length != 0 &&
2382 client_body_filters_enabled(csp->action) && can_filter_request_body(csp);
2384 if (filter_client_body)
2386 if (read_https_request_body(csp))
2390 to_send_len = csp->expected_client_content_length;
2391 to_send = execute_client_body_filters(csp, &to_send_len);
2392 if (to_send == NULL)
2394 /* just flush client_iob */
2395 filter_client_body = FALSE;
2397 else if (to_send_len != csp->expected_client_content_length &&
2398 update_client_headers(csp, to_send_len))
2400 log_error(LOG_LEVEL_HEADER, "Error updating client headers");
2403 csp->expected_client_content_length = 0;
2406 hdr = list_to_text(csp->https_headers);
2409 /* FIXME Should handle error properly */
2410 log_error(LOG_LEVEL_FATAL, "Out of memory parsing client header");
2412 list_remove_all(csp->https_headers);
2415 * Write the client's (modified) header to the server
2416 * (along with anything else that may be in the buffer)
2418 ret = ssl_send_data(&(csp->ssl_server_attr),
2419 (const unsigned char *)hdr, strlen(hdr));
2424 log_error(LOG_LEVEL_CONNECT,
2425 "Failed sending encrypted request headers to: %s: %E",
2426 csp->http->hostport);
2427 mark_server_socket_tainted(csp);
2431 if (filter_client_body)
2433 ret = ssl_send_data(&(csp->ssl_server_attr), (const unsigned char *)to_send, to_send_len);
2437 log_error(LOG_LEVEL_CONNECT, "Failed sending filtered request body to: %s",
2438 csp->http->hostport);
2443 if (((csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING) == 0)
2444 && ((flushed = ssl_flush_socket(&(csp->ssl_server_attr),
2445 csp->client_iob)) < 0))
2447 log_error(LOG_LEVEL_CONNECT, "Failed sending request body to: %s: %E",
2448 csp->http->hostport);
2451 if (flushed != 0 || csp->expected_client_content_length != 0)
2453 if (csp->expected_client_content_length != 0)
2455 if (csp->expected_client_content_length < flushed)
2457 log_error(LOG_LEVEL_ERROR,
2458 "Flushed %ld bytes of request body while only expecting %llu",
2459 flushed, csp->expected_client_content_length);
2460 csp->expected_client_content_length = 0;
2464 log_error(LOG_LEVEL_CONNECT,
2465 "Flushed %ld bytes of request body while expecting %llu",
2466 flushed, csp->expected_client_content_length);
2467 csp->expected_client_content_length -= (unsigned)flushed;
2468 if (receive_and_send_encrypted_post_data(csp))
2476 log_error(LOG_LEVEL_CONNECT,
2477 "Flushed %ld bytes of request body", flushed);
2481 log_error(LOG_LEVEL_CONNECT, "Encrypted request sent");
2488 /*********************************************************************
2490 * Function : receive_encrypted_request
2492 * Description : Receives an encrypted request.
2495 * 1 : csp = Current client state (buffers, headers, etc...)
2497 * Returns : JB_ERR_OK on success,
2498 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2500 *********************************************************************/
2501 static jb_err receive_encrypted_request(struct client_state *csp)
2503 char buf[BUFFER_SIZE];
2509 log_error(LOG_LEVEL_HEADER, "Reading encrypted headers");
2510 if (!is_ssl_pending(&(csp->ssl_client_attr)) &&
2511 !data_is_available(csp->cfd, csp->config->socket_timeout))
2513 log_error(LOG_LEVEL_CONNECT,
2514 "Socket %d timed out while waiting for client headers", csp->cfd);
2515 return JB_ERR_PARSE;
2517 len = ssl_recv_data(&(csp->ssl_client_attr),
2518 (unsigned char *)buf, sizeof(buf));
2521 log_error(LOG_LEVEL_CONNECT,
2522 "Socket %d closed while waiting for client headers", csp->cfd);
2523 return JB_ERR_PARSE;
2527 return JB_ERR_PARSE;
2529 if (add_to_iob(csp->client_iob, csp->config->buffer_limit, buf, len))
2531 return JB_ERR_MEMORY;
2533 p = strstr(csp->client_iob->cur, "\r\n\r\n");
2534 } while (p == NULL);
2536 log_error(LOG_LEVEL_HEADER, "Encrypted headers received completely");
2542 /*********************************************************************
2544 * Function : change_encrypted_request_destination
2546 * Description : Parse a (rewritten) request line from an encrypted
2547 * request and regenerate the http request data.
2550 * 1 : csp = Current client state (buffers, headers, etc...)
2552 * Returns : Forwards the parse_http_request() return code.
2553 * Terminates in case of memory problems.
2555 *********************************************************************/
2556 static jb_err change_encrypted_request_destination(struct client_state *csp)
2559 char *original_host = csp->http->host;
2560 int original_port = csp->http->port;
2562 log_error(LOG_LEVEL_REDIRECTS, "Rewrite detected: %s",
2563 csp->https_headers->first->str);
2564 csp->http->host = NULL;
2565 free_http_request(csp->http);
2566 err = parse_http_request(csp->https_headers->first->str, csp->http);
2567 if (JB_ERR_OK != err)
2569 log_error(LOG_LEVEL_ERROR, "Couldn't parse rewritten request: %s.",
2570 jb_err_to_string(err));
2571 freez(original_host);
2575 if (csp->http->host == NULL)
2577 char port_string[10];
2579 * The rewritten request line did not specify a host
2580 * which means we can use the original host specified
2583 csp->http->host = original_host;
2584 csp->http->port = original_port;
2585 log_error(LOG_LEVEL_REDIRECTS, "Keeping the original host: %s",
2588 * If the rewritten request line didn't contain a host
2589 * it also didn't contain a port so we can reuse the host
2592 freez(csp->http->hostport);
2593 csp->http->hostport = strdup_or_die(csp->http->host);
2594 snprintf(port_string, sizeof(port_string), ":%d", original_port);
2595 err = string_append(&csp->http->hostport, port_string);
2596 if (err != JB_ERR_OK)
2598 log_error(LOG_LEVEL_ERROR, "Failed to rebuild hostport: %s.",
2599 jb_err_to_string(err));
2604 * While the request line didn't mention it,
2605 * we're https-inspecting and want to speak TLS
2608 csp->http->server_ssl = 1;
2613 /* The rewrite filter added a host so we can ditch the original */
2614 freez(original_host);
2615 csp->http->server_ssl = csp->http->ssl;
2618 csp->http->client_ssl = 1;
2620 freez(csp->https_headers->first->str);
2621 build_request_line(csp, NULL, &csp->https_headers->first->str);
2623 if (!server_use_ssl(csp))
2625 log_error(LOG_LEVEL_REDIRECTS,
2626 "Rewritten request line results in downgrade to http");
2628 * Replace the unencryptd headers received with the
2629 * CONNECT request with the ones we received securely.
2631 destroy_list(csp->headers);
2632 csp->headers->first = csp->https_headers->first;
2633 csp->headers->last = csp->https_headers->last;
2634 csp->https_headers->first = NULL;
2635 csp->https_headers->last = NULL;
2643 /*********************************************************************
2645 * Function : process_encrypted_request
2647 * Description : Receives and parses an encrypted request.
2650 * 1 : csp = Current client state (buffers, headers, etc...)
2652 * Returns : JB_ERR_OK on success,
2653 * JB_ERR_PARSE or JB_ERR_MEMORY otherwise
2655 *********************************************************************/
2656 static jb_err process_encrypted_request(struct client_state *csp)
2661 /* Temporary copy of the client's headers before they get enlisted in csp->https_headers */
2662 struct list header_list;
2663 struct list *headers = &header_list;
2665 assert(csp->ssl_with_client_is_opened);
2667 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2668 if (csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_KEEP_ALIVE)
2670 csp->flags |= CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2673 err = receive_encrypted_request(csp);
2674 if (err != JB_ERR_OK)
2676 if (csp->client_iob->cur == NULL ||
2677 csp->client_iob->cur == csp->client_iob->eod)
2680 * We did not receive any data, most likely because the
2681 * client is done. Don't log this as a parse failure.
2683 return JB_ERR_PARSE;
2685 /* XXX: Also used for JB_ERR_MEMORY */
2686 log_error(LOG_LEVEL_ERROR, "Failed to receive encrypted request: %s",
2687 jb_err_to_string(err));
2688 ssl_send_data_delayed(&(csp->ssl_client_attr),
2689 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2693 /* We don't need get_request_line() because the whole HTTP head is buffered. */
2694 request_line = get_header(csp->client_iob);
2695 if (request_line == NULL)
2697 log_error(LOG_LEVEL_ERROR, "Failed to get the encrypted request line");
2698 ssl_send_data_delayed(&(csp->ssl_client_attr),
2699 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2700 return JB_ERR_PARSE;
2702 assert(*request_line != '\0');
2704 if (client_protocol_is_unsupported(csp, request_line))
2707 * If the protocol is unsupported we're done here.
2708 * client_protocol_is_unsupported() took care of sending
2709 * the error response and logging the error message.
2711 return JB_ERR_PARSE;
2714 #ifdef FEATURE_FORCE_LOAD
2715 if (force_required(csp, request_line))
2717 csp->flags |= CSP_FLAG_FORCED;
2719 #endif /* def FEATURE_FORCE_LOAD */
2721 free_http_request(csp->http);
2723 err = parse_http_request(request_line, csp->http);
2724 /* XXX: Restore ssl setting. This is ugly */
2725 csp->http->client_ssl = 1;
2726 csp->http->server_ssl = 1;
2728 freez(request_line);
2729 if (JB_ERR_OK != err)
2731 ssl_send_data_delayed(&(csp->ssl_client_attr),
2732 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2733 /* XXX: Use correct size */
2734 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"Invalid request\" 400 0", csp->ip_addr_str);
2735 log_error(LOG_LEVEL_ERROR,
2736 "Couldn't parse request line received from %s: %s",
2737 csp->ip_addr_str, jb_err_to_string(err));
2739 free_http_request(csp->http);
2740 return JB_ERR_PARSE;
2743 /* Parse the rest of the client's headers. */
2747 p = get_header(csp->client_iob);
2751 /* There are no additional headers to read. */
2758 if (JB_ERR_OK != get_destination_from_https_headers(headers, csp->http))
2761 * Our attempts to get the request destination
2764 log_error(LOG_LEVEL_ERROR,
2765 "Failed to get the encrypted request destination");
2766 ssl_send_data_delayed(&(csp->ssl_client_attr),
2767 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2768 return JB_ERR_PARSE;
2771 /* Split the domain we just got for pattern matching */
2772 init_domain_components(csp->http);
2774 #ifdef FEATURE_CLIENT_TAGS
2775 /* XXX: If the headers were enlisted sooner, passing csp would do. */
2776 if (csp->client_address == NULL)
2778 set_client_address(csp, headers);
2779 get_tag_list_for_client(csp->client_tags, csp->client_address);
2783 #ifdef FEATURE_TOGGLE
2784 if ((csp->flags & CSP_FLAG_TOGGLED_ON) != 0)
2788 * Determine the actions for this request after
2789 * clearing the ones from the previous one.
2791 free_current_action(csp->action);
2792 get_url_actions(csp, csp->http);
2795 enlist(csp->https_headers, csp->http->cmd);
2797 /* Append the previously read headers */
2798 err = list_append_list_unique(csp->https_headers, headers);
2799 destroy_list(headers);
2800 if (JB_ERR_OK != err)
2802 /* XXX: Send error message */
2806 /* XXX: Work around crash */
2807 csp->error_message = NULL;
2809 /* XXX: Why do this here? */
2812 err = sed_https(csp);
2813 if (JB_ERR_OK != err)
2815 ssl_send_data_delayed(&(csp->ssl_client_attr),
2816 (const unsigned char *)CHEADER, strlen(CHEADER), get_write_delay(csp));
2817 log_error(LOG_LEVEL_ERROR, "Failed to parse client request from %s.",
2819 log_error(LOG_LEVEL_CLF, "%s - - [%T] \"%s\" 400 0",
2820 csp->ip_addr_str, csp->http->cmd);
2821 return JB_ERR_PARSE;
2824 if ((NULL == csp->https_headers->first->str)
2825 || (strcmp(csp->http->cmd, csp->https_headers->first->str) &&
2826 (JB_ERR_OK != change_encrypted_request_destination(csp))))
2828 ssl_send_data_delayed(&(csp->ssl_client_attr),
2829 (const unsigned char *)MESSED_UP_REQUEST_RESPONSE,
2830 strlen(MESSED_UP_REQUEST_RESPONSE), get_write_delay(csp));
2831 log_error(LOG_LEVEL_ERROR,
2832 "Invalid request line after applying header filters.");
2833 /* XXX: Use correct size */
2834 log_error(LOG_LEVEL_CLF,
2835 "%s - - [%T] \"Invalid request generated\" 400 0", csp->ip_addr_str);
2837 return JB_ERR_PARSE;
2840 log_error(LOG_LEVEL_HEADER, "Encrypted request processed");
2841 log_applied_actions(csp->action);
2842 log_error(LOG_LEVEL_REQUEST, "https://%s%s", csp->http->hostport,
2849 /*********************************************************************
2851 * Function : cgi_page_requested
2853 * Description : Checks if a request is for an internal CGI page.
2856 * 1 : host = The host requested by the client.
2858 * Returns : 1 if a CGI page has been requested, 0 otherwise
2860 *********************************************************************/
2861 static int cgi_page_requested(const char *host)
2863 if ((0 == strcmpic(host, CGI_SITE_1_HOST))
2864 || (0 == strcmpic(host, CGI_SITE_1_HOST "."))
2865 || (0 == strcmpic(host, CGI_SITE_2_HOST))
2866 || (0 == strcmpic(host, CGI_SITE_2_HOST ".")))
2876 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
2877 /*********************************************************************
2879 * Function : continue_https_chat
2881 * Description : Behaves similar to chat() but only deals with
2882 * https-inspected requests that arrive on an already
2883 * established connection. The first request is always
2884 * served by chat() which is a lot more complex as it
2885 * has to deal with forwarding settings and connection
2888 * If a connection to the server has already been
2889 * opened it is reused unless the request is blocked
2890 * or the forwarder changed.
2892 * If a connection to the server has not yet been
2893 * opened (because the previous request was crunched),
2894 * or the forwarder changed, the connection is dropped
2895 * so that the client retries on a fresh one.
2898 * 1 : csp = Current client state (buffers, headers, etc...)
2900 * Returns : Nothing.
2902 *********************************************************************/
2903 static void continue_https_chat(struct client_state *csp)
2905 const struct forward_spec *fwd;
2907 if (JB_ERR_OK != process_encrypted_request(csp))
2912 csp->requests_received_total++;
2915 * We have an encrypted request. Check if one of the crunchers wants it.
2917 if (crunch_response_triggered(csp, crunchers_all))
2920 * Yes. The client got the crunch response and we're done here.
2924 if (csp->ssl_with_server_is_opened == 0)
2926 log_error(LOG_LEVEL_CONNECT,
2927 "Dropping the client connection on socket %d. "
2928 "The server connection has not been established yet.",
2930 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2933 assert(csp->server_connection.sfd != JB_INVALID_SOCKET);
2935 fwd = forward_url(csp, csp->http);
2936 if (!connection_destination_matches(&csp->server_connection, csp->http, fwd))
2938 log_error(LOG_LEVEL_CONNECT,
2939 "Dropping the client connection on socket %d with "
2940 "server socket %d connected to %s. The forwarder has changed.",
2941 csp->cfd, csp->server_connection.sfd, csp->server_connection.host);
2942 csp->flags &= ~CSP_FLAG_CLIENT_CONNECTION_KEEP_ALIVE;
2946 log_error(LOG_LEVEL_CONNECT,
2947 "Reusing server socket %d connected to %s. Requests already sent: %u.",
2948 csp->server_connection.sfd, csp->server_connection.host,
2949 csp->server_connection.requests_sent_total);
2951 if (send_https_request(csp))
2954 * Most likely the server connection timed out. We can't easily
2955 * create a new one so simply drop the client connection without a
2956 * error response to let the client retry.
2958 log_error(LOG_LEVEL_CONNECT,
2959 "Dropping client connection on socket %d. "
2960 "Forwarding the encrypted client request failed.",
2964 csp->server_connection.requests_sent_total++;
2965 handle_established_connection(csp);
2966 freez(csp->receive_buffer);
2968 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
2972 /*********************************************************************
2974 * Function : handle_established_connection
2976 * Description : Shuffle data between client and server once the
2977 * connection has been established.
2980 * 1 : csp = Current client state (buffers, headers, etc...)
2982 * Returns : Nothing.
2984 *********************************************************************/
2985 static void handle_established_connection(struct client_state *csp)
2991 struct pollfd poll_fds[2];
2995 struct timeval timeout;
2998 int ms_iis5_hack = 0;
2999 unsigned long long byte_count = 0;
3000 struct http_request *http;
3001 long len = 0; /* for buffer sizes (and negative error codes) */
3002 int buffer_and_filter_content = 0;
3003 unsigned int write_delay;
3004 #ifdef FEATURE_HTTPS_INSPECTION
3006 int use_ssl_tunnel = 0;
3007 csp->dont_verify_certificate = 0;
3009 if (csp->http->ssl && !(csp->action->flags & ACTION_HTTPS_INSPECTION))
3011 /* Pass encrypted content without filtering. */
3016 /* Skeleton for HTTP response, if we should intercept the request */
3017 struct http_response *rsp;
3018 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3019 int watch_client_socket;
3022 csp->receive_buffer_size = csp->config->receive_buffer_size;
3023 csp->receive_buffer = zalloc(csp->receive_buffer_size + 1);
3024 if (csp->receive_buffer == NULL)
3026 log_error(LOG_LEVEL_ERROR,
3027 "Out of memory. Failed to allocate the receive buffer.");
3028 rsp = cgi_error_memory();
3029 send_crunch_response(csp, rsp);
3036 maxfd = (csp->cfd > csp->server_connection.sfd) ?
3037 csp->cfd : csp->server_connection.sfd;
3040 /* pass data between the client and server
3041 * until one or the other shuts down the connection.
3046 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3047 watch_client_socket = 0 == (csp->flags & CSP_FLAG_PIPELINED_REQUEST_WAITING);
3049 write_delay = get_write_delay(csp);
3055 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3056 if (!watch_client_socket)
3058 maxfd = csp->server_connection.sfd;
3061 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3063 FD_SET(csp->cfd, &rfds);
3066 FD_SET(csp->server_connection.sfd, &rfds);
3067 #endif /* ndef HAVE_POLL */
3069 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3070 if ((csp->flags & CSP_FLAG_CHUNKED)
3071 && !(csp->flags & CSP_FLAG_CONTENT_LENGTH_SET)
3072 && ((csp->iob->eod - csp->iob->cur) >= 5)
3073 && !memcmp(csp->iob->eod-5, "0\r\n\r\n", 5))
3076 * XXX: This check should be obsolete now,
3077 * but let's wait a while to be sure.
3079 log_error(LOG_LEVEL_CONNECT,
3080 "Looks like we got the last chunk together with "
3081 "the server headers but didn't detect it earlier. "
3082 "We better stop reading.");
3083 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3084 csp->expected_content_length = byte_count;
3085 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3087 if (server_body && server_response_is_complete(csp, byte_count))
3089 if (csp->expected_content_length == byte_count)
3091 log_error(LOG_LEVEL_CONNECT,
3092 "Done reading from server. Content length: %llu as expected. "
3093 "Bytes most recently read: %ld.",
3098 log_error(LOG_LEVEL_CONNECT,
3099 "Done reading from server. Expected content length: %llu. "
3100 "Actual content length: %llu. Bytes most recently read: %ld.",
3101 csp->expected_content_length, byte_count, len);
3105 * XXX: Should not jump around, handle_established_connection()
3106 * is complicated enough already.
3110 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3113 poll_fds[0].fd = csp->cfd;
3114 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3115 if (!watch_client_socket)
3118 * Ignore incoming data, but still watch out
3119 * for disconnects etc. These flags are always
3120 * implied anyway but explicitly setting them
3123 poll_fds[0].events = POLLERR|POLLHUP;
3128 poll_fds[0].events = POLLIN;
3130 poll_fds[1].fd = csp->server_connection.sfd;
3131 poll_fds[1].events = POLLIN;
3132 n = poll(poll_fds, 2, csp->config->socket_timeout * 1000);
3134 timeout.tv_sec = csp->config->socket_timeout;
3135 timeout.tv_usec = 0;
3136 n = select((int)maxfd + 1, &rfds, NULL, NULL, &timeout);
3137 #endif /* def HAVE_POLL */
3139 /*server or client not responding in timeout */
3142 log_error(LOG_LEVEL_CONNECT, "Socket timeout %d reached: %s",
3143 csp->config->socket_timeout, http->url);
3144 if ((byte_count == 0) && (http->ssl == 0))
3146 send_crunch_response(csp, error_response(csp, "connection-timeout"));
3148 mark_server_socket_tainted(csp);
3149 #ifdef FEATURE_HTTPS_INSPECTION
3150 close_client_and_server_ssl_connections(csp);
3157 log_error(LOG_LEVEL_ERROR, "poll() failed!: %E");
3159 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
3161 mark_server_socket_tainted(csp);
3162 #ifdef FEATURE_HTTPS_INSPECTION
3163 close_client_and_server_ssl_connections(csp);
3169 * This is the body of the browser's request,
3170 * just read and write it.
3172 * Receives data from browser and sends it to server
3174 * XXX: Make sure the client doesn't use pipelining
3175 * behind Privoxy's back.
3178 if ((poll_fds[0].revents & (POLLERR|POLLHUP|POLLNVAL)) != 0)
3180 log_error(LOG_LEVEL_CONNECT,
3181 "The client socket %d has become unusable while "
3182 "the server socket %d is still open.",
3183 csp->cfd, csp->server_connection.sfd);
3184 mark_server_socket_tainted(csp);
3188 if (poll_fds[0].revents != 0)
3190 if (FD_ISSET(csp->cfd, &rfds))
3191 #endif /* def HAVE_POLL*/
3193 int max_bytes_to_read = (int)csp->receive_buffer_size;
3195 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3196 if ((csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
3198 if (data_is_available(csp->cfd, 0))
3201 * If the next request is already waiting, we have
3202 * to stop select()ing the client socket. Otherwise
3203 * we would always return right away and get nothing
3206 watch_client_socket = 0;
3207 log_error(LOG_LEVEL_CONNECT,
3208 "Stop watching client socket %d. "
3209 "There's already another request waiting.",
3214 * If the client socket is set, but there's no data
3215 * available on the socket, the client went fishing
3216 * and continuing talking to the server makes no sense.
3218 log_error(LOG_LEVEL_CONNECT,
3219 "The client closed socket %d while "
3220 "the server socket %d is still open.",
3221 csp->cfd, csp->server_connection.sfd);
3222 mark_server_socket_tainted(csp);
3225 if (csp->expected_client_content_length != 0)
3227 if (csp->expected_client_content_length < csp->receive_buffer_size)
3229 max_bytes_to_read = (int)csp->expected_client_content_length;
3231 log_error(LOG_LEVEL_CONNECT,
3232 "Waiting for up to %d bytes from the client.",
3235 assert(max_bytes_to_read <= csp->receive_buffer_size);
3236 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3238 #ifdef FEATURE_HTTPS_INSPECTION
3239 if (client_use_ssl(csp))
3241 if (csp->http->status == 101)
3243 len = ssl_recv_data(&(csp->ssl_client_attr),
3244 (unsigned char *)csp->receive_buffer,
3245 (size_t)max_bytes_to_read);
3248 log_error(LOG_LEVEL_ERROR, "Failed to receive data "
3249 "on client socket %d for an upgraded connection",
3255 log_error(LOG_LEVEL_CONNECT, "Done receiving data "
3256 "on client socket %d for an upgraded connection",
3260 byte_count += (unsigned long long)len;
3261 len = ssl_send_data(&(csp->ssl_server_attr),
3262 (unsigned char *)csp->receive_buffer, (size_t)len);
3265 log_error(LOG_LEVEL_ERROR, "Failed to send data "
3266 "on server socket %d for an upgraded connection",
3267 csp->server_connection.sfd);
3272 log_error(LOG_LEVEL_CONNECT, "Breaking with TLS/SSL.");
3276 #endif /* def FEATURE_HTTPS_INSPECTION */
3278 len = read_socket(csp->cfd, csp->receive_buffer, max_bytes_to_read);
3282 /* XXX: not sure if this is necessary. */
3283 mark_server_socket_tainted(csp);
3284 break; /* "game over, man" */
3287 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3288 if (csp->expected_client_content_length != 0)
3290 assert(len <= max_bytes_to_read);
3291 csp->expected_client_content_length -= (unsigned)len;
3292 log_error(LOG_LEVEL_CONNECT,
3293 "Expected client content length set to %llu "
3294 "after reading %ld bytes.",
3295 csp->expected_client_content_length, len);
3296 if (csp->expected_client_content_length == 0)
3298 log_error(LOG_LEVEL_CONNECT,
3299 "Done reading from the client.");
3300 csp->flags |= CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ;
3303 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3305 if (write_socket(csp->server_connection.sfd, csp->receive_buffer, (size_t)len))
3307 log_error(LOG_LEVEL_ERROR, "write to: %s failed: %E", http->host);
3308 mark_server_socket_tainted(csp);
3316 * The server wants to talk. It could be the header or the body.
3317 * If `hdr' is null, then it's the header otherwise it's the body.
3318 * FIXME: Does `hdr' really mean `host'? No.
3321 if (poll_fds[1].revents != 0)
3323 if (FD_ISSET(csp->server_connection.sfd, &rfds))
3324 #endif /* HAVE_POLL */
3326 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3328 * If we are buffering content, we don't want to eat up to
3329 * buffer-limit bytes if the client no longer cares about them.
3330 * If we aren't buffering, however, a dead client socket will be
3331 * noticed pretty much right away anyway, so we can reduce the
3332 * overhead by skipping the check.
3334 if (buffer_and_filter_content && !socket_is_still_alive(csp->cfd))
3337 log_error(LOG_LEVEL_CONNECT,
3338 "The server still wants to talk, but the client may already have hung up on us.");
3340 log_error(LOG_LEVEL_CONNECT,
3341 "The server still wants to talk, but the client hung up on us.");
3342 mark_server_socket_tainted(csp);
3343 #ifdef FEATURE_HTTPS_INSPECTION
3344 close_client_and_server_ssl_connections(csp);
3347 #endif /* def _WIN32 */
3349 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
3351 #ifdef FEATURE_HTTPS_INSPECTION
3353 * Reading data from standard or secured connection (HTTP/HTTPS)
3355 if (server_use_ssl(csp))
3357 len = ssl_recv_data(&(csp->ssl_server_attr),
3358 (unsigned char *)csp->receive_buffer, csp->receive_buffer_size);
3363 len = read_socket(csp->server_connection.sfd, csp->receive_buffer,
3364 (int)csp->receive_buffer_size);
3369 log_error(LOG_LEVEL_ERROR, "read from: %s failed: %E", http->host);
3371 if ((http->ssl && (csp->fwd == NULL))
3372 #ifdef FEATURE_HTTPS_INSPECTION
3378 * Just hang up. We already confirmed the client's CONNECT
3379 * request with status code 200 and unencrypted content is
3380 * no longer welcome.
3382 log_error(LOG_LEVEL_ERROR,
3383 "CONNECT already confirmed. Unable to tell the client about the problem.");
3386 else if (byte_count)
3389 * Just hang up. We already transmitted the original headers
3390 * and parts of the original content and therefore missed the
3391 * chance to send an error message (without risking data corruption).
3393 * XXX: we could retry with a fancy range request here.
3395 log_error(LOG_LEVEL_ERROR, "Already forwarded the original headers. "
3396 "Unable to tell the client about the problem.");
3397 mark_server_socket_tainted(csp);
3398 #ifdef FEATURE_HTTPS_INSPECTION
3399 close_client_and_server_ssl_connections(csp);
3404 * XXX: Consider handling the cases above the same.
3406 mark_server_socket_tainted(csp);
3410 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
3411 if (csp->flags & CSP_FLAG_CHUNKED)
3413 if ((len >= 5) && !memcmp(csp->receive_buffer+len-5, "0\r\n\r\n", 5))
3415 /* XXX: this is a temporary hack */
3416 log_error(LOG_LEVEL_CONNECT,
3417 "Looks like we reached the end of the last chunk. "
3418 "We better stop reading.");
3419 csp->expected_content_length = byte_count + (unsigned long long)len;
3420 csp->flags |= CSP_FLAG_CONTENT_LENGTH_SET;
3424 #endif /* FEATURE_CONNECTION_KEEP_ALIVE */
3427 * This is guaranteed by allocating with zalloc_or_die()
3428 * and never (intentionally) writing to the last byte.
3430 * csp->receive_buffer_size is the size of the part of the
3431 * buffer we intentionally write to, but we actually
3432 * allocated csp->receive_buffer_size+1 bytes so the assertion
3433 * stays within the allocated range.
3435 assert(csp->receive_buffer[csp->receive_buffer_size] == '\0');
3438 * Add a trailing zero to let be able to use string operations.
3439 * XXX: do we still need this with filter_popups gone?
3441 assert(len <= csp->receive_buffer_size);
3442 csp->receive_buffer[len] = '\0';
3445 * Normally, this would indicate that we've read
3446 * as much as the server has sent us and we can
3447 * close the client connection. However, Microsoft
3448 * in its wisdom has released IIS/5 with a bug that
3449 * prevents it from sending the trailing \r\n in
3450 * a 302 redirect header (and possibly other headers).
3451 * To work around this if we've haven't parsed
3452 * a full header we'll append a trailing \r\n
3453 * and see if this now generates a valid one.
3455 * This hack shouldn't have any impacts. If we've
3456 * already transmitted the header or if this is a
3457 * SSL connection, then we won't bother with this
3458 * hack. So we only work on partially received
3459 * headers. If we append a \r\n and this still
3460 * doesn't generate a valid header, then we won't
3461 * transmit anything to the client.
3466 if (server_body || (http->ssl
3467 #ifdef FEATURE_HTTPS_INSPECTION
3473 * If we have been buffering up the document,
3474 * now is the time to apply content modification
3475 * and send the result to the client.
3477 if (buffer_and_filter_content)
3479 p = execute_content_filters(csp);
3481 * If content filtering fails, use the original
3482 * buffer and length.
3483 * (see p != NULL ? p : csp->iob->cur below)
3487 csp->content_length = (size_t)(csp->iob->eod - csp->iob->cur);
3489 #ifdef FEATURE_COMPRESSION
3490 else if ((csp->flags & CSP_FLAG_CLIENT_SUPPORTS_DEFLATE)
3491 && (csp->content_length > LOWER_LENGTH_LIMIT_FOR_COMPRESSION))
3493 char *compressed_content = compress_buffer(p,
3494 (size_t *)&csp->content_length, csp->config->compression_level);
3495 if (compressed_content != NULL)
3498 p = compressed_content;
3499 csp->flags |= CSP_FLAG_BUFFERED_CONTENT_DEFLATED;
3504 if (JB_ERR_OK != update_server_headers(csp))
3506 log_error(LOG_LEVEL_FATAL,
3507 "Failed to update server headers. after filtering.");
3510 hdr = list_to_text(csp->headers);
3513 /* FIXME Should handle error properly */
3514 log_error(LOG_LEVEL_FATAL, "Out of memory parsing server header");
3517 #ifdef FEATURE_HTTPS_INSPECTION
3519 * Sending data with standard or secured connection (HTTP/HTTPS)
3521 if (client_use_ssl(csp))
3523 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3524 (const unsigned char *)hdr, strlen(hdr),
3525 get_write_delay(csp)) < 0)
3526 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3527 (const unsigned char *) ((p != NULL) ? p : csp->iob->cur),
3528 csp->content_length, get_write_delay(csp)) < 0))
3530 log_error(LOG_LEVEL_ERROR, "write modified content to "
3531 "client over TLS/SSL failed");
3534 mark_server_socket_tainted(csp);
3535 close_client_and_server_ssl_connections(csp);
3540 #endif /* def FEATURE_HTTPS_INSPECTION */
3542 if (write_socket_delayed(csp->cfd, hdr, strlen(hdr), write_delay)
3543 || write_socket_delayed(csp->cfd, ((p != NULL) ? p : csp->iob->cur),
3544 (size_t)csp->content_length, write_delay))
3546 log_error(LOG_LEVEL_ERROR, "write modified content to client failed: %E");
3549 mark_server_socket_tainted(csp);
3558 break; /* "game over, man" */
3562 * This is NOT the body, so
3563 * Let's pretend the server just sent us a blank line.
3565 snprintf(csp->receive_buffer, csp->receive_buffer_size, "\r\n");
3566 len = (int)strlen(csp->receive_buffer);
3569 * Now, let the normal header parsing algorithm below do its
3570 * job. If it fails, we'll exit instead of continuing.
3577 * If we're in the body of the server document, just write it to
3578 * the client, unless we need to buffer the body for later
3579 * content-filtering.
3581 if (server_body || (http->ssl
3582 #ifdef FEATURE_HTTPS_INSPECTION
3587 if (buffer_and_filter_content)
3590 * If there is no memory left for buffering the content, or the buffer limit
3591 * has been reached, switch to non-filtering mode, i.e. make & write the
3592 * header, flush the iob and buf, and get out of the way.
3594 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3599 log_error(LOG_LEVEL_INFO,
3600 "Flushing header and buffers. Stepping back from filtering.");
3602 hdr = list_to_text(csp->headers);
3606 * Memory is too tight to even generate the header.
3607 * Send our static "Out-of-memory" page.
3609 log_error(LOG_LEVEL_ERROR, "Out of memory while trying to flush.");
3610 rsp = cgi_error_memory();
3611 send_crunch_response(csp, rsp);
3612 mark_server_socket_tainted(csp);
3613 #ifdef FEATURE_HTTPS_INSPECTION
3614 close_client_and_server_ssl_connections(csp);
3618 hdrlen = strlen(hdr);
3620 #ifdef FEATURE_HTTPS_INSPECTION
3622 * Sending data with standard or secured connection (HTTP/HTTPS)
3624 if (client_use_ssl(csp))
3626 if ((ssl_send_data_delayed(&(csp->ssl_client_attr),
3627 (const unsigned char *)hdr, hdrlen, get_write_delay(csp)) < 0)
3628 || ((flushed = ssl_flush_socket(&(csp->ssl_client_attr),
3630 || (ssl_send_data_delayed(&(csp->ssl_client_attr),
3631 (const unsigned char *)csp->receive_buffer, (size_t)len,
3632 get_write_delay(csp)) < 0))
3634 log_error(LOG_LEVEL_CONNECT,
3635 "Flush header and buffers to client failed");
3637 mark_server_socket_tainted(csp);
3638 close_client_and_server_ssl_connections(csp);
3643 #endif /* def FEATURE_HTTPS_INSPECTION */
3645 if (write_socket_delayed(csp->cfd, hdr, hdrlen, write_delay)
3646 || ((flushed = flush_iob(csp->cfd, csp->iob, write_delay)) < 0)
3647 || write_socket_delayed(csp->cfd, csp->receive_buffer, (size_t)len,
3650 log_error(LOG_LEVEL_CONNECT,
3651 "Flush header and buffers to client failed: %E");
3653 mark_server_socket_tainted(csp);
3659 * Reset the byte_count to the amount of bytes
3660 * we just flushed. len will be added a few lines below,
3661 * hdrlen doesn't matter for LOG_LEVEL_CLF.
3663 byte_count = (unsigned long long)flushed;
3665 buffer_and_filter_content = 0;
3671 #ifdef FEATURE_HTTPS_INSPECTION
3673 * Sending data with standard or secured connection (HTTP/HTTPS)
3675 if (client_use_ssl(csp))
3677 ret = ssl_send_data_delayed(&(csp->ssl_client_attr),
3678 (const unsigned char *)csp->receive_buffer, (size_t)len,
3679 get_write_delay(csp));
3682 log_error(LOG_LEVEL_ERROR,
3683 "Sending data to client failed");
3684 mark_server_socket_tainted(csp);
3685 close_client_and_server_ssl_connections(csp);
3690 #endif /* def FEATURE_HTTPS_INSPECTION */
3692 if (write_socket_delayed(csp->cfd, csp->receive_buffer,
3693 (size_t)len, write_delay))
3695 log_error(LOG_LEVEL_ERROR, "write to client failed: %E");
3696 mark_server_socket_tainted(csp);
3701 byte_count += (unsigned long long)len;
3707 * We're still looking for the end of the server's header.
3708 * Buffer up the data we just read. If that fails, there's
3709 * little we can do but send our static out-of-memory page.
3711 if (add_to_iob(csp->iob, csp->config->buffer_limit, csp->receive_buffer, len))
3713 log_error(LOG_LEVEL_ERROR, "Out of memory while looking for end of server headers.");
3714 rsp = cgi_error_memory();
3715 send_crunch_response(csp, rsp);
3716 mark_server_socket_tainted(csp);
3717 #ifdef FEATURE_HTTPS_INSPECTION
3718 close_client_and_server_ssl_connections(csp);
3723 /* Convert iob into something sed() can digest */
3724 if (JB_ERR_PARSE == get_server_headers(csp))
3729 * Well, we tried our MS IIS/5 hack and it didn't work.
3730 * The header is incomplete and there isn't anything
3731 * we can do about it.
3733 log_error(LOG_LEVEL_ERROR, "Invalid server headers. "
3734 "Applying the MS IIS5 hack didn't help.");
3735 log_error(LOG_LEVEL_CLF,
3736 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3737 #ifdef FEATURE_HTTPS_INSPECTION
3739 * Sending data with standard or secured connection (HTTP/HTTPS)
3741 if (client_use_ssl(csp))
3743 ssl_send_data_delayed(&(csp->ssl_client_attr),
3744 (const unsigned char *)INVALID_SERVER_HEADERS_RESPONSE,
3745 strlen(INVALID_SERVER_HEADERS_RESPONSE), get_write_delay(csp));
3748 #endif /* def FEATURE_HTTPS_INSPECTION */
3750 write_socket_delayed(csp->cfd,
3751 INVALID_SERVER_HEADERS_RESPONSE,
3752 strlen(INVALID_SERVER_HEADERS_RESPONSE), write_delay);
3754 mark_server_socket_tainted(csp);
3755 #ifdef FEATURE_HTTPS_INSPECTION
3756 close_client_and_server_ssl_connections(csp);
3763 * Since we have to wait for more from the server before
3764 * we can parse the headers we just continue here.
3766 log_error(LOG_LEVEL_CONNECT,
3767 "Continuing buffering server headers from socket %d. "
3768 "Bytes most recently read: %ld.", csp->cfd, len);
3775 * Account for the content bytes we
3776 * might have gotten with the headers.
3778 assert(csp->iob->eod >= csp->iob->cur);
3779 byte_count = (unsigned long long)(csp->iob->eod - csp->iob->cur);
3782 /* Did we actually get anything? */
3783 if (NULL == csp->headers->first)
3785 if ((csp->flags & CSP_FLAG_REUSED_CLIENT_CONNECTION))
3787 log_error(LOG_LEVEL_ERROR,
3788 "No server or forwarder response received on socket %d. "
3789 "Closing client socket %d without sending data.",
3790 csp->server_connection.sfd, csp->cfd);
3791 log_error(LOG_LEVEL_CLF,
3792 "%s - - [%T] \"%s\" 502 0", csp->ip_addr_str, http->cmd);
3796 log_error(LOG_LEVEL_ERROR,
3797 "No server or forwarder response received on socket %d.",
3798 csp->server_connection.sfd);
3799 send_crunch_response(csp, error_response(csp, "no-server-data"));
3801 free_http_request(http);
3802 mark_server_socket_tainted(csp);
3803 #ifdef FEATURE_HTTPS_INSPECTION
3804 close_client_and_server_ssl_connections(csp);
3809 if (!csp->headers->first->str)
3811 log_error(LOG_LEVEL_ERROR, "header search: csp->headers->first->str == NULL, assert will be called");
3813 assert(csp->headers->first->str);
3815 if (strncmpic(csp->headers->first->str, "HTTP", 4) &&