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
// Copyright (C) 2022-present The NetGauze Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use crate::{InformationElement, SimpleRegistry, Xref};
use regex::{Captures, Regex, Replacer};
use roxmltree::{ExpandedName, Node};

const IANA_NAMESPACE: &str = "http://www.iana.org/assignments";
const ID_IE_DATA_TYPES: &str = "ipfix-information-element-data-types";
pub(crate) const ID_IE: &str = "ipfix-information-elements";
const ID_SEMANTICS: &str = "ipfix-information-element-semantics";
const ID_UNITS: &str = "ipfix-information-element-units";
const UNASSIGNED: &str = "Unassigned";
const RESERVED: &str = "Reserved";
const ASSIGNED_FOR_NF_V9: &str = "Assigned for NetFlow v9 compatibility";

struct RfcLinkSwapper;
impl Replacer for RfcLinkSwapper {
    fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) {
        dst.push_str("[RFC");
        dst.push_str(&caps["RFCNUM"]);
        dst.push_str("](https://datatracker.ietf.org/doc/rfc");
        dst.push_str(&caps["RFCNUM"]);
        dst.push(')');
    }
}

struct HttpLinkSwapper;
impl Replacer for HttpLinkSwapper {
    fn replace_append(&mut self, caps: &Captures<'_>, dst: &mut String) {
        dst.push('<');
        dst.push_str(&caps["href"]);
        dst.push('>');
    }
}

/// Find descendant node by it's ID
/// If multiple nodes with the same ID exists, the first one is returned
pub(crate) fn find_node_by_id<'a, 'input>(
    node: &'input Node<'a, 'input>,
    id: &str,
) -> Option<Node<'a, 'input>> {
    node.descendants().find(|x| x.attribute("id") == Some(id))
}

/// Get the text value of an XML node if applicable
/// For example `<a>bb</a>` returns `Some("bb".to_string())`,
/// while `<a><b/></a>` returns `None`
fn get_string_child(node: &Node<'_, '_>, tag_name: ExpandedName<'_, '_>) -> Option<String> {
    node.children()
        .find(|x| x.tag_name() == tag_name)
        .map(|x| x.text().map(|txt| txt.trim().to_string()))
        .unwrap_or_default()
}

/// Parse tags such as `<xref type="rfc">rfc1233</xref>`
fn parse_xref(node: &Node<'_, '_>) -> Vec<Xref> {
    let children = node
        .children()
        .filter(|x| x.tag_name() == (IANA_NAMESPACE, "xref").into())
        .collect::<Vec<_>>();
    let mut xrefs = Vec::new();
    for child in children {
        let ty = child.attribute("type").map(ToString::to_string);
        let data = child.attribute("data").map(ToString::to_string);
        if let (Some(ty), Some(data)) = (ty, data) {
            xrefs.push(Xref { ty, data });
        }
    }
    xrefs
}

/// Parse simple registries with just value, name (description), and optionally
/// a comment [IPFIX Information Element Data Types](https://www.iana.org/assignments/ipfix/ipfix.xml#ipfix-information-element-data-types)
/// And [IPFIX Information Element Semantics](https://www.iana.org/assignments/ipfix/ipfix.xhtml#ipfix-information-element-semantics)
pub(crate) fn parse_simple_registry(node: &Node<'_, '_>) -> Vec<SimpleRegistry> {
    let children = node
        .children()
        .filter(|x| x.tag_name() == (IANA_NAMESPACE, "record").into())
        .collect::<Vec<_>>();
    let mut ret = Vec::new();
    for child in &children {
        let value = get_string_child(child, (IANA_NAMESPACE, "value").into())
            .map(|x| x.as_str().parse::<u8>());
        let description = get_string_child(child, (IANA_NAMESPACE, "description").into());
        if Some(true) == description.as_ref().map(|x| x.as_str() == UNASSIGNED) {
            continue;
        }
        let comments = get_string_child(child, (IANA_NAMESPACE, "comments").into());
        let xref = parse_xref(child);
        if let (Some(Ok(value)), Some(description)) = (value, description) {
            let description = if description.trim() == "4-octet words" {
                "fourOctetWords".to_string()
            } else {
                description
            };
            ret.push(SimpleRegistry {
                value,
                description,
                comments,
                xref,
            });
        }
    }
    ret
}

pub fn parse_description_string(node: &Node<'_, '_>) -> Option<String> {
    if let Some(description) = node
        .children()
        .find(|x| x.tag_name() == (IANA_NAMESPACE, "description").into())
    {
        let mut desc_text = String::new();
        let mut first = true;
        for cc in description.children() {
            if !first {
                desc_text.push('\n');
                first = false;
            }
            if cc.tag_name() == (IANA_NAMESPACE, "paragraph").into() {
                let body = cc.text().map(|txt| txt.trim().to_string());
                if let Some(body) = body {
                    if !body.trim().is_empty() {
                        desc_text.push_str(body.trim());
                    }
                }
            }
            if cc.tag_name() == (IANA_NAMESPACE, "artwork").into() {
                let body = cc.text().map(|txt| txt.trim().to_string());
                if let Some(body) = body {
                    desc_text.push_str("\n\n```text\n");
                    desc_text.push_str(body.as_str());
                    desc_text.push_str("\n```\n");
                }
            }
        }
        let re = Regex::new(r"\[RFC(?<RFCNUM>\d+)]").unwrap();
        let desc_text = re.replace(&desc_text, RfcLinkSwapper).to_string();
        let re = Regex::new(r"(?<href>https?://(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*))").unwrap();
        let desc_text = re.replace(&desc_text, HttpLinkSwapper);
        Some(desc_text.to_string())
    } else {
        None
    }
}

