Skip to main content

sqlx_sqlserver/protocol/
packet.rs

1use thiserror::Error;
2
3/// Length in bytes of a TDS packet header.
4pub const PACKET_HEADER_LEN: usize = 8;
5
6/// Maximum encoded TDS packet length. The packet header stores this as a u16.
7pub const MAX_PACKET_LEN: usize = u16::MAX as usize;
8
9/// TDS packet type byte.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub struct PacketType(u8);
12
13impl PacketType {
14    /// SQL batch packet.
15    pub const SQL_BATCH: Self = Self(0x01);
16    /// RPC request packet.
17    pub const RPC: Self = Self(0x03);
18    /// Tabular result packet.
19    pub const TABULAR_RESULT: Self = Self(0x04);
20    /// Login7 packet.
21    pub const LOGIN7: Self = Self(0x10);
22    /// Pre-login packet.
23    pub const PRE_LOGIN: Self = Self(0x12);
24
25    /// Returns the raw packet type byte.
26    pub const fn code(self) -> u8 {
27        self.0
28    }
29}
30
31impl From<u8> for PacketType {
32    fn from(value: u8) -> Self {
33        Self(value)
34    }
35}
36
37/// TDS packet status byte.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct PacketStatus(u8);
40
41impl PacketStatus {
42    /// Normal packet.
43    pub const NORMAL: Self = Self(0x00);
44    /// Last packet in a message.
45    pub const END_OF_MESSAGE: Self = Self(0x01);
46
47    /// Returns the raw status byte.
48    pub const fn code(self) -> u8 {
49        self.0
50    }
51}
52
53impl From<u8> for PacketStatus {
54    fn from(value: u8) -> Self {
55        Self(value)
56    }
57}
58
59/// TDS packet header.
60#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61pub struct PacketHeader {
62    /// Packet type.
63    pub packet_type: PacketType,
64    /// Packet status.
65    pub status: PacketStatus,
66    /// Full packet length including the 8-byte header.
67    pub length: u16,
68    /// Server process ID.
69    pub server_process_id: u16,
70    /// Packet sequence ID.
71    pub packet_id: u8,
72    /// TDS window byte. Usually zero.
73    pub window: u8,
74}
75
76impl PacketHeader {
77    /// Creates a packet header for an outgoing client packet.
78    pub fn new(packet_type: PacketType, status: PacketStatus, length: u16, packet_id: u8) -> Self {
79        Self {
80            packet_type,
81            status,
82            length,
83            server_process_id: 0,
84            packet_id,
85            window: 0,
86        }
87    }
88
89    /// Returns the next packet ID, or None at the end of the message.
90    pub(crate) fn next_packet_id(self) -> Option<u8> {
91        (self.status.code() & PacketStatus::END_OF_MESSAGE.code() == 0)
92            .then(|| self.packet_id.wrapping_add(1))
93    }
94
95    /// Encodes this header to its wire representation.
96    pub fn encode(self) -> [u8; PACKET_HEADER_LEN] {
97        let length = self.length.to_be_bytes();
98        let server_process_id = self.server_process_id.to_be_bytes();
99
100        [
101            self.packet_type.code(),
102            self.status.code(),
103            length[0],
104            length[1],
105            server_process_id[0],
106            server_process_id[1],
107            self.packet_id,
108            self.window,
109        ]
110    }
111
112    /// Decodes a TDS packet header from its wire representation.
113    pub fn decode(input: &[u8]) -> Result<Self, PacketHeaderError> {
114        let bytes: &[u8; PACKET_HEADER_LEN] = input
115            .try_into()
116            .map_err(|_| PacketHeaderError::WrongLength(input.len()))?;
117
118        let length = u16::from_be_bytes([bytes[2], bytes[3]]);
119
120        if usize::from(length) < PACKET_HEADER_LEN {
121            return Err(PacketHeaderError::InvalidPacketLength(length));
122        }
123
124        Ok(Self {
125            packet_type: PacketType::from(bytes[0]),
126            status: PacketStatus::from(bytes[1]),
127            length,
128            server_process_id: u16::from_be_bytes([bytes[4], bytes[5]]),
129            packet_id: bytes[6],
130            window: bytes[7],
131        })
132    }
133}
134
135/// A decoded TDS message assembled from one or more packets.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct PacketMessage {
138    /// Packet type shared by all packets in the message.
139    pub packet_type: PacketType,
140    /// Concatenated message payload, excluding packet headers.
141    pub payload: Vec<u8>,
142    /// Number of bytes consumed from the input buffer.
143    pub consumed: usize,
144}
145
146/// Encodes a message payload into one or more TDS packets.
147///
148/// `packet_size` is the maximum packet length including the 8-byte header. The
149/// helper emits client packet IDs starting at one and sets
150/// `END_OF_MESSAGE` only on the final packet.
151pub fn encode_message(
152    packet_type: PacketType,
153    payload: &[u8],
154    packet_size: usize,
155) -> Result<Vec<u8>, PacketFrameError> {
156    if packet_size <= PACKET_HEADER_LEN {
157        return Err(PacketFrameError::InvalidMaxPacketSize(packet_size));
158    }
159
160    if packet_size > MAX_PACKET_LEN {
161        return Err(PacketFrameError::InvalidMaxPacketSize(packet_size));
162    }
163
164    let max_payload_len = packet_size - PACKET_HEADER_LEN;
165    let packet_count = if payload.is_empty() {
166        1
167    } else {
168        payload.len().div_ceil(max_payload_len)
169    };
170
171    let total_len = payload
172        .len()
173        .checked_add(packet_count * PACKET_HEADER_LEN)
174        .ok_or(PacketFrameError::MessageTooLarge)?;
175
176    let mut out = Vec::with_capacity(total_len);
177    let mut packet_id = 1u8;
178
179    if payload.is_empty() {
180        let header = PacketHeader::new(
181            packet_type,
182            PacketStatus::END_OF_MESSAGE,
183            PACKET_HEADER_LEN as u16,
184            packet_id,
185        );
186        out.extend_from_slice(&header.encode());
187        return Ok(out);
188    }
189
190    for chunk in payload.chunks(max_payload_len) {
191        let is_last = out.len() + PACKET_HEADER_LEN + chunk.len() == total_len;
192        let status = if is_last {
193            PacketStatus::END_OF_MESSAGE
194        } else {
195            PacketStatus::NORMAL
196        };
197        let length = u16::try_from(PACKET_HEADER_LEN + chunk.len())
198            .map_err(|_| PacketFrameError::MessageTooLarge)?;
199
200        let header = PacketHeader::new(packet_type, status, length, packet_id);
201        out.extend_from_slice(&header.encode());
202        out.extend_from_slice(chunk);
203        packet_id = packet_id.wrapping_add(1);
204    }
205
206    Ok(out)
207}
208
209/// Tries to decode one complete TDS message from the front of `input`.
210///
211/// Returns `Ok(None)` when the buffer does not yet contain a full packet or a
212/// packet marked `END_OF_MESSAGE`. On success, `PacketMessage::consumed`
213/// identifies how many bytes can be removed from the caller's receive buffer.
214pub fn try_decode_message(input: &[u8]) -> Result<Option<PacketMessage>, PacketFrameError> {
215    let mut offset = 0usize;
216    let mut packet_type = None;
217    let mut expected_packet_id = None;
218    let mut payload = Vec::new();
219
220    loop {
221        let Some(header_bytes) = input.get(offset..offset + PACKET_HEADER_LEN) else {
222            return Ok(None);
223        };
224
225        let header = PacketHeader::decode(header_bytes)?;
226
227        if let Some(packet_type) = packet_type {
228            if header.packet_type != packet_type {
229                return Err(PacketFrameError::MismatchedPacketType {
230                    expected: packet_type,
231                    actual: header.packet_type,
232                });
233            }
234        } else {
235            packet_type = Some(header.packet_type);
236        }
237
238        if let Some(packet_id) = expected_packet_id {
239            if header.packet_id != packet_id {
240                return Err(PacketFrameError::UnexpectedPacketId {
241                    expected: packet_id,
242                    actual: header.packet_id,
243                });
244            }
245        }
246
247        let packet_len = usize::from(header.length);
248        let packet_end = offset + packet_len;
249        let Some(packet) = input.get(offset + PACKET_HEADER_LEN..packet_end) else {
250            return Ok(None);
251        };
252
253        payload
254            .try_reserve(packet.len())
255            .map_err(|_| PacketFrameError::MessageTooLarge)?;
256        payload.extend_from_slice(packet);
257        offset = packet_end;
258        expected_packet_id = header.next_packet_id();
259
260        if expected_packet_id.is_none() {
261            return Ok(Some(PacketMessage {
262                packet_type: packet_type.expect("packet_type is set after decoding a header"),
263                payload,
264                consumed: offset,
265            }));
266        }
267    }
268}
269
270/// Error returned while decoding a TDS packet header.
271#[derive(Debug, Error, PartialEq, Eq)]
272pub enum PacketHeaderError {
273    /// The header input did not contain exactly 8 bytes.
274    #[error("TDS packet header must be 8 bytes, got {0}")]
275    WrongLength(usize),
276    /// The encoded packet length is smaller than the header itself.
277    #[error("TDS packet length {0} is smaller than the 8-byte header")]
278    InvalidPacketLength(u16),
279}
280
281/// Error returned while framing or deframing TDS packets.
282#[derive(Debug, Error, PartialEq, Eq)]
283pub enum PacketFrameError {
284    /// Packet header decoding failed.
285    #[error(transparent)]
286    Header(#[from] PacketHeaderError),
287    /// The requested packet size cannot be encoded in a TDS packet header or
288    /// leaves no room for payload bytes.
289    #[error("invalid maximum TDS packet size {0}")]
290    InvalidMaxPacketSize(usize),
291    /// A decoded message contained packets with different packet types.
292    #[error("TDS message packet type changed from 0x{expected:02x} to 0x{actual:02x}")]
293    MismatchedPacketType {
294        /// Packet type from the first packet.
295        expected: PacketType,
296        /// Packet type from a later packet in the same message.
297        actual: PacketType,
298    },
299    /// Packet IDs in a multi-packet message were not contiguous.
300    #[error("unexpected TDS packet id {actual}, expected {expected}")]
301    UnexpectedPacketId {
302        /// Expected packet ID.
303        expected: u8,
304        /// Packet ID from the header.
305        actual: u8,
306    },
307    /// The message could not fit in memory or in a protocol length field.
308    #[error("TDS message is too large")]
309    MessageTooLarge,
310}
311
312impl std::fmt::LowerHex for PacketType {
313    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
314        std::fmt::LowerHex::fmt(&self.0, f)
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    #[test]
323    fn encodes_header_with_big_endian_integer_fields() {
324        let header = PacketHeader {
325            packet_type: PacketType::PRE_LOGIN,
326            status: PacketStatus::END_OF_MESSAGE,
327            length: 0x1234,
328            server_process_id: 0xabcd,
329            packet_id: 7,
330            window: 0,
331        };
332
333        assert_eq!(
334            [0x12, 0x01, 0x12, 0x34, 0xab, 0xcd, 0x07, 0x00],
335            header.encode()
336        );
337    }
338
339    #[test]
340    fn decodes_header_from_wire_bytes() {
341        let header =
342            PacketHeader::decode(&[0x04, 0x01, 0x00, 0x08, 0x00, 0x2a, 0x03, 0x00]).unwrap();
343
344        assert_eq!(PacketType::TABULAR_RESULT, header.packet_type);
345        assert_eq!(PacketStatus::END_OF_MESSAGE, header.status);
346        assert_eq!(8, header.length);
347        assert_eq!(42, header.server_process_id);
348        assert_eq!(3, header.packet_id);
349    }
350
351    #[test]
352    fn rejects_header_with_impossible_length() {
353        let err = PacketHeader::decode(&[0x12, 0x01, 0x00, 0x07, 0, 0, 0, 0]).unwrap_err();
354
355        assert_eq!(PacketHeaderError::InvalidPacketLength(7), err);
356    }
357
358    #[test]
359    fn encodes_empty_message_as_end_packet() {
360        let bytes = encode_message(PacketType::SQL_BATCH, &[], 512).unwrap();
361
362        assert_eq!(vec![0x01, 0x01, 0x00, 0x08, 0, 0, 1, 0], bytes);
363    }
364
365    #[test]
366    fn encodes_client_message_across_packet_boundaries_from_packet_id_one() {
367        let bytes = encode_message(PacketType::PRE_LOGIN, b"abcdefghi", 12).unwrap();
368
369        assert_eq!(
370            vec![
371                0x12, 0x00, 0x00, 0x0c, 0, 0, 1, 0, b'a', b'b', b'c', b'd', 0x12, 0x00, 0x00, 0x0c,
372                0, 0, 2, 0, b'e', b'f', b'g', b'h', 0x12, 0x01, 0x00, 0x09, 0, 0, 3, 0, b'i',
373            ],
374            bytes
375        );
376    }
377
378    #[test]
379    fn rejects_invalid_max_packet_size() {
380        let err = encode_message(PacketType::PRE_LOGIN, b"abc", PACKET_HEADER_LEN).unwrap_err();
381
382        assert_eq!(
383            PacketFrameError::InvalidMaxPacketSize(PACKET_HEADER_LEN),
384            err
385        );
386    }
387
388    #[test]
389    fn decodes_single_packet_message_and_reports_consumed_bytes() {
390        let mut bytes = encode_message(PacketType::SQL_BATCH, b"select 1", 512).unwrap();
391        bytes.extend_from_slice(b"next message bytes");
392
393        let message = try_decode_message(&bytes).unwrap().unwrap();
394
395        assert_eq!(PacketType::SQL_BATCH, message.packet_type);
396        assert_eq!(b"select 1", message.payload.as_slice());
397        assert_eq!(PACKET_HEADER_LEN + b"select 1".len(), message.consumed);
398    }
399
400    #[test]
401    fn decodes_multi_packet_message_payload() {
402        let bytes = contiguous_packet_id_message();
403        let message = try_decode_message(&bytes).unwrap().unwrap();
404
405        assert_eq!(PacketType::PRE_LOGIN, message.packet_type);
406        assert_eq!(b"abcdefghi", message.payload.as_slice());
407        assert_eq!(bytes.len(), message.consumed);
408    }
409
410    #[test]
411    fn waits_for_complete_packet() {
412        let bytes = contiguous_packet_id_message();
413
414        assert_eq!(None, try_decode_message(&bytes[..15]).unwrap());
415    }
416
417    #[test]
418    fn waits_for_end_of_message_packet() {
419        let bytes = contiguous_packet_id_message();
420
421        assert_eq!(None, try_decode_message(&bytes[..12]).unwrap());
422    }
423
424    #[test]
425    fn rejects_mismatched_packet_types() {
426        let mut bytes = contiguous_packet_id_message();
427        bytes[12] = PacketType::SQL_BATCH.code();
428
429        let err = try_decode_message(&bytes).unwrap_err();
430
431        assert_eq!(
432            PacketFrameError::MismatchedPacketType {
433                expected: PacketType::PRE_LOGIN,
434                actual: PacketType::SQL_BATCH,
435            },
436            err
437        );
438    }
439
440    #[test]
441    fn rejects_non_contiguous_packet_ids() {
442        let mut bytes = contiguous_packet_id_message();
443        bytes[18] = 5;
444
445        let err = try_decode_message(&bytes).unwrap_err();
446
447        assert_eq!(
448            PacketFrameError::UnexpectedPacketId {
449                expected: 2,
450                actual: 5,
451            },
452            err
453        );
454    }
455
456    fn contiguous_packet_id_message() -> Vec<u8> {
457        vec![
458            0x12, 0x00, 0x00, 0x0c, 0, 0, 1, 0, b'a', b'b', b'c', b'd', 0x12, 0x00, 0x00, 0x0c, 0,
459            0, 2, 0, b'e', b'f', b'g', b'h', 0x12, 0x01, 0x00, 0x09, 0, 0, 3, 0, b'i',
460        ]
461    }
462}