mid-net 1.0.0

Network adapter for the `middleware` protocol implementation
Documentation
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use std::{
    future::Future,
    io::{
        self,
        IoSlice,
    },
};

use mid_compression::interface::ICompressor;
use tokio::io::{
    AsyncWrite,
    AsyncWriteExt,
    BufWriter,
};

use crate::{
    compression::{
        CompressionAlgorithm,
        CompressionStatus,
        ForwardCompression,
    },
    proto::{
        PacketType,
        ProtocolError,
    },
    utils::{
        encode_fwd_header,
        encode_type,
        flags,
        ident_type,
        FancyUtilExt,
    },
};

pub struct MidClientWriter<'a, W, C> {
    inner: &'a mut MidWriter<W, C>,
}

pub struct MidServerWriter<'a, W, C> {
    inner: &'a mut MidWriter<W, C>,
}

/// Write side of the `Middleware` protocol
pub struct MidWriter<W, C> {
    inner: W,
    compressor: C,
}

impl<'a, W, C> MidClientWriter<'a, W, C>
where
    W: AsyncWriteExt + Unpin,
{
    /// Write ping request to the server
    pub fn write_ping(&mut self) -> impl Future<Output = io::Result<()>> + '_ {
        self.inner
            .write_u8(ident_type(PacketType::Ping as u8))
    }
}

impl<'a, W, C> MidServerWriter<'a, W, C>
where
    W: AsyncWriteExt + Unpin,
{
    /// Write connected packet
    pub fn write_connected(
        &mut self,
        id: u16,
    ) -> impl Future<Output = io::Result<()>> + '_ {
        self.inner
            .write_client_id(id, PacketType::Connect)
    }

    /// Writes port of the created server to the client.
    pub async fn write_server(&mut self, port: u16) -> io::Result<()> {
        self.inner
            .write_all(&[
                ident_type(PacketType::CreateServer as u8),
                (port & 0xff) as u8,
                (port >> 8) as u8,
            ])
            .await
    }

    /// Writes `update rights` packet to the client.
    pub async fn write_update_rights(
        &mut self,
        new_rights: u16,
    ) -> io::Result<()> {
        if new_rights <= 0xff {
            self.inner
                .write_all(&[
                    encode_type(PacketType::UpdateRights as u8, flags::SHORT),
                    new_rights as u8,
                ])
                .await
        } else {
            self.inner
                .write_all(&[
                    ident_type(PacketType::UpdateRights as u8),
                    (new_rights & 0xff) as u8,
                    (new_rights >> 8) as u8,
                ])
                .await
        }
    }

    /// Write failure packet to the client. Indicates that
    /// something was gone wrong.
    pub async fn write_failure(
        &mut self,
        error: impl Into<ProtocolError>,
    ) -> io::Result<()> {
        self.inner
            .write_all(&[
                ident_type(PacketType::Failure as u8),
                error.into() as u8,
            ])
            .await
    }

    /// Write ping response to the client.
    pub async fn write_ping(
        &mut self,
        server_name: &str,
        algorithm: CompressionAlgorithm,
        buffer_size: u16,
    ) -> io::Result<()> {
        self.inner
            .write_two_bufs(
                &[
                    ident_type(PacketType::Ping as u8),
                    algorithm as u8,
                    (buffer_size & 0xff) as u8,
                    (buffer_size >> 8) as u8,
                    server_name.len().try_into().expect(
                        "length of `server_name is greater than `u8::MAX`",
                    ),
                ],
                server_name.as_bytes(),
            )
            .await
            .unitize_io()
    }
}

// Common writer methods

