Skip to content

Commit

Permalink
Cleaned up some code.
Browse files Browse the repository at this point in the history
Do not send response to client until connection is live.
  • Loading branch information
zlogic committed Jul 13, 2024
1 parent 12a4b39 commit 8d20b10
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 59 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ rust-version = "1.77"
log = { version = "0.4", default-features = false }
tokio = { version = "1.38", default-features = false, features = ["rt", "io-util", "signal", "net", "time", "sync"] }
tokio-native-tls = { version = "0.3", default-features = false }
smoltcp = { version = "0.11", default-features = false, features = ["std", "async", "medium-ip", "proto-ipv4", "proto-ipv6", "socket-tcp"] }
smoltcp = { version = "0.11", default-features = false, features = ["std", "medium-ip", "proto-ipv4", "proto-ipv6", "socket-tcp"] }
rand = { version = "0.8", default-features = false, features = ["std", "std_rng"] }

[profile.release]
Expand Down
52 changes: 44 additions & 8 deletions src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ pub struct Network<'a> {
iface: iface::Interface,
sockets: iface::SocketSet<'a>,
bridges: HashMap<iface::SocketHandle, SocketTunnel>,
opening_connections:
HashMap<iface::SocketHandle, Option<oneshot::Sender<SocketConnectionResult>>>,
cmd_sender: mpsc::Sender<Command>,
cmd_receiver: mpsc::Receiver<Command>,
}
Expand Down Expand Up @@ -54,6 +56,7 @@ impl Network<'_> {
iface,
sockets,
bridges: HashMap::new(),
opening_connections: HashMap::new(),
cmd_sender,
cmd_receiver,
})
Expand Down Expand Up @@ -120,6 +123,42 @@ impl Network<'_> {
}
}
}

for (handle, response) in self.opening_connections.iter_mut() {
let socket = self.sockets.get::<tcp::Socket>(*handle);
let result = match socket.state() {
tcp::State::Closed | tcp::State::TimeWait | tcp::State::Closing => {
Some(Err("Socket is closed".into()))
}
tcp::State::SynSent | tcp::State::SynReceived => {
// Not ready.
None
}
_ => {
let response = match socket.local_endpoint() {
Some(endpoint) => {
(*handle, SocketAddr::from((endpoint.addr, endpoint.port)))
}
None => (*handle, SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0)),
};
Some(Ok(response))
}
};
let result = if let Some(result) = result {
result
} else {
println!("Socket state is {}", socket.state());
continue;
};
let response = if let Some(response) = response.take() {
response
} else {
continue;
};
let _ = response.send(result);
}
self.opening_connections
.retain(|_, response| response.is_some());
}

pub fn create_command_sender(&self) -> mpsc::Sender<Command> {
Expand All @@ -143,14 +182,9 @@ impl Network<'_> {
return;
}

let local_addr = match socket.local_endpoint() {
Some(endpoint) => SocketAddr::from((endpoint.addr, endpoint.port)),
None => SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), local_port),
};
// TODO: use poll_fn until connection becomes fully available.
// See https://github.com/embassy-rs/embassy/blob/main/embassy-net/src/tcp.rs#L233 for more details.
let socket_handle = self.sockets.add(socket);
let _ = response.send(Ok((socket_handle, local_addr)));
self.opening_connections
.insert(socket_handle, Some(response));
}
Command::Bridge(socket_handle, reader, writer) => {
let socket_tunnel = SocketTunnel {
Expand Down Expand Up @@ -188,10 +222,12 @@ struct SocketTunnel {

impl SocketTunnel {}

type SocketConnectionResult = Result<(iface::SocketHandle, SocketAddr), NetworkError>;

pub enum Command {
Connect(
std::net::SocketAddr,
oneshot::Sender<Result<(iface::SocketHandle, SocketAddr), NetworkError>>,
oneshot::Sender<SocketConnectionResult>,
),
Bridge(
iface::SocketHandle,
Expand Down
50 changes: 0 additions & 50 deletions src/socks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,57 +100,7 @@ impl SocksConnection {
Ok(_) => Ok(()),
Err(_) => Err("Command channel closed".into()),
}
//tokio::io::copy(&mut self.reader, &mut socket).await?;
//let (sender, receiver) = oneshot::channel();
//let write_command = network::Command::Write(socket.handle(), self.reader, todo!());
/*
let rt = runtime::Handle::current();
rt.spawn(SocksConnection::tunnel_to_destination(
self.command_bridge.clone(),
reader,
socket.handle(),
));
let mut request = String::new();
while self.reader.read_line(&mut request).await? > 0 {
println!("Received request {}", request);
request.clear();
}
*/
}

/*
async fn tunnel_to_destination(
command_bridge: mpsc::Sender<network::Command>,
mut reader: BufReader<tcp::OwnedReadHalf>,
socket_handle: smoltcp::iface::SocketHandle,
) -> Result<(), SocksError> {
let mut buffer = None;
const BUFFER_SIZE: usize = 1024;
loop {
let (sender, receiver) = oneshot::channel();
let mut buf = if let Some(buf) = buffer.take() {
buf
} else {
Vec::with_capacity(BUFFER_SIZE)
};
let current_size = buf.len();
buf.resize(buf.capacity(), 0u8);
let bytes_read = reader.read(&mut buf[current_size..]).await?;
buf.truncate(current_size + bytes_read);
let write_command = network::Command::Write(socket_handle, buf, sender);
let _ = command_bridge.send(write_command).await;
match receiver.await {
Ok(Ok(buf)) => buffer = Some(buf),
Ok(Err(_err)) => {
return Err("Error writing into socket".into());
}
Err(_) => return Ok(()),
}
}
}
*/

async fn perform_handshake(
&mut self,
Expand Down

0 comments on commit 8d20b10

Please sign in to comment.