Spaces:
Running
Running
File size: 8,240 Bytes
bb6d3c1 | 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 | //! Protocol Codec Implementation
//!
//! Tokio codec for encoding/decoding frames with the binary protocol.
use bytes::{Buf, BytesMut};
use crc32fast::Hasher;
use lz4_flex::{compress_prepend_size, decompress_size_prepended};
use std::io;
use tokio_util::codec::{Decoder, Encoder};
use super::wire::{Frame, FrameHeader, HEADER_SIZE, MAGIC_HEADER};
use tracing::trace;
/// Maximum size (bytes) of a *decompressed* frame body.
///
/// The wire `body_length` only bounds the on-the-wire (possibly compressed)
/// size. An attacker can send a tiny compressed payload that declares a huge
/// uncompressed size via the LZ4 prepended length prefix, causing the server
/// to allocate that much memory (decompression bomb / OOM DoS). We cap the
/// decompressed output to bound that allocation.
pub const MAX_DECOMPRESSED_SIZE: usize = 64 * 1024 * 1024; // 64 MB
/// Codec for the memory protocol
pub struct MemoryProtocolCodec {
/// Enable compression for bodies > 1KB
enable_compression: bool,
/// Maximum frame size (16MB default)
max_frame_size: usize,
}
impl MemoryProtocolCodec {
/// Create a new codec
pub fn new() -> Self {
Self {
enable_compression: true,
max_frame_size: 16 * 1024 * 1024, // 16MB
}
}
/// Create codec with custom settings
pub fn with_config(enable_compression: bool, max_frame_size: usize) -> Self {
Self {
enable_compression,
max_frame_size,
}
}
/// Compress body if needed
fn maybe_compress(&self, body: &[u8]) -> (Vec<u8>, bool) {
if self.enable_compression && body.len() > 1024 {
let compressed = compress_prepend_size(body);
// Only use compression if it actually reduces size
if compressed.len() < body.len() {
return (compressed, true);
}
}
(body.to_vec(), false)
}
/// Decompress body if needed
fn maybe_decompress(&self, body: &[u8], is_compressed: bool) -> io::Result<Vec<u8>> {
if is_compressed {
let decompressed = decompress_size_prepended(body)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
if decompressed.len() > MAX_DECOMPRESSED_SIZE {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"Decompressed frame too large: {} bytes (max {})",
decompressed.len(),
MAX_DECOMPRESSED_SIZE
),
));
}
Ok(decompressed)
} else {
if body.len() > MAX_DECOMPRESSED_SIZE {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"Frame body too large: {} bytes (max {})",
body.len(),
MAX_DECOMPRESSED_SIZE
),
));
}
Ok(body.to_vec())
}
}
/// Calculate CRC32 checksum
fn calculate_checksum(data: &[u8]) -> u32 {
let mut hasher = Hasher::new();
hasher.update(data);
hasher.finalize()
}
}
impl Default for MemoryProtocolCodec {
fn default() -> Self {
Self::new()
}
}
impl Decoder for MemoryProtocolCodec {
type Item = Frame;
type Error = io::Error;
fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
// Need at least header size
if src.len() < HEADER_SIZE {
return Ok(None);
}
// Peek at header to get body length
let body_length = {
let mut peek = src.clone();
// Validate magic
let magic = peek.get_u32();
if magic != MAGIC_HEADER {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("Invalid magic header: {:08x}", magic),
));
}
// Skip to body length field (at offset 23)
peek.advance(19); // skip version(1) + type(1) + flags(1) + message_id(16)
peek.get_u64() as usize
};
// Check frame size limit
if body_length > self.max_frame_size {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!("Frame too large: {} bytes", body_length),
));
}
// Wait for complete frame
if src.len() < HEADER_SIZE + body_length {
src.reserve(HEADER_SIZE + body_length - src.len());
return Ok(None);
}
// Parse header
let header = FrameHeader::read_from(src)?
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "Failed to parse header"))?;
// Extract body
let mut body = src.split_to(body_length).to_vec();
// Verify checksum if present
if header.has_checksum() {
if body.len() < 4 {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"Body too short for checksum",
));
}
let expected_crc = u32::from_le_bytes([body[0], body[1], body[2], body[3]]);
body = body[4..].to_vec();
let actual_crc = Self::calculate_checksum(&body);
if expected_crc != actual_crc {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"CRC mismatch: expected {:08x}, got {:08x}",
expected_crc, actual_crc
),
));
}
}
// Decompress if needed
body = self.maybe_decompress(&body, header.is_compressed())?;
trace!("Decoded frame type: {:?}", header.message_type);
Ok(Some(Frame { header, body }))
}
}
impl Encoder<Frame> for MemoryProtocolCodec {
type Error = io::Error;
fn encode(&mut self, item: Frame, dst: &mut BytesMut) -> Result<(), Self::Error> {
let mut header = item.header;
let mut body = item.body;
trace!("Encoding frame type: {:?}", header.message_type);
// Compress if beneficial
let (compressed_body, was_compressed) = self.maybe_compress(&body);
if was_compressed {
body = compressed_body;
header.set_compressed();
}
// Calculate checksum
let checksum = Self::calculate_checksum(&body);
header.set_checksum();
// Update body length (checksum + body)
header.body_length = (4 + body.len()) as u64;
// Reserve space
dst.reserve(HEADER_SIZE + 4 + body.len());
// Write header
header.write_to(dst);
// Write checksum (little-endian)
dst.extend_from_slice(&checksum.to_le_bytes());
// Write body
dst.extend_from_slice(&body);
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::protocol::MessageType;
#[test]
fn test_encode_decode_roundtrip() {
let mut codec = MemoryProtocolCodec::new();
let original = Frame::new(MessageType::Store, b"test data".to_vec());
let mut buf = BytesMut::new();
codec.encode(original.clone(), &mut buf).unwrap();
let decoded = codec.decode(&mut buf).unwrap().unwrap();
assert_eq!(decoded.body, b"test data");
assert_eq!(decoded.header.message_type, MessageType::Store);
}
#[test]
fn test_compression() {
let mut codec = MemoryProtocolCodec::new();
// Large body that should be compressed
let body = vec![b'a'; 2048];
let original = Frame::new(MessageType::Store, body.clone());
let mut buf = BytesMut::new();
codec.encode(original, &mut buf).unwrap();
// Verify compression happened (buffer should be smaller)
assert!(buf.len() < 2048 + HEADER_SIZE);
// Decode and verify body matches
let decoded = codec.decode(&mut buf).unwrap().unwrap();
assert_eq!(decoded.body, body);
}
}
|