Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update #23

Merged
merged 4 commits into from
Jun 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 55 additions & 32 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,25 +163,13 @@ impl<C: Borrow<rcgen::CertifiedKey> + Send + Sync + 'static> MitmProxy<C> {
B::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
{
let original_uri = req.uri().clone();
let (req_back_tx, req_back_rx) = futures::channel::oneshot::channel();
let (res_tx, res_rx) = futures::channel::oneshot::channel();
let (upgrade_tx, upgrade_rx) = futures::channel::oneshot::channel();
// Used tokio::spawn above to middle_man can consume rx in request()
let _ = tx.unbounded_send(Communication {
client_addr,
request: req,
request_back: req_back_tx,
response: res_rx,
upgrade: upgrade_rx,
});

let Ok(req) = req_back_rx.await else {
tracing::info!("Request canceled");

let (Some(req), res_tx, upgrade_tx) = send_and_receive_request(&tx, client_addr, req).await
else {
return Ok(no_body(StatusCode::INTERNAL_SERVER_ERROR));
};

if req.method() == Method::CONNECT {
// Modified CONNECT request is ignored
// HTTPS connection
let Some(connect_authority) = req.uri().authority().cloned() else {
tracing::error!(
Expand Down Expand Up @@ -217,9 +205,16 @@ impl<C: Borrow<rcgen::CertifiedKey> + Send + Sync + 'static> MitmProxy<C> {
// TODO: Cache server_config
let server_config = Arc::new(server_config);
let tls_acceptor = tokio_rustls::TlsAcceptor::from(server_config);
let Ok(client) = tls_acceptor.accept(TokioIo::new(client)).await else {
tracing::error!("Failed to accept TLS connection for {}", original_host);
return;
let client = match tls_acceptor.accept(TokioIo::new(client)).await {
Ok(client) => client,
Err(err) => {
tracing::error!(
"Failed to accept TLS connection for {}, {}",
original_host,
err
);
return;
}
};

let f = move |mut req: Request<_>| {
Expand All @@ -228,20 +223,11 @@ impl<C: Borrow<rcgen::CertifiedKey> + Send + Sync + 'static> MitmProxy<C> {
let proxy = proxy.clone();

async move {
let (req_back_tx, req_back_rx) = futures::channel::oneshot::channel();
let (res_tx, res_rx) = futures::channel::oneshot::channel();
let (upgrade_tx, upgrade_rx) = futures::channel::oneshot::channel();

inject_authority(&mut req, connect_authority.clone());
let _ = tx.unbounded_send(Communication {
client_addr,
request: req,
request_back: req_back_tx,
response: res_rx,
upgrade: upgrade_rx,
});
let Ok(req) = req_back_rx.await else {
tracing::info!("Request canceled");

let (Some(req), res_tx, upgrade_tx) =
send_and_receive_request(&tx, client_addr, req).await
else {
return Ok::<_, hyper::Error>(no_body(
StatusCode::INTERNAL_SERVER_ERROR,
));
Expand Down Expand Up @@ -423,7 +409,13 @@ impl<C> MitmProxyImpl<C> {
80
});

let tcp = TcpStream::connect((host, port)).await.unwrap();
let tcp = match TcpStream::connect((host, port)).await {
Ok(tcp) => tcp,
Err(err) => {
tracing::error!("Failed to connect to {}:{} {}", host, port, err);
panic!();
}
};
// This is actually needed to some servers
let _ = tcp.set_nodelay(true);

Expand Down Expand Up @@ -595,3 +587,34 @@ where

(StreamBody::new(body), rx)
}

async fn send_and_receive_request<B>(
tx: &UnboundedSender<Communication<B>>,
client_addr: std::net::SocketAddr,
req: Request<Incoming>,
) -> (
Option<Request<B>>,
futures::channel::oneshot::Sender<
Result<Response<UnboundedReceiver<Result<Frame<Bytes>, Arc<hyper::Error>>>>, hyper::Error>,
>,
futures::channel::oneshot::Sender<Upgrade>,
) {
let (req_back_tx, req_back_rx) = futures::channel::oneshot::channel();
let (res_tx, res_rx) = futures::channel::oneshot::channel();
let (upgrade_tx, upgrade_rx) = futures::channel::oneshot::channel();
// Used tokio::spawn above to middle_man can consume rx in request()
let _ = tx.unbounded_send(Communication {
client_addr,
request: req,
request_back: req_back_tx,
response: res_rx,
upgrade: upgrade_rx,
});

if let Ok(req) = req_back_rx.await {
tracing::info!("Request canceled");
(Some(req), res_tx, upgrade_tx)
} else {
(None, res_tx, upgrade_tx)
}
}
8 changes: 4 additions & 4 deletions tests/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ async fn test_modify_header() {
assert_eq!(String::from_utf8(body).unwrap(), "MODIFIED");
}
#[tokio::test]
async fn test_modify_url() {
async fn test_modify_url_http_to_http() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));

let mut setup = setup(app, false).await;
Expand All @@ -340,7 +340,7 @@ async fn test_modify_url() {
}

#[tokio::test]
async fn test_modify_url_https() {
async fn test_modify_url_http_to_https() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));

let mut setup = setup(app, true).await;
Expand Down Expand Up @@ -529,7 +529,7 @@ async fn test_tls_simple() {
}

#[tokio::test]
async fn test_tls_modify_url() {
async fn test_tls_modify_url_https_to_https() {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
Expand Down Expand Up @@ -566,7 +566,7 @@ async fn test_tls_modify_url() {
}

#[tokio::test]
async fn test_tls_modify_url_http() {
async fn test_tls_modify_url_https_to_http() {
let app = Router::new().route("/", get(|| async { "Hello, World!" }));

let mut setup = setup_tls(app, false, true).await;
Expand Down
Loading