summaryrefslogtreecommitdiffstats
path: root/rust/src/mqtt/mqtt.rs
blob: 8260251218bd0f22a2502b1192b0fb20a56428fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
/* Copyright (C) 2020-2022 Open Information Security Foundation
 *
 * You can copy, redistribute or modify this Program under the terms of
 * the GNU General Public License version 2 as published by the Free
 * Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * version 2 along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

// written by Sascha Steinbiss <sascha@steinbiss.name>

use super::mqtt_message::*;
use super::parser::*;
use crate::applayer::*;
use crate::applayer::{self, LoggerFlags};
use crate::conf::conf_get;
use crate::core::*;
use crate::frames::*;
use nom7::Err;
use std;
use std::collections::VecDeque;
use std::ffi::CString;

// Used as a special pseudo packet identifier to denote the first CONNECT
// packet in a connection. Note that there is no risk of collision with a
// parsed packet identifier because in the protocol these are only 16 bit
// unsigned.
const MQTT_CONNECT_PKT_ID: u32 = std::u32::MAX;
// Maximum message length in bytes. If the length of a message exceeds
// this value, it will be truncated. Default: 1MB.
static mut MAX_MSG_LEN: u32 = 1048576;

static mut MQTT_MAX_TX: usize = 1024;

static mut ALPROTO_MQTT: AppProto = ALPROTO_UNKNOWN;

#[derive(AppLayerFrameType)]
pub enum MQTTFrameType {
    Pdu,
    Header,
    Data,
}

#[derive(FromPrimitive, Debug, AppLayerEvent)]
pub enum MQTTEvent {
    MissingConnect,
    MissingPublish,
    MissingSubscribe,
    MissingUnsubscribe,
    DoubleConnect,
    UnintroducedMessage,
    InvalidQosLevel,
    MissingMsgId,
    UnassignedMsgType,
    TooManyTransactions,
    MalformedTraffic,
}

#[derive(Debug)]
pub struct MQTTTransaction {
    tx_id: u64,
    pkt_id: Option<u32>,
    pub msg: Vec<MQTTMessage>,
    complete: bool,
    toclient: bool,
    toserver: bool,

    logged: LoggerFlags,
    tx_data: applayer::AppLayerTxData,
}

impl MQTTTransaction {
    pub fn new(msg: MQTTMessage, direction: Direction) -> MQTTTransaction {
        let mut m = MQTTTransaction::new_empty(direction);
        m.msg.push(msg);
        return m;
    }

    pub fn new_empty(direction: Direction) -> MQTTTransaction {
        return MQTTTransaction {
            tx_id: 0,
            pkt_id: None,
            complete: false,
            logged: LoggerFlags::new(),
            msg: Vec::new(),
            toclient: direction.is_to_client(),
            toserver: direction.is_to_server(),
            tx_data: applayer::AppLayerTxData::for_direction(direction),
        };
    }
}

impl Transaction for MQTTTransaction {
    fn id(&self) -> u64 {
        self.tx_id
    }
}

pub struct MQTTState {
    state_data: AppLayerStateData,
    tx_id: u64,
    pub protocol_version: u8,
    transactions: VecDeque<MQTTTransaction>,
    connected: bool,
    skip_request: usize,
    skip_response: usize,
    max_msg_len: usize,
    tx_index_completed: usize,
}

impl State<MQTTTransaction> for MQTTState {
    fn get_transaction_count(&self) -> usize {
        self.transactions.len()
    }

    fn get_transaction_by_index(&self, index: usize) -> Option<&MQTTTransaction> {
        self.transactions.get(index)
    }
}

impl Default for MQTTState {
    fn default() -> Self {
        Self::new()
    }
}

impl MQTTState {
    pub fn new() -> Self {
        Self {
            state_data: AppLayerStateData::new(),
            tx_id: 0,
            protocol_version: 0,
            transactions: VecDeque::new(),
            connected: false,
            skip_request: 0,
            skip_response: 0,
            max_msg_len: unsafe { MAX_MSG_LEN as usize },
            tx_index_completed: 0,
        }
    }

    fn free_tx(&mut self, tx_id: u64) {
        let len = self.transactions.len();
        let mut found = false;
        let mut index = 0;
        for i in 0..len {
            let tx = &self.transactions[i];
            if tx.tx_id == tx_id + 1 {
                found = true;
                index = i;
                break;
            }
        }
        if found {
            self.tx_index_completed = 0;
            self.transactions.remove(index);
        }
    }

    pub fn get_tx(&mut self, tx_id: u64) -> Option<&MQTTTransaction> {
        self.transactions.iter().find(|tx| tx.tx_id == tx_id + 1)
    }

    pub fn get_tx_by_pkt_id(&mut self, pkt_id: u32) -> Option<&mut MQTTTransaction> {
        for tx in &mut self.transactions.range_mut(self.tx_index_completed..) {
            if !tx.complete {
                if let Some(mpktid) = tx.pkt_id {
                    if mpktid == pkt_id {
                        return Some(tx);
                    }
                }
            }
        }
        return None;
    }

    fn new_tx(&mut self, msg: MQTTMessage, toclient: bool) -> MQTTTransaction {
        let direction = if toclient {
            Direction::ToClient
        } else {
            Direction::ToServer
        };
        let mut tx = MQTTTransaction::new(msg, direction);
        self.tx_id += 1;
        tx.tx_id = self.tx_id;
        if self.transactions.len() > unsafe { MQTT_MAX_TX } {
            let mut index = self.tx_index_completed;
            for tx_old in &mut self.transactions.range_mut(self.tx_index_completed..) {
                index += 1;
                if !tx_old.complete {
                    tx_old.complete = true;
                    MQTTState::set_event(tx_old, MQTTEvent::TooManyTransactions);
                    break;
                }
            }
            self.tx_index_completed = index;
        }
        return tx;
    }

    // Handle a MQTT message depending on the direction and state.
    // Note that we are trying to only have one mutable reference to msg
    // and its components, however, since we are in a large match operation,
    // we cannot pass around and/or store more references or move things
    // without having to introduce lifetimes etc.
    // This is the reason for the code duplication below. Maybe there is a
    // more concise way to do it, but this works for now.
    fn handle_msg(&mut self, msg: MQTTMessage, toclient: bool) {
        match msg.op {
            MQTTOperation::CONNECT(ref conn) => {
                self.protocol_version = conn.protocol_version;
                let mut tx = self.new_tx(msg, toclient);
                tx.pkt_id = Some(MQTT_CONNECT_PKT_ID);
                if self.connected {
                    MQTTState::set_event(&mut tx, MQTTEvent::DoubleConnect);
                }
                self.transactions.push_back(tx);
            }
            MQTTOperation::PUBLISH(ref publish) => {
                let qos = msg.header.qos_level;
                let pkt_id = publish.message_id;
                let mut tx = self.new_tx(msg, toclient);
                match qos {
                    0 => {
                        // with QOS level 0, we do not need to wait for a
                        // response
                        tx.complete = true;
                    }
                    1..=2 => {
                        if let Some(pkt_id) = pkt_id {
                            tx.pkt_id = Some(pkt_id as u32);
                        } else {
                            MQTTState::set_event(&mut tx, MQTTEvent::MissingMsgId);
                        }
                    }
                    _ => {
                        MQTTState::set_event(&mut tx, MQTTEvent::InvalidQosLevel);
                    }
                }
                if !self.connected {
                    MQTTState::set_event(&mut tx, MQTTEvent::UnintroducedMessage);
                }
                self.transactions.push_back(tx);
            }
            MQTTOperation::SUBSCRIBE(ref subscribe) => {
                let pkt_id = subscribe.message_id as u32;
                let qos = msg.header.qos_level;
                let mut tx = self.new_tx(msg, toclient);
                match qos {
                    0 => {
                        // with QOS level 0, we do not need to wait for a
                        // response
                        tx.complete = true;
                    }
                    1..=2 => {
                        tx.pkt_id = Some(pkt_id);
                    }
                    _ => {
                        MQTTState::set_event(&mut tx, MQTTEvent::InvalidQosLevel);
                    }
                }
                if !self.connected {
                    MQTTState::set_event(&mut tx, MQTTEvent::UnintroducedMessage);
                }
                self.transactions.push_back(tx);
            }
            MQTTOperation::UNSUBSCRIBE(ref unsubscribe) => {
                let pkt_id = unsubscribe.message_id as u32;
                let qos = msg.header.qos_level;
                let mut tx = self.new_tx(msg, toclient);
                match qos {
                    0 => {
                        // with QOS level 0, we do not need to wait for a
                        // response
                        tx.complete = true;
                    }
                    1..=2 => {
                        tx.pkt_id = Some(pkt_id);
                    }
                    _ => {
                        MQTTState::set_event(&mut tx, MQTTEvent::InvalidQosLevel);
                    }
                }
                if !self.connected {
                    MQTTState::set_event(&mut tx, MQTTEvent::UnintroducedMessage);
                }
                self.transactions.push_back(tx);
            }
            MQTTOperation::CONNACK(ref _connack) => {
                if let Some(tx) = self.get_tx_by_pkt_id(MQTT_CONNECT_PKT_ID) {
                    tx.msg.push(msg);
                    tx.complete = true;
                    tx.pkt_id = None;
                    self.connected = true;
                } else {
                    let mut tx = self.new_tx(msg, toclient);
                    MQTTState::set_event(&mut tx, MQTTEvent::MissingConnect);
                    tx.complete = true;
                    self.transactions.push_back(tx);
                }
            }
            MQTTOperation::PUBREC(ref v) | MQTTOperation::PUBREL(ref v) => {
                if let Some(tx) = self.get_tx_by_pkt_id(v.message_id as u32) {
                    tx.msg.push(msg);
                } else {
                    let mut tx = self.new_tx(msg, toclient);
                    MQTTState::set_event(&mut tx, MQTTEvent::MissingPublish);
                    if !self.connected {
                        MQTTState::set_event(&mut tx, MQTTEvent::UnintroducedMessage);
                    }
                    tx.complete = true;
                    self.transactions.push_back(tx);
                }
            }
            MQTTOperation::PUBACK(ref v) | MQTTOperation::PUBCOMP(ref v) => {
                if let Some(tx) = self.get_tx_by_pkt_id(v.message_id as u32) {
                    tx.msg.push(msg);
                    tx.complete = true;
                    tx.pkt_id = None;
                } else {
                    let mut tx = self.new_tx(msg, toclient);
                    MQTTState::set_event(&mut tx, MQTTEvent::MissingPublish);
                    if !self.connected {
                        MQTTState::set_event(&mut tx, MQTTEvent::UnintroducedMessage);
                    }
                    tx.complete = true;
                    self.transactions.push_back(tx);
                }
            }
            MQTTOperation::SUBACK(ref suback) => {
                if let Some(tx) = self.get_tx_by_pkt_id(suback.message_id as u32) {
                    tx.msg.push(msg);
                    tx.complete = true;
                    tx.pkt_id = None;
                } else {
                    let mut tx = self.new_tx(msg, toclient);
                    MQTTState::set_event(&mut tx, MQTTEvent::MissingSubscribe);
                    if !self.connected {
                        MQTTState::set_event(&mut tx, MQTTEvent::UnintroducedMessage);
                    }
                    tx.complete = true;
                    self.transactions.push_back(tx);
                }
            }
            MQTTOperation::UNSUBACK(ref unsuback) => {
                if let Some(tx) = self.get_tx_by_pkt_id(unsuback.message_id as u32) {
                    tx.msg.push(msg);
                    tx.complete = true;
                    tx.pkt_id = None;
                } else {
                    let mut tx = self.new_tx(msg, toclient);
                    MQTTState::set_event(&mut tx, MQTTEvent::MissingUnsubscribe);
                    if !self.connected {
                        MQTTState::set_event(&mut tx, MQTTEvent::UnintroducedMessage);
                    }
                    tx.complete = true;
                    self.transactions.push_back(tx);
                }
            }
            MQTTOperation::UNASSIGNED => {
                let mut tx = self.new_tx(msg, toclient);
                tx.complete = true;
                MQTTState::set_event(&mut tx, MQTTEvent::UnassignedMsgType);
                self.transactions.push_back(tx);
            }
            MQTTOperation::TRUNCATED(_) => {
                let mut tx = self.new_tx(msg, toclient);
                tx.complete = true;
                self.transactions.push_back(tx);
            }
            MQTTOperation::AUTH(_) | MQTTOperation::DISCONNECT(_) => {
                let mut tx = self.new_tx(msg, toclient);
                tx.complete = true;
                if !self.connected {
                    MQTTState::set_event(&mut tx, MQTTEvent::UnintroducedMessage);
                }
                self.transactions.push_back(tx);
            }
            MQTTOperation::PINGREQ | MQTTOperation::PINGRESP => {
                let mut tx = self.new_tx(msg, toclient);
                tx.complete = true;
                if !self.connected {
                    MQTTState::set_event(&mut tx, MQTTEvent::UnintroducedMessage);
                }
                self.transactions.push_back(tx);
            }
        }
    }

    fn parse_request(&mut self, flow: *const Flow, stream_slice: StreamSlice) -> AppLayerResult {
        let input = stream_slice.as_slice();
        let mut current = input;

        if input.is_empty() {
            return AppLayerResult::ok();
        }

        let mut consumed = 0;
        SCLogDebug!(
            "skip_request {} input len {}",
            self.skip_request,
            input.len()
        );
        if self.skip_request > 0 {
            if input.len() <= self.skip_request {
                SCLogDebug!("reducing skip_request by {}", input.len());
                self.skip_request -= input.len();
                return AppLayerResult::ok();
            } else {
                current = &input[self.skip_request..];
                SCLogDebug!(
                    "skip end reached, skipping {} :{:?}",
                    self.skip_request,
                    current
                );
                consumed = self.skip_request;
                self.skip_request = 0;
            }
        }

        while !current.is_empty() {
            SCLogDebug!("request: handling {}", current.len());
            match parse_message(current, self.protocol_version, self.max_msg_len) {
                Ok((rem, msg)) => {
                    let _pdu = Frame::new(
                        flow,
                        &stream_slice,
                        current,
                        (current.len() - rem.len()) as i64,
                        MQTTFrameType::Pdu as u8,
                    );
                    SCLogDebug!("request msg {:?}", msg);
                    if let MQTTOperation::TRUNCATED(ref trunc) = msg.op {
                        SCLogDebug!(
                            "found truncated with skipped {} current len {}",
                            trunc.skipped_length,
                            current.len()
                        );
                        if trunc.skipped_length >= current.len() {
                            self.skip_request = trunc.skipped_length - current.len();
                            self.handle_msg(msg, true);
                            return AppLayerResult::ok();
                        } else {
                            consumed += trunc.skipped_length;
                            current = &current[trunc.skipped_length..];
                            self.handle_msg(msg, true);
                            self.skip_request = 0;
                            continue;
                        }
                    }

                    self.mqtt_hdr_and_data_frames(flow, &stream_slice, &msg);
                    self.handle_msg(msg, false);
                    consumed += current.len() - rem.len();
                    current = rem;
                }
                Err(Err::Incomplete(_)) => {
                    SCLogDebug!(
                        "incomplete request: consumed {} needed {} (input len {})",
                        consumed,
                        (current.len() + 1),
                        input.len()
                    );
                    return AppLayerResult::incomplete(consumed as u32, (current.len() + 1) as u32);
                }
                Err(_) => {
                    self.set_event_notx(MQTTEvent::MalformedTraffic, false);
                    return AppLayerResult::err();
                }
            }
        }

        return AppLayerResult::ok();
    }

    fn parse_response(&mut self, flow: *const Flow, stream_slice: StreamSlice) -> AppLayerResult {
        let input = stream_slice.as_slice();
        let mut current = input;

        if input.is_empty() {
            return AppLayerResult::ok();
        }

        let mut consumed = 0;
        SCLogDebug!(
            "skip_response {} input len {}",
            self.skip_response,
            current.len()
        );
        if self.skip_response > 0 {
            if input.len() <= self.skip_response {
                self.skip_response -= current.len();
                return AppLayerResult::ok();
            } else {
                current = &input[self.skip_response..];
                SCLogDebug!(
                    "skip end reached, skipping {} :{:?}",
                    self.skip_request,
                    current
                );
                consumed = self.skip_response;
                self.skip_response = 0;
            }
        }

        while !current.is_empty() {
            SCLogDebug!("response: handling {}", current.len());
            match parse_message(current, self.protocol_version, self.max_msg_len) {
                Ok((rem, msg)) => {
                    let _pdu = Frame::new(
                        flow,
                        &stream_slice,
                        current,
                        (current.len() - rem.len()) as i64,
                        MQTTFrameType::Pdu as u8,
                    );

                    SCLogDebug!("response msg {:?}", msg);
                    if let MQTTOperation::TRUNCATED(ref trunc) = msg.op {
                        SCLogDebug!(
                            "found truncated with skipped {} current len {}",
                            trunc.skipped_length,
                            current.len()
                        );
                        if trunc.skipped_length >= current.len() {
                            self.skip_response = trunc.skipped_length - current.len();
                            self.handle_msg(msg, true);
                            SCLogDebug!("skip_response now {}", self.skip_response);
                            return AppLayerResult::ok();
                        } else {
                            consumed += trunc.skipped_length;
                            current = &current[trunc.skipped_length..];
                            self.handle_msg(msg, true);
                            self.skip_response = 0;
                            continue;
                        }
                    }

                    self.mqtt_hdr_and_data_frames(flow, &stream_slice, &msg);
                    self.handle_msg(msg, true);
                    consumed += current.len() - rem.len();
                    current = rem;
                }
                Err(Err::Incomplete(_)) => {
                    SCLogDebug!(
                        "incomplete response: consumed {} needed {} (input len {})",
                        consumed,
                        (current.len() + 1),
                        input.len()
                    );
                    return AppLayerResult::incomplete(consumed as u32, (current.len() + 1) as u32);
                }
                Err(_) => {
                    self.set_event_notx(MQTTEvent::MalformedTraffic, true);
                    return AppLayerResult::err();
                }
            }
        }

        return AppLayerResult::ok();
    }

    fn set_event(tx: &mut MQTTTransaction, event: MQTTEvent) {
        tx.tx_data.set_event(event as u8);
    }

    fn set_event_notx(&mut self, event: MQTTEvent, toclient: bool) {
        let mut tx = MQTTTransaction::new_empty(if toclient {
            Direction::ToClient
        } else {
            Direction::ToServer
        });
        self.tx_id += 1;
        tx.tx_id = self.tx_id;
        if toclient {
            tx.toclient = true;
        } else {
            tx.toserver = true;
        }
        tx.complete = true;
        tx.tx_data.set_event(event as u8);
        self.transactions.push_back(tx);
    }

    fn mqtt_hdr_and_data_frames(
        &mut self, flow: *const Flow, stream_slice: &StreamSlice, input: &MQTTMessage,
    ) {
        let hdr = stream_slice.as_slice();
        //MQTT payload has a fixed header of 2 bytes
        let _mqtt_hdr = Frame::new(flow, stream_slice, hdr, 2, MQTTFrameType::Header as u8);
        SCLogDebug!("mqtt_hdr Frame {:?}", _mqtt_hdr);
        let rem_length = input.header.remaining_length as usize;
        let data = &hdr[2..rem_length + 2];
        let _mqtt_data = Frame::new(
            flow,
            stream_slice,
            data,
            rem_length as i64,
            MQTTFrameType::Data as u8,
        );
        SCLogDebug!("mqtt_data Frame {:?}", _mqtt_data);
    }
}

// C exports.

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_probing_parser(
    _flow: *const Flow, _direction: u8, input: *const u8, input_len: u32, _rdir: *mut u8,
) -> AppProto {
    let buf = build_slice!(input, input_len as usize);
    match parse_fixed_header(buf) {
        Ok((_, hdr)) => {
            // reject unassigned message type
            if hdr.message_type == MQTTTypeCode::UNASSIGNED {
                return ALPROTO_FAILED;
            }
            // with 2 being the highest valid QoS level
            if hdr.qos_level > 2 {
                return ALPROTO_FAILED;
            }
            return ALPROTO_MQTT;
        }
        Err(Err::Incomplete(_)) => ALPROTO_UNKNOWN,
        Err(_) => ALPROTO_FAILED,
    }
}

#[no_mangle]
pub extern "C" fn rs_mqtt_state_new(
    _orig_state: *mut std::os::raw::c_void, _orig_proto: AppProto,
) -> *mut std::os::raw::c_void {
    let state = MQTTState::new();
    let boxed = Box::new(state);
    return Box::into_raw(boxed) as *mut _;
}

#[no_mangle]
pub extern "C" fn rs_mqtt_state_free(state: *mut std::os::raw::c_void) {
    std::mem::drop(unsafe { Box::from_raw(state as *mut MQTTState) });
}

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_state_tx_free(state: *mut std::os::raw::c_void, tx_id: u64) {
    let state = cast_pointer!(state, MQTTState);
    state.free_tx(tx_id);
}

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_parse_request(
    flow: *const Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
    stream_slice: StreamSlice, _data: *const std::os::raw::c_void,
) -> AppLayerResult {
    let state = cast_pointer!(state, MQTTState);
    return state.parse_request(flow, stream_slice);
}

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_parse_response(
    flow: *const Flow, state: *mut std::os::raw::c_void, _pstate: *mut std::os::raw::c_void,
    stream_slice: StreamSlice, _data: *const std::os::raw::c_void,
) -> AppLayerResult {
    let state = cast_pointer!(state, MQTTState);
    return state.parse_response(flow, stream_slice);
}

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_state_get_tx(
    state: *mut std::os::raw::c_void, tx_id: u64,
) -> *mut std::os::raw::c_void {
    let state = cast_pointer!(state, MQTTState);
    match state.get_tx(tx_id) {
        Some(tx) => {
            return tx as *const _ as *mut _;
        }
        None => {
            return std::ptr::null_mut();
        }
    }
}

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_state_get_tx_count(state: *mut std::os::raw::c_void) -> u64 {
    let state = cast_pointer!(state, MQTTState);
    return state.tx_id;
}

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_tx_is_toclient(
    tx: *const std::os::raw::c_void,
) -> std::os::raw::c_int {
    let tx = cast_pointer!(tx, MQTTTransaction);
    if tx.toclient {
        return 1;
    }
    return 0;
}

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_tx_get_alstate_progress(
    tx: *mut std::os::raw::c_void, direction: u8,
) -> std::os::raw::c_int {
    let tx = cast_pointer!(tx, MQTTTransaction);
    match direction.into() {
        Direction::ToServer => {
            if tx.complete || tx.toclient {
                return 1;
            }
        }
        Direction::ToClient => {
            if tx.complete || tx.toserver {
                return 1;
            }
        }
    }
    return 0;
}

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_tx_get_logged(
    _state: *mut std::os::raw::c_void, tx: *mut std::os::raw::c_void,
) -> u32 {
    let tx = cast_pointer!(tx, MQTTTransaction);
    return tx.logged.get();
}

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_tx_set_logged(
    _state: *mut std::os::raw::c_void, tx: *mut std::os::raw::c_void, logged: u32,
) {
    let tx = cast_pointer!(tx, MQTTTransaction);
    tx.logged.set(logged);
}

// Parser name as a C style string.
const PARSER_NAME: &[u8] = b"mqtt\0";

export_tx_data_get!(rs_mqtt_get_tx_data, MQTTTransaction);
export_state_data_get!(rs_mqtt_get_state_data, MQTTState);

#[no_mangle]
pub unsafe extern "C" fn rs_mqtt_register_parser(cfg_max_msg_len: u32) {
    let default_port = CString::new("[1883]").unwrap();
    let max_msg_len = &mut MAX_MSG_LEN;
    *max_msg_len = cfg_max_msg_len;
    let parser = RustParser {
        name: PARSER_NAME.as_ptr() as *const std::os::raw::c_char,
        default_port: default_port.as_ptr(),
        ipproto: IPPROTO_TCP,
        probe_ts: Some(rs_mqtt_probing_parser),
        probe_tc: Some(rs_mqtt_probing_parser),
        min_depth: 0,
        max_depth: 16,
        state_new: rs_mqtt_state_new,
        state_free: rs_mqtt_state_free,
        tx_free: rs_mqtt_state_tx_free,
        parse_ts: rs_mqtt_parse_request,
        parse_tc: rs_mqtt_parse_response,
        get_tx_count: rs_mqtt_state_get_tx_count,
        get_tx: rs_mqtt_state_get_tx,
        tx_comp_st_ts: 1,
        tx_comp_st_tc: 1,
        tx_get_progress: rs_mqtt_tx_get_alstate_progress,
        get_eventinfo: Some(MQTTEvent::get_event_info),
        get_eventinfo_byid: Some(MQTTEvent::get_event_info_by_id),
        localstorage_new: None,
        localstorage_free: None,
        get_tx_files: None,
        get_tx_iterator: Some(crate::applayer::state_get_tx_iterator::<MQTTState, MQTTTransaction>),
        get_tx_data: rs_mqtt_get_tx_data,
        get_state_data: rs_mqtt_get_state_data,
        apply_tx_config: None,
        flags: 0,
        truncate: None,
        get_frame_id_by_name: Some(MQTTFrameType::ffi_id_from_name),
        get_frame_name_by_id: Some(MQTTFrameType::ffi_name_from_id),
    };

    let ip_proto_str = CString::new("tcp").unwrap();

    if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
        let alproto = AppLayerRegisterProtocolDetection(&parser, 1);
        ALPROTO_MQTT = alproto;
        if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name) != 0 {
            let _ = AppLayerRegisterParser(&parser, alproto);
        }
        if let Some(val) = conf_get("app-layer.protocols.mqtt.max-tx") {
            if let Ok(v) = val.parse::<usize>() {
                MQTT_MAX_TX = v;
            } else {
                SCLogError!("Invalid value for mqtt.max-tx");
            }
        }
    } else {
        SCLogDebug!("Protocol detector and parser disabled for MQTT.");
    }
}