1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
use std::{fmt::Debug, time::Duration};

use bytes::BytesMut;
use if_chain::if_chain;
use tokio::{
    io::BufWriter,
    net::{TcpStream, UdpSocket},
    time::{self, timeout},
};

#[cfg(feature = "websocket")]
use super::websocket::TungsteniteWebSocket;
use super::AsyncTryReadWriteBytes;
use crate::{
    error::Error,
    insim::Isi,
    net::{Codec, DEFAULT_TIMEOUT_SECS},
    packet::Packet,
    result::Result,
    DEFAULT_BUFFER_CAPACITY,
};

/// A unified wrapper around anything that implements [AsyncTryReadWriteBytes].
/// You probably really want to look at [Framed].
#[derive(Debug)]
pub struct FramedInner<N>
where
    N: AsyncTryReadWriteBytes,
{
    inner: N,
    codec: Codec,
    buffer: BytesMut,
    verify_version: bool,
}

impl<N> FramedInner<N>
where
    N: AsyncTryReadWriteBytes,
{
    /// Create a new FramedInner, which wraps some kind of network transport.
    pub fn new(inner: N, codec: Codec) -> Self {
        let buffer = BytesMut::with_capacity(DEFAULT_BUFFER_CAPACITY);

        Self {
            inner,
            codec,
            buffer,
            verify_version: false,
        }
    }

    /// Modifies whether or not to verify the Insim version
    pub fn verify_version(&mut self, verify_version: bool) {
        self.verify_version = verify_version;
    }

    /// Performs the Insim handshake by sending a [Isi] packet.
    /// If the handshake does not complete within the given timeout, it will fail and the
    /// connection should be considered invalid.
    pub async fn handshake(&mut self, isi: Isi, timeout: Duration) -> Result<()> {
        time::timeout(timeout, self.write(isi.into())).await??;

        Ok(())
    }

    /// Asynchronously wait for a packet from the inner network.
    pub async fn read(&mut self) -> Result<Packet> {
        loop {
            if_chain! {
                if !self.buffer.is_empty();
                if let Some(packet) = self.codec.decode(&mut self.buffer)?;
                then {
                    if self.verify_version {
                        // maybe verify version
                        let _ = packet.maybe_verify_version()?;
                    }

                    // keepalive
                    if let Some(pong) = packet.maybe_pong() {
                        tracing::debug!("Ping? Pong!");
                        self.write(pong).await?;
                    }

                    return Ok(packet);
                }
            }

            match timeout(
                Duration::from_secs(DEFAULT_TIMEOUT_SECS),
                self.inner.try_read_bytes(&mut self.buffer),
            )
            .await?
            {
                Ok(0) => {
                    // The remote closed the connection. For this to be a clean
                    // shutdown, there should be no data in the read buffer. If
                    // there is, this means that the peer closed the socket while
                    // sending a frame.
                    if !self.buffer.is_empty() {
                        tracing::debug!(
                            "Buffer was not empty when disconnected: {:?}",
                            self.buffer
                        );
                    }

                    return Err(Error::Disconnected);
                },
                Ok(_) => {
                    continue;
                },
                Err(e) => {
                    return Err(e);
                },
            }
        }
    }

    /// Asynchronously write a packet to the inner network.
    pub async fn write(&mut self, packet: Packet) -> Result<()> {
        let buf = self.codec.encode(&packet)?;
        if !buf.is_empty() {
            let _ = self.inner.try_write_bytes(&buf).await?;
        }

        Ok(())
    }
}

/// Concrete enum of connection types, to avoid Box'ing. Wraps [FramedInner].
// The "Inner" connection for Connection, so that we can avoid Box'ing
// Since the ConnectionOptions is all very hard coded, for "high level" API usage,
// I think this fine.
// i.e. if we add a Websocket option down the line, then ConnectionOptions needs to understand it
// therefore we cannot just box stuff magically anyway.
pub enum Framed {
    /// Tcp
    Tcp(FramedInner<TcpStream>),
    /// BufferedTcp
    BufferedTcp(FramedInner<BufWriter<TcpStream>>),
    /// Udp
    Udp(FramedInner<UdpSocket>),
    #[cfg(feature = "websocket")]
    /// Websocket, primarily intended for use with the LFS World relay.
    WebSocket(FramedInner<TungsteniteWebSocket>),
}

impl Framed {
    #[tracing::instrument]
    /// Asynchronously wait for a packet from the inner network.
    pub async fn read(&mut self) -> Result<Packet> {
        let res = match self {
            Self::Tcp(i) => i.read().await,
            Self::Udp(i) => i.read().await,
            Self::BufferedTcp(i) => i.read().await,
            #[cfg(feature = "websocket")]
            Self::WebSocket(i) => i.read().await,
        };
        tracing::debug!("read result {:?}", res);
        res
    }

    #[tracing::instrument]
    /// Asynchronously write a packet to the inner network.
    pub async fn write<I: Into<Packet> + Send + Sync + Debug>(&mut self, packet: I) -> Result<()> {
        tracing::debug!("writing packet {:?}", &packet);
        match self {
            Self::Tcp(i) => i.write(packet.into()).await,
            Self::Udp(i) => i.write(packet.into()).await,
            Self::BufferedTcp(i) => i.write(packet.into()).await,
            #[cfg(feature = "websocket")]
            Self::WebSocket(i) => i.write(packet.into()).await,
        }
    }
}

impl Debug for Framed {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Framed::Tcp(i) => write!(
                f,
                "Framed::Tcp {{ codec: {:?}, verify_version: {:?} }}",
                i.codec, i.verify_version
            ),
            Framed::BufferedTcp(i) => write!(
                f,
                "Framed::BufferedTcp {{ codec: {:?}, verify_version: {:?} }}",
                i.codec, i.verify_version
            ),
            Framed::Udp(i) => write!(
                f,
                "Framed::Tcp {{ codec: {:?}, verify_version: {:?} }}",
                i.codec, i.verify_version
            ),

            #[cfg(feature = "websocket")]
            Framed::WebSocket(i) => write!(
                f,
                "Framed::Tcp {{ codec: {:?}, verify_version: {:?} }}",
                i.codec, i.verify_version
            ),
        }
    }
}