1use std::io::{Read, Write};
17use std::net::TcpStream;
18
19use crate::{DmError, Result};
20
21pub const FRAME_HEADER_LEN: usize = 64;
22pub const CMD_HANDSHAKE: i16 = 200;
23pub const CMD_LOGIN: i16 = 1;
24pub const CMD_SESSION_QUERY: i16 = 3;
25pub const CMD_EXECUTE: i16 = 5;
26pub const CMD_EXEC_COMPLETE: i16 = 4;
27pub const CMD_FETCH: i16 = 44;
28pub const CMD_BIND: i16 = 13;
29pub const MAX_MSG_LEN: usize = 0x2000_0000;
30
31pub fn make_header(stmt_id: i32, cmd: i16, body_len: u32, opts: &[u8]) -> [u8; 64] {
33 debug_assert!(opts.len() <= 44, "参数区最大 44 字节");
34 let mut hdr = [0u8; 64];
35 hdr[0..4].copy_from_slice(&(stmt_id as u32).to_le_bytes());
36 hdr[4..6].copy_from_slice(&(cmd as u16).to_le_bytes());
37 hdr[6..10].copy_from_slice(&body_len.to_le_bytes());
38 if !opts.is_empty() {
39 let n = opts.len().min(44);
40 hdr[20..20 + n].copy_from_slice(&opts[..n]);
41 }
42 let mut xor = 0u8;
44 for &b in &hdr[..19] {
45 xor ^= b;
46 }
47 hdr[19] = xor;
48 hdr
49}
50
51pub fn encode_frame(stmt_id: i32, cmd: i16, opts: &[u8], body: &[u8]) -> Vec<u8> {
53 let mut out = Vec::with_capacity(FRAME_HEADER_LEN + body.len());
54 out.extend_from_slice(&make_header(stmt_id, cmd, body.len() as u32, opts));
55 out.extend_from_slice(body);
56 out
57}
58
59#[derive(Debug, Clone)]
61pub struct Frame {
62 pub stmt_id: i32,
63 pub cmd: i16,
64 pub length: u32,
65 pub retcode: i32,
66 pub opts: Vec<u8>,
68 pub body: Vec<u8>,
70}
71
72pub struct FrameReader {
74 stream: TcpStream,
75 buf: Vec<u8>,
76 recv_size: usize,
77}
78
79impl FrameReader {
80 pub fn new(stream: TcpStream) -> Self {
81 FrameReader { stream, buf: Vec::with_capacity(65536), recv_size: 65536 }
82 }
83
84 fn fill(&mut self, n: usize) -> std::io::Result<bool> {
86 while self.buf.len() < n {
87 let mut chunk = vec![0u8; self.recv_size];
88 match self.stream.read(&mut chunk) {
89 Ok(0) => return Ok(false),
90 Ok(k) => self.buf.extend_from_slice(&chunk[..k]),
91 Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
92 Err(e) => return Err(e),
93 }
94 }
95 Ok(true)
96 }
97
98 pub fn read_frame(&mut self) -> Result<Frame> {
100 if !self.fill(FRAME_HEADER_LEN)? {
101 return Err(DmError::conn("连接关闭(读取帧头)"));
102 }
103 let stmt_id = i32::from_le_bytes(self.buf[0..4].try_into().unwrap());
104 let cmd = i16::from_le_bytes(self.buf[4..6].try_into().unwrap());
105 let length = u32::from_le_bytes(self.buf[6..10].try_into().unwrap());
106 let retcode = i32::from_le_bytes(self.buf[10..14].try_into().unwrap());
107 let mut xor = 0u8;
108 for &b in &self.buf[..19] {
109 xor ^= b;
110 }
111 if xor != self.buf[19] {
112 return Err(DmError::protocol(format!("XOR 校验失败 cmd={cmd}")));
113 }
114 if length as usize > MAX_MSG_LEN {
115 return Err(DmError::protocol(format!("帧过长: {length}")));
116 }
117 let total = FRAME_HEADER_LEN + length as usize;
118 if !self.fill(total)? {
119 return Err(DmError::conn("连接关闭(读取body)"));
120 }
121 let opts = self.buf[20..64].to_vec();
122 let body = self.buf[64..total].to_vec();
123 self.buf.drain(..total);
124 Ok(Frame { stmt_id, cmd, length, retcode, opts, body })
125 }
126
127 pub fn send_frame(&mut self, stmt_id: i32, cmd: i16, opts: &[u8], body: &[u8]) -> Result<()> {
129 let frame = encode_frame(stmt_id, cmd, opts, body);
130 self.stream.write_all(&frame)?;
131 self.stream.flush()?;
132 Ok(())
133 }
134}
135
136#[cfg(test)]
137mod tests {
138 use super::*;
139
140 #[test]
141 fn header_layout_and_xor() {
142 let hdr = make_header(3, CMD_EXECUTE, 1024, &[0x01, 0x00]);
143 assert_eq!(&hdr[0..4], &3u32.to_le_bytes());
145 assert_eq!(&hdr[4..6], &5u16.to_le_bytes());
146 assert_eq!(&hdr[6..10], &1024u32.to_le_bytes());
147 assert_eq!(hdr[20], 0x01);
149 assert_eq!(hdr[21], 0x00);
150 let mut xor = 0u8;
152 for &b in &hdr[..19] {
153 xor ^= b;
154 }
155 assert_eq!(hdr[19], xor);
156 }
157
158 #[test]
159 fn encode_roundtrip() {
160 let f = encode_frame(1, CMD_LOGIN, &[1, 2, 3], b"hello");
161 assert_eq!(f.len(), 64 + 5);
162 assert_eq!(i32::from_le_bytes(f[0..4].try_into().unwrap()), 1);
163 assert_eq!(i16::from_le_bytes(f[4..6].try_into().unwrap()), CMD_LOGIN);
164 assert_eq!(u32::from_le_bytes(f[6..10].try_into().unwrap()), 5);
165 assert_eq!(&f[64..], b"hello");
166 }
167}