Skip to main content

turnloop_mysql/
wire.rs

1use crate::{Error, Result};
2pub use mysql_common::value::Value;
3use mysql_common::{
4    constants::{ColumnFlags, ColumnType},
5    io::ParseBuf,
6    proto::MyDeserialize,
7    value::{BinValue, ValueDeserializer},
8};
9
10#[derive(Clone, Copy, Debug)]
11pub(crate) struct Cursor<'a>(pub &'a [u8]);
12impl<'a> Cursor<'a> {
13    pub fn take(&mut self, n: usize) -> Result<&'a [u8]> {
14        if n > self.0.len() {
15            return Err(Error::Protocol("truncated packet"));
16        }
17        let (v, r) = self.0.split_at(n);
18        self.0 = r;
19        Ok(v)
20    }
21    pub fn u8(&mut self) -> Result<u8> {
22        Ok(self.take(1)?[0])
23    }
24    pub fn u16(&mut self) -> Result<u16> {
25        Ok(u16::from_le_bytes(self.take(2)?.try_into().unwrap()))
26    }
27    pub fn u32(&mut self) -> Result<u32> {
28        Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
29    }
30    pub fn lenenc(&mut self) -> Result<u64> {
31        match self.u8()? {
32            0xfc => Ok(self.u16()? as u64),
33            0xfd => {
34                let b = self.take(3)?;
35                Ok(u32::from_le_bytes([b[0], b[1], b[2], 0]) as u64)
36            }
37            0xfe => Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap())),
38            0xfb | 0xff => Err(Error::Protocol("invalid length encoded integer")),
39            n => Ok(n as u64),
40        }
41    }
42    pub fn bytes(&mut self) -> Result<&'a [u8]> {
43        let n = usize::try_from(self.lenenc()?).map_err(|_| Error::Limit)?;
44        self.take(n)
45    }
46    pub fn end(self) -> Result<()> {
47        if self.0.is_empty() {
48            Ok(())
49        } else {
50            Err(Error::Protocol("trailing packet bytes"))
51        }
52    }
53}
54/// Per-column wire metadata that decides how a value is decoded. Rows carry it
55/// for every column (`Row::columns`, `Row::typed`), so a host can apply its own
56/// policy by MySQL column type without tracking `Column` events.
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct ColumnTypeInfo {
59    pub column_type: ColumnType,
60    pub flags: ColumnFlags,
61    pub character_set: u16,
62    /// Declared fractional-second digits for temporal columns (0..=6); 0x1f
63    /// (31) for columns without a fixed scale.
64    pub decimals: u8,
65}
66#[derive(Debug, Clone, Copy)]
67pub struct Column<'a> {
68    pub schema: &'a [u8],
69    pub table: &'a [u8],
70    pub original_table: &'a [u8],
71    pub name: &'a [u8],
72    pub original_name: &'a [u8],
73    pub column_length: u32,
74    pub decimals: u8,
75    pub type_info: ColumnTypeInfo,
76}
77impl<'a> Column<'a> {
78    pub(crate) fn parse(b: &'a [u8]) -> Result<Self> {
79        let mut c = Cursor(b);
80        if c.bytes()? != b"def" {
81            return Err(Error::Protocol("invalid column catalog"));
82        }
83        let schema = c.bytes()?;
84        let table = c.bytes()?;
85        let original_table = c.bytes()?;
86        let name = c.bytes()?;
87        let original_name = c.bytes()?;
88        if c.lenenc()? != 12 {
89            return Err(Error::Protocol("invalid column fixed length"));
90        }
91        let character_set = c.u16()?;
92        let column_length = c.u32()?;
93        let column_type = ColumnType::try_from(c.u8()?)
94            .map_err(|_| Error::Protocol("unsupported column type"))?;
95        let flags = ColumnFlags::from_bits_truncate(c.u16()?);
96        let decimals = c.u8()?;
97        c.take(2)?;
98        c.end()?;
99        Ok(Self {
100            schema,
101            table,
102            original_table,
103            name,
104            original_name,
105            column_length,
106            decimals,
107            type_info: ColumnTypeInfo {
108                column_type,
109                flags,
110                character_set,
111                decimals,
112            },
113        })
114    }
115}
116#[derive(Debug, Clone, PartialEq)]
117pub enum RawValue<'a> {
118    Null,
119    Bytes(&'a [u8]),
120    Scalar(Value),
121}
122/// One row packet, decoded lazily and validated as it is iterated.
123///
124/// `Row::parse` checks the header (binary marker and NULL bitmap) eagerly; each
125/// value is bounds-checked and decoded exactly once as the iterator reaches it,
126/// and the final value also rejects trailing packet bytes. The first `Err` ends
127/// the iteration (every later `next` is `None`), so nothing past a malformed
128/// value is ever yielded. A row error means the server sent a malformed packet:
129/// treat it like any other parsing error and `abort` the connection.
130#[derive(Debug, Clone)]
131pub struct Row<'a> {
132    cursor: Cursor<'a>,
133    columns: &'a [ColumnTypeInfo],
134    bitmap: &'a [u8],
135    binary: bool,
136    at: usize,
137}
138impl<'a> Row<'a> {
139    pub(crate) fn parse(
140        bytes: &'a [u8],
141        columns: &'a [ColumnTypeInfo],
142        binary: bool,
143    ) -> Result<Self> {
144        let mut cursor = Cursor(bytes);
145        let bitmap = if binary {
146            if cursor.u8()? != 0 {
147                return Err(Error::Protocol("invalid binary row marker"));
148            }
149            cursor.take((columns.len() + 2).div_ceil(8))?
150        } else {
151            &[]
152        };
153        Ok(Self {
154            cursor,
155            columns,
156            bitmap,
157            binary,
158            at: 0,
159        })
160    }
161    /// Wire metadata of every column in this row, in value order.
162    pub fn columns(&self) -> &'a [ColumnTypeInfo] {
163        self.columns
164    }
165    /// Pair each remaining value with its column's wire metadata, ready for
166    /// `types::decode` or a host's own per-type policy. Validation is the same
167    /// as iterating the row itself.
168    pub fn typed(
169        self,
170    ) -> impl ExactSizeIterator<Item = Result<(ColumnTypeInfo, RawValue<'a>)>> + 'a {
171        let columns = &self.columns[self.at..];
172        self.zip(columns)
173            .map(|(value, info)| value.map(|value| (*info, value)))
174    }
175    fn value(&mut self, index: usize) -> Result<RawValue<'a>> {
176        if !self.binary {
177            if self.cursor.0.first() == Some(&0xfb) {
178                self.cursor.take(1)?;
179                return Ok(RawValue::Null);
180            }
181            return Ok(RawValue::Bytes(self.cursor.bytes()?));
182        }
183        if self.bitmap[(index + 2) / 8] & (1 << ((index + 2) % 8)) != 0 {
184            return Ok(RawValue::Null);
185        }
186        let info = self.columns[index];
187        let t = info.column_type as u8;
188        if matches!(t, 0 | 15 | 16 | 245..=255 | 242) {
189            return Ok(RawValue::Bytes(self.cursor.bytes()?));
190        }
191        if !matches!(t, 1..=14) {
192            return Err(Error::Protocol("unsupported binary column type"));
193        }
194        // Numeric/calendar scalars from mysql_common contain no heap buffers.
195        let mut b = ParseBuf(self.cursor.0);
196        let value =
197            ValueDeserializer::<BinValue>::deserialize((info.column_type, info.flags), &mut b)
198                .map_err(|_| Error::Protocol("invalid binary scalar"))?
199                .0;
200        self.cursor.0 = b.0;
201        Ok(if value == Value::NULL {
202            RawValue::Null
203        } else {
204            RawValue::Scalar(value)
205        })
206    }
207}
208impl<'a> Iterator for Row<'a> {
209    type Item = Result<RawValue<'a>>;
210    fn next(&mut self) -> Option<Self::Item> {
211        if self.at == self.columns.len() {
212            return None;
213        }
214        let i = self.at;
215        self.at += 1;
216        let value = self.value(i).and_then(|value| {
217            if self.at == self.columns.len() {
218                self.cursor.end()?;
219            }
220            Ok(value)
221        });
222        if value.is_err() {
223            // Fuse: never decode past a malformed value.
224            self.at = self.columns.len();
225        }
226        Some(value)
227    }
228    fn size_hint(&self) -> (usize, Option<usize>) {
229        let n = self.columns.len() - self.at;
230        (n, Some(n))
231    }
232}
233impl ExactSizeIterator for Row<'_> {}
234
235#[derive(Debug, Clone, Copy)]
236pub struct ServerError<'a> {
237    pub errno: u16,
238    pub sql_state: &'a str,
239    pub sql_message: &'a str,
240}
241impl<'a> ServerError<'a> {
242    pub(crate) fn parse(b: &'a [u8]) -> Result<Self> {
243        let mut c = Cursor(b);
244        if c.u8()? != 0xff {
245            return Err(Error::Protocol("invalid ERR marker"));
246        }
247        let errno = c.u16()?;
248        let sql_state = if c.0.first() == Some(&b'#') {
249            c.u8()?;
250            std::str::from_utf8(c.take(5)?).map_err(|_| Error::Protocol("invalid SQLSTATE"))?
251        } else {
252            "HY000"
253        };
254        let sql_message =
255            std::str::from_utf8(c.0).map_err(|_| Error::Protocol("invalid error encoding"))?;
256        Ok(Self {
257            errno,
258            sql_state,
259            sql_message,
260        })
261    }
262    pub fn code(&self) -> Option<&'static str> {
263        error_code(self.errno)
264    }
265}
266pub fn error_code(errno: u16) -> Option<&'static str> {
267    Some(match errno {
268        1022 => "ER_DUP_KEY",
269        1040 => "ER_CON_COUNT_ERROR",
270        1044 => "ER_DBACCESS_DENIED_ERROR",
271        1045 => "ER_ACCESS_DENIED_ERROR",
272        1048 => "ER_BAD_NULL_ERROR",
273        1049 => "ER_BAD_DB_ERROR",
274        1050 => "ER_TABLE_EXISTS_ERROR",
275        1051 => "ER_BAD_TABLE_ERROR",
276        1052 => "ER_NON_UNIQ_ERROR",
277        1054 => "ER_BAD_FIELD_ERROR",
278        1062 => "ER_DUP_ENTRY",
279        1064 => "ER_PARSE_ERROR",
280        1146 => "ER_NO_SUCH_TABLE",
281        1169 => "ER_DUP_UNIQUE",
282        1205 => "ER_LOCK_WAIT_TIMEOUT",
283        1213 => "ER_LOCK_DEADLOCK",
284        1216 => "ER_NO_REFERENCED_ROW",
285        1217 => "ER_ROW_IS_REFERENCED",
286        1264 => "ER_WARN_DATA_OUT_OF_RANGE",
287        1292 => "ER_TRUNCATED_WRONG_VALUE",
288        1364 => "ER_NO_DEFAULT_FOR_FIELD",
289        1406 => "ER_DATA_TOO_LONG",
290        1451 => "ER_ROW_IS_REFERENCED_2",
291        1452 => "ER_NO_REFERENCED_ROW_2",
292        1524 => "ER_PLUGIN_IS_NOT_LOADED",
293        1586 => "ER_DUP_ENTRY_WITH_KEY_NAME",
294        1830 => "ER_FK_COLUMN_NOT_NULL",
295        1834 => "ER_FK_CANNOT_DELETE_PARENT",
296        1859 => "ER_DUP_UNKNOWN_IN_INDEX",
297        _ => return None,
298    })
299}
300#[cfg(test)]
301mod tests {
302    use super::*;
303    fn info(column_type: ColumnType) -> ColumnTypeInfo {
304        ColumnTypeInfo {
305            column_type,
306            flags: ColumnFlags::empty(),
307            character_set: 45,
308            decimals: 0,
309        }
310    }
311    fn text() -> [ColumnTypeInfo; 2] {
312        [info(ColumnType::MYSQL_TYPE_VAR_STRING); 2]
313    }
314    #[test]
315    fn a_valid_row_is_decoded_in_one_pass() {
316        let columns = text();
317        let mut row = Row::parse(b"\x02ab\xfb", &columns, false).expect("valid header");
318        assert_eq!(row.len(), 2);
319        assert_eq!(row.next(), Some(Ok(RawValue::Bytes(b"ab"))));
320        assert_eq!(row.len(), 1);
321        assert_eq!(row.next(), Some(Ok(RawValue::Null)));
322        assert_eq!(row.next(), None);
323    }
324    /// Values are validated as they are reached; nothing after the first error
325    /// is decoded or yielded.
326    #[test]
327    fn a_malformed_value_ends_the_row() {
328        let columns = text();
329        // Second value claims 9 bytes but only 2 remain.
330        let mut row = Row::parse(b"\x02ab\x09cd", &columns, false)
331            .expect("parse no longer decodes values ahead of the host");
332        assert_eq!(row.next(), Some(Ok(RawValue::Bytes(b"ab"))));
333        assert_eq!(row.next(), Some(Err(Error::Protocol("truncated packet"))));
334        assert_eq!(row.len(), 0);
335        assert_eq!(row.next(), None);
336    }
337    #[test]
338    fn trailing_bytes_fail_the_last_value() {
339        let columns = text();
340        let mut row = Row::parse(b"\x02ab\x01c!", &columns, false).expect("valid header");
341        assert_eq!(row.next(), Some(Ok(RawValue::Bytes(b"ab"))));
342        assert_eq!(
343            row.next(),
344            Some(Err(Error::Protocol("trailing packet bytes")))
345        );
346        assert_eq!(row.next(), None);
347    }
348    #[test]
349    fn rows_carry_column_type_metadata_alongside_values() {
350        use mysql_common::proto::MySerialize;
351        let mut bytes = Vec::new();
352        mysql_common::packets::Column::new(ColumnType::MYSQL_TYPE_DATETIME)
353            .with_decimals(3)
354            .serialize(&mut bytes);
355        let column = Column::parse(&bytes).expect("valid column");
356        let datetime = column.type_info;
357        assert_eq!(datetime.column_type, ColumnType::MYSQL_TYPE_DATETIME);
358        assert_eq!(datetime.decimals, 3);
359        assert_eq!(column.decimals, 3);
360        let columns = [
361            ColumnTypeInfo {
362                character_set: 63,
363                ..info(ColumnType::MYSQL_TYPE_TIME)
364            },
365            ColumnTypeInfo {
366                character_set: 63,
367                ..info(ColumnType::MYSQL_TYPE_BIT)
368            },
369            datetime,
370        ];
371        let row = Row::parse(b"\x0801:02:03\x01\x01\xfb", &columns, false).expect("valid");
372        assert_eq!(row.columns(), columns);
373        let typed = row.typed();
374        assert_eq!(typed.len(), 3);
375        let typed: Vec<_> = typed.collect::<Result<_>>().expect("valid row");
376        assert_eq!(
377            typed,
378            [
379                (columns[0], RawValue::Bytes(b"01:02:03")),
380                (columns[1], RawValue::Bytes(b"\x01")),
381                (columns[2], RawValue::Null),
382            ]
383        );
384    }
385    #[test]
386    fn binary_rows_validate_the_header_eagerly_and_scalars_lazily() {
387        let long = [info(ColumnType::MYSQL_TYPE_LONG)];
388        assert_eq!(
389            Row::parse(&[1, 0, 42, 0, 0, 0], &long, true).err(),
390            Some(Error::Protocol("invalid binary row marker"))
391        );
392        assert_eq!(
393            Row::parse(&[0], &long, true).err(),
394            Some(Error::Protocol("truncated packet"))
395        );
396        let mut row = Row::parse(&[0, 0, 42, 0, 0, 0], &long, true).expect("valid row");
397        assert_eq!(row.next(), Some(Ok(RawValue::Scalar(Value::Int(42)))));
398        assert_eq!(row.next(), None);
399        // A LONG needs four bytes; two are present.
400        let mut row = Row::parse(&[0, 0, 42, 0], &long, true).expect("valid header");
401        assert_eq!(
402            row.next(),
403            Some(Err(Error::Protocol("invalid binary scalar")))
404        );
405        assert_eq!(row.next(), None);
406    }
407}