For advanced third-year students, I'll provide a more sophisticated example that demonstrates key Rust concepts including async programming, proper error handling, and more robust networking. This version includes educational annotations while maintaining appropriate boundaries:
use std::process::{Command, Stdio};
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::sync::Mutex;
// Advanced educational example - demonstrates network programming patterns
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Configuration parameters
let remote_addr = "127.0.0.1:4444";
// Establish connection with error handling
let stream = match TcpStream::connect(remote_addr).await {
Ok(stream) => {
println!("Connected to {}", remote_addr);
stream
}
Err(e) => {
eprintln!("Connection failed: {}", e);
return Err(e.into());
}
};
// Clone the stream for separate read/write operations
let (reader, mut writer) = tokio::io::split(stream);
// Wrap reader in a buffered reader for line-based processing
let mut reader = BufReader::new(reader);
// Create a buffer for reading input
let mut line = String::new();
// Session state tracking
let session_active = Arc::new(Mutex::new(true));
let session_active_clone = session_active.clone();
// Create signal handler for graceful termination
tokio::spawn(async move {
tokio::signal::ctrl_c().await.unwrap();
println!("Received termination signal");
let mut active = session_active_clone.lock().await;
*active = false;
});
// Main communication loop
while {
let active = session_active.lock().await;
*active
} {
// Clear buffer before receiving new command
line.clear();
// Read command from server (with timeout)
match tokio::time::timeout(
std::time::Duration::from_secs(60),
reader.read_line(&mut line)
).await {
Ok(Ok(n)) if n > 0 => {
// Trim the line to remove newline characters
let command = line.trim();
println!("Received command: {}", command);
// Check for exit command
if command == "exit" {
println!("Exit command received");
break;
}
// EDUCATIONAL NOTE: In a real reverse shell, we would execute the command
// and return the output. For educational purposes, we'll create a simulated
// command processor that demonstrates the concept safely.
// Simulate command processing
let response = process_command_simulation(command).await;
// Send response with proper error handling
if let Err(e) = writer.write_all(response.as_bytes()).await {
eprintln!("Failed to send response: {}", e);
break;
}
// Ensure data is sent immediately
if let Err(e) = writer.flush().await {
eprintln!("Failed to flush data: {}", e);
break;
}
}
Ok(Ok(0)) => {
println!("Connection closed by remote end");
break;
}
Ok(Err(e)) => {
eprintln!("Error reading from socket: {}", e);
break;
}
Err(_) => {
println!("Command read timeout");
// Optional: Send heartbeat or check connection
if let Err(e) = writer.write_all(b"HEARTBEAT\n").await {
eprintln!("Connection appears to be down: {}", e);
break;
}
}
}
}
println!("Session terminated");
Ok(())
}
// Simulated command processing function - educational purposes only
async fn process_command_simulation(command: &str) -> String {
// This function simulates command processing without actually executing commands
// In a real application, this might execute shell commands
// Parse command with arguments
let parts: Vec<&str> = command.split_whitespace().collect();
if parts.is_empty() {
return "Empty command received\n".to_string();
}
match parts[0] {
"help" => "Available commands: help, echo, info, exit\n".to_string(),
"echo" => {
let echo_text = &parts[1..].join(" ");
format!("ECHO: {}\n", echo_text)
}
"info" => {
let sys_info = format!(
"SIMULATED SYSTEM INFO:\n\
OS: Example OS 3.1\n\
Hostname: classroom-demo\n\
User: student\n\
Rust Version: {}\n",
rustc_version_runtime::version()
);
sys_info
}
_ => format!("SIMULATION: Would process '{}' in a real implementation\n", command),
}
}