impl<W, C> MidWriter<W, C>
where
    W: AsyncWriteExt + Unpin,
    C: ICompressor,
{
    async fn write_forward_impl(
        &mut self,
        client_id: u16,
        buffer: &[u8],
        compressed: bool,
    ) -> io::Result<()> {
        let (header, header_size) = encode_fwd_header(
            client_id,
            buffer
                .len()
                .try_into()
                .expect("Buffer size exceeds `u16::MAX`"),
            compressed,
        );
        self.write_two_bufs(&header[..header_size], buffer)
            .await
            .unitize_io()
    }

    /// Write forward packet to the destination socket.
    pub async fn write_forward(
        &mut self,
        client_id: u16,
        buffer: &[u8],
        compression: ForwardCompression,
    ) -> io::Result<CompressionStatus> {
        fn uncompressed(in_: io::Result<()>) -> io::Result<CompressionStatus> {
            in_.map(|()| CompressionStatus::Uncompressed)
        }

        match compression {
            ForwardCompression::Compress { with_threshold }
                if with_threshold <= buffer.len() =>
            {
                let mut preallocated = Vec::with_capacity(buffer.len());
                if let Ok(compressed) = self
                    .compressor
                    .try_compress(buffer, &mut preallocated)
                {
                    if compressed.get() > buffer.len() {
                        // Yeah, this is possible
                        uncompressed(
                            self.write_forward_impl(client_id, buffer, false)
                                .await,
                        )
                    } else {
                        let status = CompressionStatus::Compressed {
                            before: buffer.len(),
                            after: compressed.get(),
                        };

                        self.write_forward_impl(client_id, buffer, true)
                            .await
                            .map(move |()| status)
                    }
                } else {
                    uncompressed(
                        self.write_forward_impl(client_id, buffer, false)
                            .await,
                    )
                }
            }
            _ => uncompressed(
                self.write_forward_impl(client_id, buffer, false)
                    .await,
            ),
        }
    }
}

impl<W, C> MidWriter<W, C>
where
    W: AsyncWriteExt + Unpin,
{
    /// Write disconnect packet to the destination socket
    pub fn write_disconnected(
        &mut self,
        id: u16,
    ) -> impl Future<Output = io::Result<()>> + '_ {
        self.write_client_id(id, PacketType::Disconnect)
    }

    pub(crate) async fn write_client_id(
        &mut self,
        id: u16,
        pkt_type: PacketType,
    ) -> io::Result<()> {
        let mut buf = [0; 3];
        let (length, flags) = if id <= 0xff {
            buf[1] = id as u8;
            (2, flags::SHORT_CLIENT)
        } else {
            buf[1] = (id & 0xff) as u8;
            buf[2] = (id >> 8) as u8;
            (3, 0)
        };

        buf[0] = encode_type(pkt_type as u8, flags);

        self.write_all(&buf[..length]).await
    }

    /// Write two buffers to the socket in vectored mode.
    ///
    /// Returns
    /// - Ok(true) if buffer was wrote using efficient
    ///   implementation (without allocating buffer with
    ///   size before.len() + after.len())
    /// - Ok(false) if buffer was wrote using the fallback
    ///   way (allocating buffer with size before.len() +
    ///   after.len() and copying data to it)
    pub async fn write_two_bufs(
        &mut self,
        before: &[u8],
        after: &[u8],
    ) -> io::Result<bool> {
        let (blen, alen) = (before.len(), after.len());
        let total = blen + alen;

        if !self.inner.is_write_vectored() {
            let mut buf = Vec::with_capacity(total);

            // SAFETY: this is safe since `Vec::with_capacity` will
            // return buffer with at least `total` capacity and its data
            // will be initialized.
            // Possibly it can be done better? Without buffer
            // pre-filling
            unsafe {
                std::ptr::copy_nonoverlapping(
                    before.as_ptr(),
                    buf.as_mut_ptr(),
                    before.len(),
                );

                std::ptr::copy_nonoverlapping(
                    after.as_ptr(),
                    buf.as_mut_ptr()
                        .offset(before.len().try_into().expect(
                            "Failed to copy to a single buffer: too long \
                             `before` buffer size",
                        )),
                    after.len(),
                );

                buf.set_len(total);
            };

            self.inner.write_all(&buf).await?;
            return Ok(false);
        }

        let mut written: usize = 0;
        let mut ios = [IoSlice::new(before), IoSlice::new(after)];

        loop {
            let wrote = self.inner.write_vectored(&ios).await?;
            written += wrote;

            if written < total {
                if written >= blen {
                    break self
                        .inner
                        .write_all(&after[(written - blen)..])
                        .await
                        .map(|_| true);
                }

                ios[0] = IoSlice::new(&before[written..]);
            } else {
                break Ok(true);
            }
        }
    }

    /// Writes entire buffer into the socket
    pub fn write_all<'a>(
        &'a mut self,
        buf: &'a [u8],
    ) -> impl Future<Output = io::Result<()>> + 'a {
        self.inner.write_all(buf)
    }

    /// Same as [`MidWriter::write_u32`] but writes u32
    /// (little endian)
    pub fn write_u32(
        &mut self,
        v: u32,
    ) -> impl Future<Output = io::Result<()>> + '_ {
        self.inner.write_u32_le(v)
    }

    /// Same as [`MidWriter::write_u8`] but writes u16
    /// (little endian)
    pub fn write_u16(
        &mut self,
        v: u16,
    ) -> impl Future<Output = io::Result<()>> + '_ {
        self.inner.write_u16_le(v)
    }

    /// Write u8 to the destination socket (or possibly to
    /// buffer)
    pub fn write_u8(
        &mut self,
        v: u8,
    ) -> impl Future<Output = io::Result<()>> + '_ {
        self.inner.write_u8(v)
    }
}

