Skip to main content

utopia_query/classifier/
mongodb.rs

1//! The MongoDB `OP_MSG` classifier.
2
3use super::Classifier;
4use crate::Type;
5
6/// Classifies MongoDB `OP_MSG` (opcode 2013) messages by their command name,
7/// the first key of the body section's BSON document.
8///
9/// Reads (`find`, `aggregate`, `count`, `ping`, `hello`, ...) and writes
10/// (`insert`, `update`, `delete`, `create`, `drop`, ...) are looked up;
11/// `commitTransaction` / `abortTransaction` end a transaction, and a CRUD
12/// command carrying a top-level `startTransaction` key begins one. Anything
13/// else, or a malformed message, is unknown.
14///
15/// PHP: `Utopia\Query\Classifier\MongoDB`.
16#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
17pub struct MongoDb;
18
19/// The `OP_MSG` opcode.
20const OP_MSG: i64 = 2013;
21
22/// Header (16) + flags (4) + section kind (1) + smallest BSON document (5).
23const MIN_MSG_SIZE: usize = 26;
24
25/// Where the body section's BSON document starts.
26const BSON_OFFSET: usize = 21;
27
28impl Classifier for MongoDb {
29    /// PHP: `MongoDB::classify()`.
30    fn classify(&self, data: &[u8]) -> Type {
31        if data.len() < MIN_MSG_SIZE || read_u32(data, 12) != OP_MSG || data[20] != 0 {
32            return Type::Unknown;
33        }
34        let Some(command) = first_key(data, BSON_OFFSET) else {
35            return Type::Unknown;
36        };
37        if command == b"commitTransaction" || command == b"abortTransaction" {
38            return Type::TransactionEnd;
39        }
40        // Only CRUD commands can carry `startTransaction`: others skip the scan.
41        if matches!(command, b"find" | b"insert" | b"update" | b"delete" | b"aggregate" | b"findAndModify")
42            && has_key(data, BSON_OFFSET, b"startTransaction")
43        {
44            return Type::TransactionBegin;
45        }
46        match command {
47            b"find" | b"aggregate" | b"count" | b"distinct" | b"listCollections" | b"listDatabases"
48            | b"listIndexes" | b"dbStats" | b"collStats" | b"explain" | b"getMore" | b"serverStatus" | b"buildInfo"
49            | b"connectionStatus" | b"ping" | b"isMaster" | b"ismaster" | b"hello" => Type::Read,
50            b"insert" | b"update" | b"delete" | b"findAndModify" | b"create" | b"drop" | b"createIndexes"
51            | b"dropIndexes" | b"dropDatabase" | b"renameCollection" => Type::Write,
52            _ => Type::Unknown,
53        }
54    }
55}
56
57/// The little-endian `u32` at `offset` (PHP's `unpack('V')`); the caller
58/// checks the bounds.
59fn read_u32(data: &[u8], offset: usize) -> i64 {
60    match data.get(offset..offset + 4) {
61        Some(b) => i64::from(u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
62        None => 0,
63    }
64}
65
66/// The end of the BSON document at `offset`, when its declared length is
67/// valid and within `data`.
68fn document_end(data: &[u8], offset: usize) -> Option<usize> {
69    let len = data.len() as i64;
70    if offset as i64 + 4 > len {
71        return None;
72    }
73    let doc_len = read_u32(data, offset);
74    if doc_len < 5 || offset as i64 + doc_len > len {
75        return None;
76    }
77    Some(offset + doc_len as usize)
78}
79
80/// The end of the cstring starting at `pos`, before `end`.
81fn cstring_end(data: &[u8], pos: usize, end: usize) -> Option<usize> {
82    data[pos..end].iter().position(|&b| b == 0).map(|i| pos + i)
83}
84
85/// The first key of the BSON document at `offset`.
86fn first_key(data: &[u8], offset: usize) -> Option<&[u8]> {
87    let end = document_end(data, offset)?;
88    let pos = offset + 4;
89    if pos >= end || data[pos] == 0x00 {
90        return None;
91    }
92    let key_end = cstring_end(data, pos + 1, end)?;
93    Some(&data[pos + 1..key_end])
94}
95
96/// Whether the BSON document at `offset` has the top-level key `target`.
97fn has_key(data: &[u8], offset: usize, target: &[u8]) -> bool {
98    let Some(end) = document_end(data, offset) else {
99        return false;
100    };
101    let mut pos = offset + 4;
102    while pos < end {
103        let kind = data[pos];
104        if kind == 0x00 {
105            break;
106        }
107        let Some(key_end) = cstring_end(data, pos + 1, end) else {
108            break;
109        };
110        if &data[pos + 1..key_end] == target {
111            return true;
112        }
113        match skip_value(data, key_end + 1, kind, end) {
114            Some(next) => pos = next,
115            None => break,
116        }
117    }
118    false
119}
120
121/// The position after the value of BSON type `kind` at `pos`, within `limit`.
122fn skip_value(data: &[u8], pos: usize, kind: u8, limit: usize) -> Option<usize> {
123    match kind {
124        0x01 | 0x09 | 0x11 | 0x12 => advance(pos, 8, limit),
125        0x02 | 0x0D | 0x0E => skip_string(data, pos, limit),
126        0x03 | 0x04 => skip_document(data, pos, limit),
127        0x05 => skip_binary(data, pos, limit),
128        0x06 | 0x0A | 0xFF | 0x7F => Some(pos),
129        0x07 => advance(pos, 12, limit),
130        0x08 => advance(pos, 1, limit),
131        0x0B => skip_regex(data, pos, limit),
132        0x0C => skip_string(data, pos, limit).and_then(|next| advance(next, 12, limit)),
133        0x10 => advance(pos, 4, limit),
134        0x13 => advance(pos, 16, limit),
135        _ => None,
136    }
137}
138
139fn advance(pos: usize, bytes: usize, limit: usize) -> Option<usize> {
140    (pos + bytes <= limit).then_some(pos + bytes)
141}
142
143/// A length-prefixed value: `extra` bytes follow the length besides the data.
144fn skip_sized(data: &[u8], pos: usize, limit: usize, extra: i64) -> Option<usize> {
145    if pos + 4 > limit {
146        return None;
147    }
148    let size = read_u32(data, pos);
149    (size <= limit as i64 - pos as i64 - 4 - extra).then(|| pos + 4 + extra as usize + size as usize)
150}
151
152fn skip_string(data: &[u8], pos: usize, limit: usize) -> Option<usize> {
153    skip_sized(data, pos, limit, 0)
154}
155
156fn skip_binary(data: &[u8], pos: usize, limit: usize) -> Option<usize> {
157    skip_sized(data, pos, limit, 1)
158}
159
160fn skip_document(data: &[u8], pos: usize, limit: usize) -> Option<usize> {
161    if pos + 4 > limit {
162        return None;
163    }
164    let size = read_u32(data, pos);
165    (size >= 5 && size <= limit as i64 - pos as i64).then(|| pos + size as usize)
166}
167
168/// Two cstrings: the pattern and the options.
169fn skip_regex(data: &[u8], pos: usize, limit: usize) -> Option<usize> {
170    let pattern_end = cstring_end(data, pos, limit)?;
171    cstring_end(data, pattern_end + 1, limit).map(|end| end + 1)
172}