Prevent Denial-of-Service in Rust by enforcing strict input limits and using non-blocking I/O to avoid resource exhaustion.
use std::io::{self, Read};
use std::time::Duration;
fn read_safe(input: &mut impl Read) -> io::Result<Vec<u8>> {
let mut buffer = Vec::with_capacity(1024 * 1024); // Limit to 1MB
let mut timeout = Duration::from_secs(5);
// Note: Actual timeout requires async runtime or platform-specific APIs
// This example demonstrates the capacity limit principle
let bytes_read = input.read_to_end(&mut buffer)?;
if bytes_read > 1024 * 1024 {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "Input too large"));
}
Ok(buffer)
}
- Set a maximum buffer size to prevent memory exhaustion.
- Validate input length immediately after reading.
- Reject requests exceeding the limit with an error.
- Use async runtimes like
tokiofor non-blocking I/O timeouts.