// Bufferization & creation related stuff

impl<W, C> MidWriter<BufWriter<W>, C>
where
    W: AsyncWrite + Unpin,
{
    /// Flush underlying write buffer, so remote side will
    /// receive buffered bytes immediately
    pub fn flush(&mut self) -> impl Future<Output = io::Result<()>> + '_ {
        self.inner.flush()
    }
}

impl<W, C> MidWriter<BufWriter<W>, C>
where
    W: AsyncWrite,
{
    /// Create buffered writer.
    pub fn new_buffered(socket: W, compressor: C, buffer_size: usize) -> Self {
        Self {
            inner: BufWriter::with_capacity(buffer_size, socket),
            compressor,
        }
    }

    /// Remove bufferization from the writer.
    ///
    /// WARNING: it is neccessary to call
    /// [`MidWriter::flush`] before the unbuffering so
    /// you're sure that previously buffered data was wrote
    pub fn unbuffer(self) -> MidWriter<W, C> {
        MidWriter {
            inner: self.inner.into_inner(),
            compressor: self.compressor,
        }
    }
}

impl<W, C> MidWriter<W, C>
where
    W: AsyncWrite,
{
    /// Make writer buffered
    pub fn make_buffered(
        self,
        buffer_size: usize,
    ) -> MidWriter<BufWriter<W>, C> {
        MidWriter::new_buffered(self.inner, self.compressor, buffer_size)
    }
}

impl<W, C> MidWriter<W, C> {
    /// Create client packets writer. Used mainly to
    /// incapsulate client and server packets
    pub fn client(&mut self) -> MidClientWriter<'_, W, C> {
        MidClientWriter { inner: self }
    }

    /// Same as [`MidWriter::client`] but for server packets
    pub fn server(&mut self) -> MidServerWriter<'_, W, C> {
        MidServerWriter { inner: self }
    }

    /// Get shared access to the underlying socket.
    pub const fn socket(&self) -> &W {
        &self.inner
    }

    /// Get exclusive access to the underlying socket.
    pub fn socket_mut(&mut self) -> &mut W {
        &mut self.inner
    }

    /// Simply create writer from the underlying socket
    pub const fn new(socket: W, compressor: C) -> Self {
        Self {
            inner: socket,
            compressor,
        }
    }
}