Improve RCON

Remove all unwraps when handling packets. Also improve split Packets into Client & Server bound removing ugly match statement where we are reading Clientboud Packets (which is impossible).
This commit is contained in:
Alexander Medvedev committed 2024-10-07 23:00:25 +01:00
1 parent 5e45ebac33
commit 2194f14981
5 files changed
+277 -300

No files matched your search

+28 -22
View File
@@ -1,6 +1,6 @@
use std::{
collections::HashMap,
io::{self, Read},
io::{self, Read, Write},
sync::Arc,
};
@@ -8,7 +8,7 @@ use mio::{
net::{TcpListener, TcpStream},
Events, Interest, Poll, Token,
};
use packet::{Packet, PacketError, PacketType};
use packet::{ClientboundPacket, Packet, PacketError, ServerboundPacket};
use pumpkin_config::RCONConfig;
use thiserror::Error;
@@ -72,6 +72,12 @@ impl RCONServer {
}
};
log::info!("Accepted connection from: {}", address);
if config.max_connections != 0
&& connections.len() >= config.max_connections as usize
{
log::warn!("Max RCON connections reached");
break;
}
let token = Self::next(&mut unique_token);
poll.registry()
@@ -156,27 +162,21 @@ impl RCONClient {
};
match packet.get_type() {
PacketType::Auth => {
ServerboundPacket::Auth => {
let body = packet.get_body();
if !body.is_empty() && packet.get_body() == password {
self.send(&mut Packet::new(
packet.get_id(),
PacketType::AuthResponse,
"".into(),
))
.await
.unwrap();
self.send(ClientboundPacket::AuthResponse, packet.get_id(), "".into())
.await?;
log::info!("RCON Client logged in successfully");
self.logged_in = true;
} else {
log::warn!("RCON Client has tried wrong password");
self.send(&mut Packet::new(-1, PacketType::AuthResponse, "".into()))
.await
.unwrap();
return Err(PacketError::WrongPassword);
self.send(ClientboundPacket::AuthResponse, -1, "".into())
.await?;
self.closed = true;
}
}
PacketType::ExecCommand => {
ServerboundPacket::ExecCommand => {
if self.logged_in {
let mut output = Vec::new();
let dispatcher = server.command_dispatcher.clone();
@@ -186,14 +186,11 @@ impl RCONClient {
packet.get_body(),
);
for line in output {
self.send(&mut Packet::new(packet.get_id(), PacketType::Output, line))
.await
.unwrap();
self.send(ClientboundPacket::Output, packet.get_id(), line)
.await?;
}
}
}
PacketType::Output => todo!(),
PacketType::AuthResponse => unreachable!(),
}
}
}
@@ -208,8 +205,17 @@ impl RCONClient {
Ok(false)
}
async fn send(&mut self, packet: &mut Packet) -> io::Result<()> {
packet.send_packet(&mut self.connection).await
async fn send(
&mut self,
packet: ClientboundPacket,
id: i32,
body: String,
) -> Result<(), PacketError> {
let buf = packet.write_buf(id, body);
self.connection
.write(&buf)
.map_err(PacketError::FailedSend)?;
Ok(())
}
async fn receive_packet(&mut self) -> Result<Option<Packet>, PacketError> {
+67 -60
View File
@@ -1,91 +1,98 @@
use std::io::{self, BufRead, Cursor, Write};
use std::{
io::{BufRead, Cursor},
string::FromUtf8Error,
};
use bytes::{BufMut, BytesMut};
use mio::net::TcpStream;
use thiserror::Error;
use tokio::io::AsyncReadExt;
/// Client -> Server
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PacketType {
Auth,
AuthResponse,
ExecCommand,
Output,
#[repr(i32)]
pub enum ServerboundPacket {
/// Typically, the first packet sent by the client, which is used to authenticate the connection with the server.
Auth = 2,
/// This packet type represents a command issued to the server by a client. This can be a ConCommand such as kill <player> or weather clear.
/// The response will vary depending on the command issued.
ExecCommand = 3,
}
impl ServerboundPacket {
pub fn from_i32(n: i32) -> Self {
match n {
3 => Self::Auth,
2 => Self::ExecCommand,
_ => Self::Auth,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(i32)]
/// Server -> Client
pub enum ClientboundPacket {
/// This packet is a notification of the connection's current auth status. When the server receives an auth request, it will respond with an empty SERVERDATA_RESPONSE_VALUE,
/// followed immediately by a SERVERDATA_AUTH_RESPONSE indicating whether authentication succeeded or failed. Note that the status code is returned in the packet id field, so when pairing the response with the original auth request, you may need to look at the packet id of the preceeding SERVERDATA_RESPONSE_VALUE.
AuthResponse = 2,
/// A SERVERDATA_RESPONSE packet is the response to a SERVERDATA_EXECCOMMAND request.
Output = 0,
}
impl ClientboundPacket {
pub fn write_buf(&self, id: i32, body: String) -> BytesMut {
// let len = outgoing.len() as u64;
let mut buf = BytesMut::new();
// 10 is for 4 bytes ty, 4 bytes id, and 2 terminating nul bytes.
buf.put_i32_le(10 + body.len() as i32);
buf.put_i32_le(id);
buf.put_i32_le(*self as i32);
let bytes = body.as_bytes();
buf.put_slice(bytes);
buf.put_u8(0);
buf.put_u8(0);
buf
}
}
#[derive(Error, Debug)]
pub enum PacketError {
#[error("invalid length")]
InvalidLength,
#[error("expected terminating NUL byte")]
NoNullTermination,
#[error("wrong password")]
WrongPassword,
}
impl PacketType {
fn to_i32(self) -> i32 {
match self {
PacketType::Auth => 3,
PacketType::AuthResponse => 2,
PacketType::ExecCommand => 2,
PacketType::Output => 0,
}
}
pub fn from_i32(n: i32) -> PacketType {
match n {
3 => PacketType::Auth,
2 => PacketType::ExecCommand,
_ => PacketType::Output,
}
}
#[error("failed to read packet")]
FailedRead(std::io::Error),
#[error("failed to send packet")]
FailedSend(std::io::Error),
#[error("invalid Packet String body")]
InvalidBody(FromUtf8Error),
}
#[derive(Debug)]
/// Serverbound Packet
pub struct Packet {
id: i32,
ptype: PacketType,
ptype: ServerboundPacket,
body: String,
}
impl Packet {
pub fn new(id: i32, ptype: PacketType, body: String) -> Packet {
Packet { id, ptype, body }
}
pub async fn send_packet(&mut self, connection: &mut TcpStream) -> io::Result<()> {
// let len = outgoing.len() as u64;
let mut buf = BytesMut::new();
// 10 is for 4 bytes ty, 4 bytes id, and 2 terminating nul bytes.
buf.put_i32_le(10 + self.get_body().len() as i32);
buf.put_i32_le(self.id);
buf.put_i32_le(self.get_type().to_i32());
let bytes = self.get_body().as_bytes();
buf.put_slice(bytes);
buf.put_u8(0);
buf.put_u8(0);
let _ = connection.write(&buf).unwrap();
Ok(())
}
pub async fn deserialize(incoming: &mut Vec<u8>) -> Result<Option<Packet>, PacketError> {
if incoming.len() < 4 {
return Ok(None);
}
let mut buf = Cursor::new(&incoming);
let len = buf.read_i32_le().await.unwrap() + 4;
let len = buf.read_i32_le().await.map_err(PacketError::FailedRead)? + 4;
if !(0..=1460).contains(&len) {
return Err(PacketError::InvalidLength);
}
let id = buf.read_i32_le().await.unwrap();
let ty = buf.read_i32_le().await.unwrap();
let id = buf.read_i32_le().await.map_err(PacketError::FailedRead)?;
let ty = buf.read_i32_le().await.map_err(PacketError::FailedRead)?;
let mut payload = vec![];
let _ = buf.read_until(b'\0', &mut payload).unwrap();
let _ = buf
.read_until(b'\0', &mut payload)
.map_err(PacketError::FailedRead)?;
payload.pop();
if buf.read_u8().await.unwrap() != 0 {
return Err(PacketError::NoNullTermination);
}
buf.read_u8().await.map_err(PacketError::FailedRead)?;
if buf.position() != len as u64 {
return Err(PacketError::InvalidLength);
}
@@ -93,8 +100,8 @@ impl Packet {
let packet = Packet {
id,
ptype: PacketType::from_i32(ty),
body: String::from_utf8(payload).unwrap(),
ptype: ServerboundPacket::from_i32(ty),
body: String::from_utf8(payload).map_err(PacketError::InvalidBody)?,
};
Ok(Some(packet))
@@ -103,7 +110,7 @@ impl Packet {
&self.body
}
pub fn get_type(&self) -> PacketType {
pub fn get_type(&self) -> ServerboundPacket {
self.ptype
}