Skip to content

Commit eb29a8a

Browse files
authored
Always reclaim buffer space (#229)
* simplify some buffer usage with `Vec<u8>`, fix a bug where we didn't reclaim capacity * fixup
1 parent 49e5d6c commit eb29a8a

File tree

4 files changed

+20
-23
lines changed

4 files changed

+20
-23
lines changed

mitmproxy-linux/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ This package requires the following software to build (via https://aya-rs.dev/bo
1616

1717
1. Install build dependencies (see above).
1818
2. Install mitmproxy_linux as editable: `pip install -e .`
19-
3. Run something along the lines of `mitmdump --mode local:curl`.
19+
3. Remove `$VIRTUAL_ENV/bin/mitmproxy-linux-redirector`
20+
4. Run something along the lines of `mitmdump --mode local:curl`.
2021
You should see a `Development mode: Compiling mitmproxy-linux-redirector...` message.
2122

2223

mitmproxy-linux/src/main2.rs

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -109,18 +109,18 @@ async fn main() -> anyhow::Result<()> {
109109
std::process::exit(0);
110110
});
111111

112-
let mut ipc_buf = BytesMut::with_capacity(IPC_BUF_SIZE);
112+
let mut ipc_buf = Vec::with_capacity(IPC_BUF_SIZE);
113113
let mut dev_buf = BytesMut::with_capacity(IPC_BUF_SIZE);
114114

115115
loop {
116+
ipc_buf.clear();
116117
select! {
117118
r = ipc.recv_buf(&mut ipc_buf) => {
118119
match r {
119120
Ok(len) if len > 0 => {
120-
let Ok(FromProxy { message: Some(message)}) = FromProxy::decode(&mut ipc_buf) else {
121+
let Ok(FromProxy { message: Some(message)}) = FromProxy::decode(ipc_buf.as_slice()) else {
121122
return Err(anyhow!("Received invalid IPC message: {:?}", &ipc_buf[..len]));
122123
};
123-
assert_eq!(ipc_buf.len(), 0);
124124
// debug!("Received IPC message: {message:?}");
125125

126126
match message {
@@ -161,10 +161,12 @@ async fn main() -> anyhow::Result<()> {
161161
};
162162

163163
packet.encode(&mut ipc_buf)?;
164-
let encoded = ipc_buf.split();
165-
166164
// debug!("Sending packet to proxy: {} {:?}", encoded.len(), &encoded);
167-
ipc.send(&encoded).await?;
165+
ipc.send(ipc_buf.as_slice()).await?;
166+
167+
// Reclaim space in dev_buf.
168+
drop(packet);
169+
assert!(dev_buf.try_reclaim(IPC_BUF_SIZE));
168170
},
169171
}
170172
}

src/packet_sources/macos.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -152,11 +152,8 @@ impl PacketSourceTask for MacOsTask {
152152
},
153153
// pipe through changes to the intercept list
154154
Some(conf) = self.conf_rx.recv() => {
155-
let msg = ipc::InterceptConf::from(conf);
156-
let len = msg.encoded_len();
157-
let mut buf = BytesMut::with_capacity(len);
158-
msg.encode(&mut buf)?;
159-
control_channel.send(buf.freeze()).await.context("Failed to write to control channel")?;
155+
let msg = ipc::InterceptConf::from(conf).encode_to_vec();
156+
control_channel.send(Bytes::from(msg)).await.context("Failed to write to control channel")?;
160157
},
161158
}
162159
}
@@ -191,12 +188,12 @@ impl ConnectionTask {
191188
.read_u32()
192189
.await
193190
.context("Failed to read handshake.")? as usize;
194-
let mut buf = BytesMut::zeroed(len);
191+
let mut buf = vec![0; len];
195192
self.stream
196193
.read_exact(&mut buf)
197194
.await
198195
.context("Failed to read handshake contents.")?;
199-
NewFlow::decode(&buf[..]).context("Invalid handshake IPC")?
196+
NewFlow::decode(buf.as_slice()).context("Invalid handshake IPC")?
200197
};
201198

202199
match new_flow {

src/packet_sources/mod.rs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use crate::messages::{
66
use crate::network::add_network_layer;
77
use crate::{ipc, shutdown, MAX_PACKET_SIZE};
88
use anyhow::{anyhow, Context, Result};
9-
use prost::bytes::{Bytes, BytesMut};
9+
use prost::bytes::Bytes;
1010
use prost::Message;
1111
use std::future::Future;
1212
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
@@ -53,11 +53,12 @@ async fn forward_packets<T: AsyncRead + AsyncWrite + Unpin>(
5353
mut conf_rx: UnboundedReceiver<InterceptConf>,
5454
shutdown: shutdown::Receiver,
5555
) -> Result<()> {
56-
let mut buf = BytesMut::with_capacity(IPC_BUF_SIZE);
56+
let mut buf = Vec::with_capacity(IPC_BUF_SIZE);
5757
let (mut network_task_handle, net_tx, mut net_rx) =
5858
add_network_layer(transport_events_tx, transport_commands_rx, shutdown);
5959

6060
loop {
61+
buf.clear();
6162
tokio::select! {
6263
// Monitor the network task for errors or planned shutdown.
6364
// This way we implicitly monitor the shutdown channel.
@@ -68,9 +69,7 @@ async fn forward_packets<T: AsyncRead + AsyncWrite + Unpin>(
6869
message: Some(ipc::from_proxy::Message::InterceptConf(conf.into())),
6970
};
7071
msg.encode(&mut buf)?;
71-
72-
// debug!("Sending IPC message to redirector: {} {:?}", buf.len(), buf);
73-
channel.write_all_buf(&mut buf).await.context("failed to propagate interception config update")?;
72+
channel.write_all(&buf).await.context("failed to propagate interception config update")?;
7473
},
7574
// read packets from the IPC pipe into our network stack.
7675
_ = channel.read_buf(&mut buf) => {
@@ -85,10 +84,9 @@ async fn forward_packets<T: AsyncRead + AsyncWrite + Unpin>(
8584
return Err(anyhow!("redirect daemon exited prematurely."));
8685
}
8786

88-
let Ok(PacketWithMeta { data, tunnel_info}) = PacketWithMeta::decode(&mut buf) else {
87+
let Ok(PacketWithMeta { data, tunnel_info}) = PacketWithMeta::decode(buf.as_slice()) else {
8988
return Err(anyhow!("Received invalid IPC message from redirector: {:?}", &buf));
9089
};
91-
assert!(buf.is_empty());
9290

9391
// TODO: Use Bytes in SmolPacket to avoid copy
9492
let data = data.to_vec();
@@ -121,10 +119,9 @@ async fn forward_packets<T: AsyncRead + AsyncWrite + Unpin>(
121119
match e {
122120
NetworkCommand::SendPacket(packet) => {
123121
let packet = ipc::FromProxy { message: Some(ipc::from_proxy::Message::Packet( ipc::Packet { data: Bytes::from(packet.into_inner()) }))};
124-
assert!(buf.is_empty());
125122
packet.encode(&mut buf)?;
126123
// debug!("Sending packet: {} {:?}", buf.len(), &packet.message.as_ref().unwrap());
127-
channel.write_all_buf(&mut buf).await.context("failed to send packet")?;
124+
channel.write_all(&buf).await.context("failed to send packet")?;
128125
}
129126
}
130127
}

0 commit comments

Comments
 (0)