tramex_tools/interface/parser/
parser_gtpu.rs

1//! Parser for GTPU traces
2use super::ParsingError;
3use super::hex_extractor::extract_binary_from_lines;
4use crate::data::{AdditionalInfos, Trace};
5use crate::interface::association::TraceRelation;
6use std::str::FromStr;
7
8use crate::interface::{layer::Layer, types::Direction};
9
10use super::{FileParser, LayerParser, ParsedHeader};
11
12#[derive(Debug, Clone, Default)]
13/// Data structure to store the GTPU message type
14pub struct GTPUInfos {
15    /// Direction of the message (TO/FROM)
16    pub direction: Direction,
17
18    /// Message type (e.g., "G-PDU", "Echo Request")
19    pub message_type: String,
20
21    /// Connection info (e.g., "127.0.1.100:2152")
22    pub connection_info: Option<String>,
23
24    /// Tunnel Endpoint Identifier
25    pub teid: Option<u32>,
26
27    /// QoS Flow Identifier
28    pub qfi: Option<u8>,
29
30    /// Length of the encapsulated SDU
31    pub sdu_len: Option<u32>,
32
33    /// Source address of the encapsulated packet (e.g., "192.168.3.2:51158")
34    pub src_addr: Option<String>,
35
36    /// Destination address of the encapsulated packet (e.g., "172.217.18.202:443")
37    pub dst_addr: Option<String>,
38}
39
40impl GTPUInfos {
41    /// Address of the remote (data network) side of the encapsulated flow
42    pub fn remote_addr(&self) -> Option<&String> {
43        match self.direction {
44            Direction::FROM | Direction::DL => self.src_addr.as_ref(),
45            _ => self.dst_addr.as_ref(),
46        }
47    }
48
49    /// Address of the UE side of the encapsulated flow
50    pub fn ue_addr(&self) -> Option<&String> {
51        match self.direction {
52            Direction::FROM | Direction::DL => self.dst_addr.as_ref(),
53            _ => self.src_addr.as_ref(),
54        }
55    }
56}
57
58/// GTPU Parser
59pub struct GTPUParser;
60
61impl GTPUParser {
62    /// Function that parses the remaining lines of a log
63    fn parse_lines(lines: &[String]) -> Vec<String> {
64        lines.to_vec()
65    }
66
67    /// Parse the GTPU payload (everything after the IP:port)
68    /// e.g. "G-PDU TEID=0x5315caa3 QFI=1 SDU_len=1452: IP/TCP 192.168.3.2:51158 > 172.217.18.202:443"
69    fn parse_payload(direction: Direction, connection_info: Option<String>, payload: &str) -> GTPUInfos {
70        let (header, inner) = match payload.split_once(": ") {
71            Some((h, i)) => (h, Some(i.trim())),
72            None => (payload.trim_end_matches(':'), None),
73        };
74
75        let mut tokens = header.split_whitespace();
76        let mut infos = GTPUInfos {
77            direction,
78            message_type: tokens.next().unwrap_or("Unknown").to_string(),
79            connection_info,
80            ..Default::default()
81        };
82
83        for token in tokens {
84            let Some((key, value)) = token.trim_end_matches(':').split_once('=') else {
85                continue;
86            };
87            match key {
88                "TEID" => {
89                    let hex = value.trim_start_matches("0x").trim_start_matches("0X");
90                    infos.teid = u32::from_str_radix(hex, 16).ok();
91                }
92                "QFI" => infos.qfi = value.parse().ok(),
93                "SDU_len" => infos.sdu_len = value.parse().ok(),
94                _ => {}
95            }
96        }
97
98        if let Some(inner) = inner {
99            let (_, flow) = inner.split_once(' ').unwrap_or((inner, ""));
100            if let Some((src, dst)) = flow.split_once(" > ") {
101                infos.src_addr = Some(src.trim().to_string());
102                infos.dst_addr = Some(dst.trim().to_string());
103            }
104        }
105
106        infos
107    }
108}
109
110impl FileParser for GTPUParser {
111    fn parse_additional_infos(lines: &[String]) -> Result<AdditionalInfos, ParsingError> {
112        let line = &lines[0];
113        let parts: Vec<&str> = line.split_whitespace().collect();
114
115        // Example: "13:20:45.574 [GTPU] TO 127.0.1.100:2152 G-PDU TEID=0x5315caa3 QFI=1 SDU_len=1452: IP/TCP ..."
116        // Parts: ["13:20:45.574", "[GTPU]", "TO", "127.0.1.100:2152", "G-PDU", ...]
117        if parts.len() < 5 {
118            return Err(ParsingError::new(
119                "Could not find enough (5) parameters for GTPU".to_string(),
120                1,
121            ));
122        }
123
124        let direction_result = Direction::from_str(parts[2]);
125        let direction = match direction_result {
126            Ok(d) => d,
127            Err(_) => {
128                return Err(ParsingError::new(
129                    format!("The direction could not be parsed in the part {:?} of {}", parts[2], line),
130                    1,
131                ));
132            }
133        };
134
135        // Connection info is typically at parts[3] (IP:port)
136        let (connection_info, payload_start) = if parts[3].contains(':') {
137            (Some(parts[3].to_string()), 4)
138        } else {
139            (None, 3)
140        };
141
142        let payload = parts[payload_start..].join(" ");
143        Ok(AdditionalInfos::GTPUInfos(Self::parse_payload(
144            direction,
145            connection_info,
146            &payload,
147        )))
148    }
149
150    fn parse(lines: &[String]) -> Result<Trace, ParsingError> {
151        let additional_infos = match Self::parse_additional_infos(lines) {
152            Ok(m) => m,
153            Err(e) => {
154                return Err(e);
155            }
156        };
157
158        let text = Self::parse_lines(lines);
159
160        let binary = extract_binary_from_lines(lines);
161
162        // Parse timestamp from first line
163        let timestamp = if let Some(first_line) = lines.first() {
164            super::parse_timestamp(first_line)?
165        } else {
166            0
167        };
168
169        let trace = Trace {
170            timestamp,
171            layer: Layer::GTPU,
172            additional_infos,
173            text: Some(text),
174            binary,
175            relation: TraceRelation::default(),
176        };
177        Ok(trace)
178    }
179}
180
181impl LayerParser for GTPUParser {
182    /// Parse GTPU payload lines.
183    /// data_lines[0] = "IP:PORT G-PDU TEID=... QFI=... SDU_len=..."
184    fn parse_layer(header: &ParsedHeader, data_lines: &[String]) -> Result<AdditionalInfos, ParsingError> {
185        if data_lines.is_empty() {
186            return Err(ParsingError::new("GTPU: empty data lines".to_string(), 0));
187        }
188        let first_line = data_lines[0].trim();
189
190        // First part might be IP:port
191        let (connection_info, payload) = match first_line.split_once(char::is_whitespace) {
192            Some((first, rest)) if first.contains(':') && first.contains('.') => (Some(first.to_string()), rest),
193            _ => (header.connection_info.clone(), first_line),
194        };
195
196        Ok(AdditionalInfos::GTPUInfos(Self::parse_payload(
197            header.direction.clone(),
198            connection_info,
199            payload.trim(),
200        )))
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn test_parse_gtpu_ul() {
210        let line = "13:20:45.574 [GTPU] TO 127.0.1.100:2152 G-PDU TEID=0x5315caa3 QFI=1 SDU_len=1452: IP/TCP 192.168.3.2:51158 > 172.217.18.202:443";
211        let AdditionalInfos::GTPUInfos(infos) = GTPUParser::parse_additional_infos(&[line.to_string()]).unwrap() else {
212            panic!("Expected GTPUInfos");
213        };
214        assert_eq!(infos.direction, Direction::TO);
215        assert_eq!(infos.message_type, "G-PDU");
216        assert_eq!(infos.connection_info.as_deref(), Some("127.0.1.100:2152"));
217        assert_eq!(infos.teid, Some(0x5315caa3));
218        assert_eq!(infos.qfi, Some(1));
219        assert_eq!(infos.sdu_len, Some(1452));
220        assert_eq!(infos.ue_addr().map(String::as_str), Some("192.168.3.2:51158"));
221        assert_eq!(infos.remote_addr().map(String::as_str), Some("172.217.18.202:443"));
222    }
223
224    #[test]
225    fn test_parse_gtpu_layer() {
226        let header = ParsedHeader {
227            direction: Direction::TO,
228            ..Default::default()
229        };
230        let data =
231            vec!["127.0.1.100:2152 G-PDU TEID=0x5315caa3 QFI=2 SDU_len=10: IP/UDP 1.2.3.4:5 > 6.7.8.9:10".to_string()];
232        let AdditionalInfos::GTPUInfos(infos) = GTPUParser::parse_layer(&header, &data).unwrap() else {
233            panic!("Expected GTPUInfos");
234        };
235        assert_eq!(infos.connection_info.as_deref(), Some("127.0.1.100:2152"));
236        assert_eq!(infos.qfi, Some(2));
237        assert_eq!(infos.remote_addr().map(String::as_str), Some("6.7.8.9:10"));
238    }
239
240    #[test]
241    fn test_parse_gtpu_no_inner() {
242        let line = "10:32:29.599 [GTPU] TO 127.0.1.100:2152 Echo Request";
243        let AdditionalInfos::GTPUInfos(infos) = GTPUParser::parse_additional_infos(&[line.to_string()]).unwrap() else {
244            panic!("Expected GTPUInfos");
245        };
246        assert_eq!(infos.message_type, "Echo");
247        assert_eq!(infos.teid, None);
248        assert_eq!(infos.remote_addr(), None);
249    }
250}