Skip to content

Commit

Permalink
[gateway] Fix SQL batch header parsing for multi-packet sequences (#671)
Browse files Browse the repository at this point in the history
This PR fixes an edge case in SQL batch header parsing where the packet sequence number resets (exceeds 255). Previously, the code would incorrectly attempt to parse stream headers from subsequent packets in a multi-packet sequence.

Changes:
- Added length validation before parsing ALL_HEADERS to prevent incorrect header parsing
- Added clarifying comments about stream header presence rules in MSSQL protocol
- Improved code readability with additional spacing and comments

According to the MSSQL protocol specification, stream headers MUST only be present in the first packet of requests that span multiple packets. This change ensures we follow this requirement correctly, particularly in cases where the packet sequence number wraps around.

Testing:
- Tested with long SQL queries that span multiple packets
- Verified correct behavior when packet sequence numbers reset
- Confirmed proper handling of ALL_HEADERS parsing
  • Loading branch information
sandromello authored Feb 3, 2025
1 parent dad3efd commit 7702758
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions common/mssqltypes/sqlbatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,20 @@ func DecodeSQLBatchToRawQuery(data []byte) (string, error) {
if PacketType(data[0]) != PacketSQLBatchType {
return "", fmt.Errorf("it's not a sql batch type, found=%X", data[0])
}
// re slice after packet header

packetNo := data[6]

// re slice after packet header
data = data[8:]

// Stream headers MUST be present only in the first packet of requests that span more than one packet
if packetNo == 0x01 {
// skip ALL_HEADERS
batchHeaderLength := binary.LittleEndian.Uint32(data[:4])
// this check guarantees to not decode ALL_HEADERS
// when the number of sequence packets resets (> 255)
if int(batchHeaderLength) > len(data[4:]) {
return ucs22str(data), nil
}
return ucs22str(data[batchHeaderLength:]), nil
}
return ucs22str(data), nil
Expand Down

0 comments on commit 7702758

Please sign in to comment.