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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
//! Common utilities for this crate.

use std::io::Error;
use bytes::{Buf, BufMut, BytesMut};
use thiserror::Error;
use tokio::io::{AsyncRead, AsyncWrite};
use variable_len_reader::{AsyncVariableReader, AsyncVariableWriter};
use variable_len_reader::helper::{AsyncReaderHelper, AsyncWriterHelper};
use crate::config::get_max_packet_size;

/// Error when send/recv packets.
#[derive(Error, Debug)]
pub enum PacketError {
    /// The packet size is larger than the maximum allowed packet size.
    /// This is due to you sending too much data at once,
    /// resulting in triggering memory safety limit.
    ///
    /// You can reduce the size of data packet sent each time.
    /// Or you can change the maximum packet size by call [tcp_handler::config::set_config].
    #[error("Packet size {0} is larger than the maximum allowed packet size {1}.")]
    TooLarge(usize, usize),

    /// During io bytes.
    #[error("During io bytes.")]
    IO(#[from] Error),

    /// During encrypting/decrypting bytes.
    #[cfg(feature = "encryption")]
    #[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
    #[error("During encrypting/decrypting bytes.")]
    AES(#[from] aes_gcm::aead::Error),

    /// Broken stream cipher. This is a fatal error.
    ///
    /// When another error returned during send/recv, the stream is broken because no [Cipher] received.
    /// In order not to panic, marks this stream as broken and returns this error.
    #[cfg(feature = "encryption")]
    #[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
    #[error("Broken stream.")]
    Broken(),
}

/// Error when init/start protocol.
#[derive(Error, Debug)]
pub enum StarterError {
    /// [MAGIC_BYTES] isn't matched. Or the [MAGIC_VERSION] is no longer supported.
    /// Please confirm that you are connected to the correct address.
    #[error("Invalid stream. MAGIC is not matched.")]
    InvalidStream(),

    /// Incompatible tcp-handler protocol.
    /// The param came from the other side.
    /// Please check whether you use the same protocol between client and server.
    #[error("Incompatible protocol. received protocol: {0:?}")]
    InvalidProtocol(ProtocolVariant),

    /// Invalid application identifier.
    /// The param came from the other side.
    /// Please confirm that you are connected to the correct application,
    /// or that there are no spelling errors in the server and client identifiers.
    #[error("Invalid identifier. received: {0}")]
    InvalidIdentifier(String),

    /// Invalid application version.
    /// The param came from the other side.
    /// This is usually caused by the low version of the client application.
    #[error("Invalid version. received: {0}")]
    InvalidVersion(String),

    /// During io bytes.
    #[error("During io bytes.")]
    IO(#[from] Error),

    /// During generating/encrypting/decrypting rsa key.
    #[cfg(feature = "encryption")]
    #[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
    #[error("During generating/encrypting/decrypting rsa key.")]
    RSA(#[from] rsa::Error),
}


/// The MAGIC is generated in j-shell environment:
/// ```java
/// var r = new Random("tcp-handler".hashCode());
/// r.nextInt(0, 255); r.nextInt(0, 255);
/// r.nextInt(0, 255); r.nextInt(0, 255);
/// ```
static MAGIC_BYTES: [u8; 4] = [208, 8, 166, 104];

/// The version of the tcp-handler protocol.
///
/// | crate version | protocol version |
/// |---------------|------------------|
/// | \>=0.6.0      | 1                |
/// | <0.6.0        | 0                |
static MAGIC_VERSION: u16 = 1;

/// The variants of the protocol.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ProtocolVariant {
    /// See [crate::raw].
    Raw,
    /// See [crate::compress].
    Compression,
    /// See [crate::encrypt].
    Encryption,
    /// See [crate::compress_encrypt].
    CompressEncryption,
}

impl From<[bool; 2]> for ProtocolVariant {
    fn from(value: [bool; 2]) -> Self {
        match value {
            [false, false] => ProtocolVariant::Raw,
            [false, true] => ProtocolVariant::Compression,
            [true, false] => ProtocolVariant::Encryption,
            [true, true] => ProtocolVariant::CompressEncryption,
        }
    }
}

impl From<ProtocolVariant> for [bool; 2] {
    fn from(value: ProtocolVariant) -> Self {
        match value {
            ProtocolVariant::Raw => [false, false],
            ProtocolVariant::Compression => [false, true],
            ProtocolVariant::Encryption => [true, false],
            ProtocolVariant::CompressEncryption => [true, true],
        }
    }
}


/// In client side.
/// ```text
///   ┌─ Magic bytes
///   │     ┌─ Magic version
///   │     │    ┌─ Protocol variant
///   │     │    │    ┌─ Application identifier
///   │     │    │    │       ┌─ Application version
///   v     v    v    v       v
/// ┌─────┬────┬────┬───────┬───────┐
/// │ *** │ ** │ ** │ ***** │ ***** │
/// └─────┴────┴────┴───────┴───────┘
/// ```
pub(crate) async fn write_head<W: AsyncWrite + Unpin>(stream: &mut W, protocol: ProtocolVariant, identifier: &str, version: &str) -> Result<(), StarterError> {
    stream.write_more(&MAGIC_BYTES).await?;
    stream.write_u16_raw_be(MAGIC_VERSION).await?;
    stream.write_bools_2(protocol.into()).await?;
    AsyncWriterHelper(stream).help_write_string(identifier).await?;
    AsyncWriterHelper(stream).help_write_string(version).await?;
    Ok(())
}

/// In server side.
/// See [write_head].
pub(crate) async fn read_head<R: AsyncRead + Unpin, P: FnOnce(&str) -> bool>(stream: &mut R, protocol: ProtocolVariant, identifier: &str, version: P) -> Result<(u16, String), StarterError> {
    let mut magic = [0; 4];
    stream.read_more(&mut magic).await?;
    if magic != MAGIC_BYTES { return Err(StarterError::InvalidStream()); }
    let protocol_version = stream.read_u16_raw_be().await?;
    if protocol_version != MAGIC_VERSION { return Err(StarterError::InvalidStream()); }
    let protocol_read = stream.read_bools_2().await?.into();
    if protocol_read != protocol { return Err(StarterError::InvalidProtocol(protocol_read)); }
    let identifier_read = AsyncReaderHelper(stream).help_read_string().await?;
    if identifier_read != identifier { return Err(StarterError::InvalidIdentifier(identifier_read)); }
    let version_read = AsyncReaderHelper(stream).help_read_string().await?;
    if !version(&version_read) { return Err(StarterError::InvalidVersion(version_read)); }
    Ok((protocol_version, version_read))
}

/// In server side.
/// ```text
///   ┌─ State bytes
///   │   ┌─ Error information.
///   v   v
/// ┌───┬───────┐
/// │ * │ ***** │
/// └───┴───────┘
/// ```
pub(crate) async fn write_last<W: AsyncWrite + Unpin, E>(stream: &mut W, protocol: ProtocolVariant, identifier: &str, version: &str, last: Result<E, StarterError>) -> Result<E, StarterError> {
    match last {
        Err(e) => {
            match &e {
                StarterError::InvalidProtocol(_) => {
                    stream.write_bools_2([false, false]).await?;
                    stream.write_bools_2(protocol.into()).await?;
                }
                StarterError::InvalidIdentifier(_) => {
                    stream.write_bools_2([false, true]).await?;
                    AsyncWriterHelper(stream).help_write_string(identifier).await?;
                }
                StarterError::InvalidVersion(_) => {
                    stream.write_bools_2([true, false]).await?;
                    AsyncWriterHelper(stream).help_write_string(version).await?;
                }
                _ => {}
            }
            return Err(e);
        },
        Ok(k) => {
            stream.write_bools_2([true, true]).await?;
            Ok(k)
        }
    }
}

/// In client side.
/// See [write_last].
pub(crate) async fn read_last<R: AsyncRead + Unpin, E>(stream: &mut R, last: Result<E, StarterError>) -> Result<E, StarterError> {
    let extra = last?;
    match stream.read_bools_2().await? {
        [true, true] => Ok(extra),
        [false, false] => Err(StarterError::InvalidProtocol(stream.read_bools_2().await?.into())),
        [false, true] => Err(StarterError::InvalidIdentifier(AsyncReaderHelper(stream).help_read_string().await?)),
        [true, false] => Err(StarterError::InvalidVersion(AsyncReaderHelper(stream).help_read_string().await?)),
    }
}


#[inline]
fn check_bytes_len(len: usize) -> Result<(), PacketError> {
    let config = get_max_packet_size();
    if len > config { Err(PacketError::TooLarge(len, config)) } else { Ok(()) }
}

/// ```text
///   ┌─ Packet length (in varint)
///   │    ┌─ Packet message
///   v    v
/// ┌────┬────────┐
/// │ ** │ ****** │
/// └────┴────────┘
/// ```
pub(crate) async fn write_packet<W: AsyncWrite + Unpin, B: Buf>(stream: &mut W, bytes: &mut B) -> Result<(), PacketError> {
    check_bytes_len(bytes.remaining())?;
    stream.write_usize_varint_ap(bytes.remaining()).await?;
    stream.write_more_buf(bytes).await?;
    Ok(())
}

/// See [write_packet].
pub(crate) async fn read_packet<R: AsyncRead + Unpin>(stream: &mut R) -> Result<BytesMut, PacketError> {
    let len = stream.read_usize_varint_ap().await?;
    check_bytes_len(len)?;
    let mut buf = BytesMut::with_capacity(len).limit(len);
    stream.read_more_buf(&mut buf).await?;
    Ok(buf.into_inner())
}


#[cfg(feature = "encryption")]
pub(crate) fn generate_rsa_private() -> Result<(rsa::RsaPrivateKey, Vec<u8>, Vec<u8>), StarterError> {
    use rsa::traits::PublicKeyParts;
    let key = rsa::RsaPrivateKey::new(&mut rand::thread_rng(), 2048)?;
    let n = key.n().to_bytes_le();
    let e = key.e().to_bytes_le();
    Ok((key, n, e))
}

#[cfg(feature = "encryption")]
pub(crate) fn compose_rsa_public(n: Vec<u8>, e: Vec<u8>) -> Result<rsa::RsaPublicKey, StarterError> {
    let n = rsa::BigUint::from_bytes_le(&n);
    let e = rsa::BigUint::from_bytes_le(&e);
    Ok(rsa::RsaPublicKey::new(n, e)?)
}

/// The cipher in encryption mode.
/// You **must** update this value after each call to the send/recv function.
#[cfg(feature = "encryption")]
pub(crate) type InnerAesCipher = (aes_gcm::Aes256Gcm, aes_gcm::Nonce<aes_gcm::aead::consts::U12>);

/// The cipher in encryption mode.
#[cfg(feature = "encryption")]
#[cfg_attr(docsrs, doc(cfg(feature = "encryption")))]
pub struct Cipher {
    cipher: std::sync::Mutex<Option<InnerAesCipher>>,
}

#[cfg(feature = "encryption")]
impl std::fmt::Debug for Cipher {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Cipher")
            .field("cipher", &self.cipher.try_lock()
                .map_or_else(|_| "<locked>",
                             |inner| if (*inner).is_some() { "<unlocked>" } else { "<broken>" }))
            .finish()
    }
}

#[cfg(feature = "encryption")]
impl Cipher {
    #[inline]
    pub(crate) fn new(cipher: InnerAesCipher) -> Self {
        Self {
            cipher: std::sync::Mutex::new(Some(cipher))
        }
    }

    #[inline]
    pub(crate) fn get(&self) -> Result<(InnerAesCipher, std::sync::MutexGuard<Option<InnerAesCipher>>), PacketError> {
        let mut guard = self.cipher.lock().unwrap();
        let cipher = (*guard).take().ok_or(PacketError::Broken())?;
        Ok((cipher, guard))
    }

    #[inline]
    pub(crate) fn reset(mut guard: std::sync::MutexGuard<Option<InnerAesCipher>>, cipher: InnerAesCipher) {
        (*guard).replace(cipher);
    }
}


#[cfg(test)]
pub(crate) mod tests {
    use anyhow::Result;
    use bytes::{Buf, Bytes};
    use tokio::io::{AsyncRead, AsyncWrite, duplex};
    use crate::common::{read_packet, write_packet};

    pub(crate) async fn create() -> Result<(impl AsyncRead + AsyncWrite + Unpin, impl AsyncRead + AsyncWrite + Unpin)> {
        let (client, server) = duplex(1024);
        Ok((client, server))
    }

    #[tokio::test]
    async fn packet() -> Result<()> {
        let (mut client, mut server) = create().await?;

        let source = &[1, 2, 3, 4, 5];
        write_packet(&mut client, &mut Bytes::from_static(source)).await?;
        let res = read_packet(&mut server).await?;
        assert_eq!(source, res.chunk());

        Ok(())
    }
}