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
/// Buffered reader for TLS parsing.
///
/// This reader uses `stream.read()` instead of `read_exact()` to ensure
/// cancellation safety. It maintains a buffer that can be retrieved even
/// if parsing fails, allowing the data to be replayed for other purposes.
use tokio::io::AsyncReadExt;
use tokio::net::TcpStream;
use crate::util::allocate_vec;
/// Maximum TLS frame size (5 byte header + 65535 byte payload)
const TLS_FRAME_MAX_LEN: usize = 5 + 65535;
pub struct TlsReader {
buf: Vec<u8>,
pos: usize,
end: usize,
}
impl TlsReader {
pub fn new() -> Self {
Self {
buf: allocate_vec(TLS_FRAME_MAX_LEN),
pos: 0,
end: 0,
}
}
/// Ensure at least `len` more bytes are buffered
pub async fn ensure_bytes(
&mut self,
stream: &mut TcpStream,
len: usize,
) -> std::io::Result<()> {
let needed = self.pos + len;
if needed > self.buf.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"Requested data exceeds buffer size".to_string(),
));
}
// Read until we have enough bytes
while self.end < needed {
// If buffer would be too small after compaction, error out
if needed - self.pos > self.buf.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Request too large for buffer",
));
}
// Compact buffer if needed
if self.end == self.buf.len() {
if self.pos == 0 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"Buffer full but need more data",
));
}
self.buf.copy_within(self.pos..self.end, 0);
self.end -= self.pos;
self.pos = 0;
}
loop {
match stream.read(&mut self.buf[self.end..]).await {
Ok(0) => {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"EOF while reading TLS data",
));
}
Ok(n) => {
self.end += n;
break;
}
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {
continue;
}
Err(e) => return Err(e),
}
}
}
Ok(())
}
/// Read a single u8
pub fn read_u8(&mut self) -> std::io::Result<u8> {
if self.pos >= self.end {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"buffer underflow",
));
}
let val = self.buf[self.pos];
self.pos += 1;
Ok(val)
}
/// Read a u16 in big-endian
pub fn read_u16_be(&mut self) -> std::io::Result<u16> {
if self.pos + 2 > self.end {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"buffer underflow",
));
}
let val = u16::from_be_bytes([self.buf[self.pos], self.buf[self.pos + 1]]);
self.pos += 2;
Ok(val)
}
/// Read a u24 in big-endian
pub fn read_u24_be(&mut self) -> std::io::Result<u32> {
if self.pos + 3 > self.end {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"buffer underflow",
));
}
let val = u32::from_be_bytes([
0,
self.buf[self.pos],
self.buf[self.pos + 1],
self.buf[self.pos + 2],
]);
self.pos += 3;
Ok(val)
}
/// Skip n bytes
pub fn skip(&mut self, n: usize) -> std::io::Result<()> {
if self.pos + n > self.end {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"buffer underflow",
));
}
self.pos += n;
Ok(())
}
/// Read a slice of bytes
pub fn read_slice(&mut self, len: usize) -> std::io::Result<&[u8]> {
if self.pos + len > self.end {
return Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"buffer underflow",
));
}
let slice = &self.buf[self.pos..self.pos + len];
self.pos += len;
Ok(slice)
}
/// Read a UTF-8 string
pub fn read_str(&mut self, len: usize) -> std::io::Result<&str> {
let slice = self.read_slice(len)?;
std::str::from_utf8(slice).map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("invalid UTF-8: {}", e),
)
})
}
/// Get the current position
pub fn position(&self) -> usize {
self.pos
}
/// Check if all data has been consumed
pub fn is_consumed(&self) -> bool {
self.pos >= self.end
}
/// Consume the reader and return the internal buffer and positions
/// Returns (buffer, position, end) where buffer[0..end] contains all read data
/// and buffer[position..end] contains unread data
pub fn into_inner(self) -> (Vec<u8>, usize, usize) {
(self.buf, self.pos, self.end)
}
}