geph4_protocol/
vpn_msg.rs

1use bytes::{Bytes, BytesMut};
2use serde::{Deserialize, Serialize};
3
4use std::net::Ipv4Addr;
5use std::ops::DerefMut;
6
7/// VPN on-the-wire message
8#[derive(Serialize, Deserialize, Debug, Clone)]
9pub enum VpnMessage {
10    ClientHello {
11        client_id: u128,
12    },
13    ServerHello {
14        client_ip: Ipv4Addr,
15        gateway: Ipv4Addr,
16    },
17    Payload(Bytes),
18}
19
20/// Stdio message
21#[derive(Debug, Clone)]
22pub struct VpnStdio {
23    pub verb: u8,
24    pub body: Bytes,
25}
26
27impl VpnStdio {
28    /// Reads a new StdioMsg
29    pub async fn read<R: smol::io::AsyncRead + Unpin>(reader: &mut R) -> std::io::Result<Self> {
30        use smol::io::AsyncReadExt;
31        // first we read one byte
32        let mut scratch_space = [0u8; 2];
33        reader.read_exact(&mut scratch_space[..1]).await?;
34        let verb = scratch_space[0];
35        reader.read_exact(&mut scratch_space).await?;
36        let length = u16::from_le_bytes(scratch_space);
37        let mut bts = BytesMut::new();
38        bts.resize(length as usize, 0);
39        reader.read_exact(&mut bts).await?;
40        Ok(VpnStdio {
41            verb,
42            body: bts.into(),
43        })
44    }
45
46    /// Reads a new StdioMsg, synchronously.
47    pub fn read_blocking<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self> {
48        let mut scratch_space = [0u8; 2];
49        reader.read_exact(&mut scratch_space[..1])?;
50        let verb = scratch_space[0];
51        reader.read_exact(&mut scratch_space)?;
52        let length = u16::from_le_bytes(scratch_space);
53        let mut bts = BytesMut::new();
54        bts.resize(length as usize, 0);
55        reader.read_exact(&mut bts)?;
56        Ok(VpnStdio {
57            verb,
58            body: bts.into(),
59        })
60    }
61
62    /// Write out the StdioMsg
63    pub async fn write<W: smol::io::AsyncWrite + Unpin>(
64        &self,
65        writer: &mut W,
66    ) -> std::io::Result<()> {
67        use smol::io::AsyncWriteExt;
68        let mut buf = Vec::with_capacity(2048);
69        buf.write_all(&[self.verb]).await?;
70        buf.write_all(&(self.body.len() as u16).to_le_bytes())
71            .await?;
72        buf.write_all(&self.body).await?;
73        writer.write_all(&buf).await?;
74        Ok(())
75    }
76
77    /// Write out the StdioMsg, blockingly.
78    pub fn write_blocking<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
79        use std::io::Write;
80        let mut buf = Vec::with_capacity(2048);
81        buf.write_all(&[self.verb])?;
82        buf.write_all(&(self.body.len() as u16).to_le_bytes())?;
83        buf.write_all(&self.body)?;
84        writer.write_all(&buf)?;
85        Ok(())
86    }
87}
88
89pub fn serialize<T: Serialize>(val: &T) -> Bytes {
90    let mut bmut = Vec::new();
91    bincode::serialize_into(bmut.deref_mut(), val).unwrap();
92    bmut.into()
93}