pub(crate) fn parse_information_elements(node: &Node<'_, '_>, pen: u32) -> Vec<InformationElement> {
    let children = node
        .children()
        .filter(|x| x.tag_name() == (IANA_NAMESPACE, "record").into())
        .collect::<Vec<_>>();
    let mut ret = vec![];
    for child in &children {
        let name = get_string_child(child, (IANA_NAMESPACE, "name").into());
        let name = if let Some(name) = name {
            if name.as_str() == ASSIGNED_FOR_NF_V9 {
                log::info!("Skipping Netflow V9 element {name}");
                continue;
            }
            if name == *UNASSIGNED {
                log::info!("Skipping unsigned name: {child:?}");
                continue;
            }
            if name == *RESERVED {
                log::info!("Skipping reserved name: {child:?}");
                continue;
            }
            name
        } else {
            log::info!("Skipping a child with no name: {child:?}");
            continue;
        };

        let Some(data_type) =
            get_string_child(child, (IANA_NAMESPACE, "dataType").into()).map(|data_type| {
                if name.as_str() == "samplerId" {
                    "unsigned32".to_string()
                } else {
                    data_type
                }
            })
        else {
            log::info!("Skipping {name} a child with no data type defined: {child:?}");
            continue;
        };
        let group = get_string_child(child, (IANA_NAMESPACE, "group").into());
        let data_type_semantics =
            get_string_child(child, (IANA_NAMESPACE, "dataTypeSemantics").into());
        let element_id = get_string_child(child, (IANA_NAMESPACE, "elementId").into())
            .map(|x| x.as_str().parse::<u16>());
        let element_id = match element_id {
            Some(Ok(element_id)) => element_id,
            Some(Err(err)) => {
                log::info!(
                    "Skipping {name} a child with invalid element id defined `{err:?}`: {child:?}"
                );
                continue;
            }
            None => {
                log::info!("Skipping {name} a child with no element id defined: {child:?}");
                continue;
            }
        };
        let applicability = get_string_child(child, (IANA_NAMESPACE, "applicability").into());
        let status =
            if let Some(status) = get_string_child(child, (IANA_NAMESPACE, "status").into()) {
                status
            } else {
                log::info!("Skipping {name} a child with no status defined: {child:?}");
                continue;
            };
        let description = match parse_description_string(child) {
            Some(description) => description,
            None => {
                log::info!("Skipping {name} a child with no description defined: {child:?}");
                continue;
            }
        };

        let revision = if let Some(revision) =
            get_string_child(child, (IANA_NAMESPACE, "revision").into())
        {
            let rev = match revision.as_str().parse::<u32>() {
                Ok(rev) => rev,
                Err(err) => {
                    log::info!("Skipping {name} a child with invalid revision defined `{err:?}`: {child:?}");
                    continue;
                }
            };
            rev
        } else {
            log::info!("Skipping {name} a child with no revision defined: {child:?}");
            continue;
        };
        let date = if let Some(data) = get_string_child(child, (IANA_NAMESPACE, "date").into()) {
            data
        } else {
            log::info!("Skipping {name} a child with no date defined: {child:?}");
            continue;
        };
        let references = if let Some(references) = child
            .children()
            .find(|x| x.tag_name() == (IANA_NAMESPACE, "references").into())
        {
            get_string_child(&references, (IANA_NAMESPACE, "paragraph").into())
        } else {
            None
        };
        let xrefs = parse_xref(child);
        let units = get_string_child(child, (IANA_NAMESPACE, "units").into());
        let units = units.map(|x| {
            if x == "4-octet words" {
                "fourOctetWords".to_string()
            } else {
                x
            }
        });
        let range = get_string_child(child, (IANA_NAMESPACE, "range").into());

        let ie = InformationElement {
            pen,
            name,
            data_type,
            group,
            data_type_semantics,
            element_id,
            applicability,
            status,
            description,
            revision,
            date,
            references,
            xrefs,
            units,
            range,
        };
        ret.push(ie);
    }
    ret
}

/// Parse data types, data type semantics, and units registries
pub(crate) fn parse_iana_common_values(
    iana_root: &Node<'_, '_>,
) -> (
    Vec<SimpleRegistry>,
    Vec<SimpleRegistry>,
    Vec<SimpleRegistry>,
) {
    let data_types_node = find_node_by_id(iana_root, ID_IE_DATA_TYPES).unwrap();
    let data_types_parsed = parse_simple_registry(&data_types_node);

    let semantics_node = find_node_by_id(iana_root, ID_SEMANTICS).unwrap();
    let semantics_parsed = parse_simple_registry(&semantics_node);

    let units_node = find_node_by_id(iana_root, ID_UNITS).unwrap();
    let units_parsed = parse_simple_registry(&units_node);

    (data_types_parsed, semantics_parsed, units_parsed)
}