use anyhow::{Result, Context}; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; use tracing::debug; /// RCON packet types const PACKET_LOGIN: i32 = 3; const PACKET_COMMAND: i32 = 2; const PACKET_RESPONSE: i32 = 0; /// A minimal Source RCON client. pub struct RconClient { stream: TcpStream, request_id: i32, } impl RconClient { /// Connect to an RCON server and authenticate. pub async fn connect(address: &str, password: &str) -> Result { let stream = TcpStream::connect(address) .await .context("Failed to connect to RCON")?; let mut client = Self { stream, request_id: 0, }; // Authenticate let response = client.send_packet(PACKET_LOGIN, password).await?; if response.id == -1 { anyhow::bail!("RCON authentication failed"); } debug!(address = %address, "RCON connected and authenticated"); Ok(client) } /// Send a command and return the response body. pub async fn command(&mut self, cmd: &str) -> Result { let response = self.send_packet(PACKET_COMMAND, cmd).await?; Ok(response.body) } async fn send_packet(&mut self, packet_type: i32, body: &str) -> Result { self.request_id += 1; let id = self.request_id; let body_bytes = body.as_bytes(); let length = 4 + 4 + body_bytes.len() + 2; // id + type + body + 2 null bytes // Write packet self.stream.write_i32_le(length as i32).await?; self.stream.write_i32_le(id).await?; self.stream.write_i32_le(packet_type).await?; self.stream.write_all(body_bytes).await?; self.stream.write_all(&[0, 0]).await?; // two null terminators self.stream.flush().await?; // Read response let resp_length = self.stream.read_i32_le().await?; let resp_id = self.stream.read_i32_le().await?; let resp_type = self.stream.read_i32_le().await?; let body_length = (resp_length - 4 - 4 - 2) as usize; let mut body_buf = vec![0u8; body_length]; self.stream.read_exact(&mut body_buf).await?; // Read two null terminators let mut null_buf = [0u8; 2]; self.stream.read_exact(&mut null_buf).await?; let response_body = String::from_utf8_lossy(&body_buf).to_string(); Ok(RconPacket { id: resp_id, packet_type: resp_type, body: response_body, }) } } struct RconPacket { id: i32, packet_type: i32, body: String, }