bgpfu-netconf 0.1.0

A toolset for working with IRR data
Documentation
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
use std::{
    convert::Infallible,
    fmt::{self, Debug},
    str::{from_utf8, FromStr},
    sync::Arc,
};

use quick_xml::{
    events::{BytesStart, Event},
    name::ResolveResult,
    NsReader,
};

use crate::{message::ReadError, session::SessionId};

use super::{xmlns, ReadXml};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Errors {
    inner: Vec<Error>,
}

impl Errors {
    pub(super) const fn new() -> Self {
        Self { inner: Vec::new() }
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    pub(super) fn push(&mut self, err: Error) {
        self.inner.push(err);
    }

    pub fn iter(&self) -> impl Iterator<Item = &Error> {
        self.inner.iter()
    }
}

impl fmt::Display for Errors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.iter().try_for_each(|err| writeln!(f, "{err}"))
    }
}

impl std::error::Error for Errors {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Error {
    error_type: Type,
    error_tag: Tag,
    severity: Severity,
    app_tag: Option<AppTag>,
    path: Option<Path>,
    message: Option<Message>,
    info: Info,
}

impl ReadXml for Error {
    #[tracing::instrument(skip_all, fields(tag = ?start.local_name()), level = "debug")]
    fn read_xml(reader: &mut NsReader<&[u8]>, start: &BytesStart<'_>) -> Result<Self, ReadError> {
        let end = start.to_end();
        let mut error_type = None;
        let mut error_tag = None;
        let mut severity = None;
        let mut app_tag = None;
        let mut path = None;
        let mut message = None;
        let mut info = None;
        loop {
            match reader.read_resolved_event()? {
                (ResolveResult::Bound(ns), Event::Start(tag))
                    if ns == xmlns::BASE
                        && tag.local_name().as_ref() == b"error-type"
                        && error_type.is_none() =>
                {
                    tracing::debug!(?tag);
                    error_type = Some(reader.read_text(tag.to_end().name())?.trim().parse()?);
                }
                (ResolveResult::Bound(ns), Event::Start(tag))
                    if ns == xmlns::BASE
                        && tag.local_name().as_ref() == b"error-tag"
                        && error_tag.is_none() =>
                {
                    tracing::debug!(?tag);
                    error_tag = Some(reader.read_text(tag.to_end().name())?.trim().parse()?);
                }
                (ResolveResult::Bound(ns), Event::Start(tag))
                    if ns == xmlns::BASE
                        && tag.local_name().as_ref() == b"error-severity"
                        && severity.is_none() =>
                {
                    tracing::debug!(?tag);
                    severity = Some(reader.read_text(tag.to_end().name())?.trim().parse()?);
                }
                (ResolveResult::Bound(ns), Event::Start(tag))
                    if ns == xmlns::BASE
                        && tag.local_name().as_ref() == b"error-app-tag"
                        && app_tag.is_none() =>
                {
                    tracing::debug!(?tag);
                    app_tag = Some(
                        reader
                            .read_text(tag.to_end().name())?
                            .trim()
                            .parse()
                            .unwrap_or_else(|_| unreachable!()),
                    );
                }
                (ResolveResult::Bound(ns), Event::Start(tag))
                    if ns == xmlns::BASE
                        && tag.local_name().as_ref() == b"error-path"
                        && path.is_none() =>
                {
                    tracing::debug!(?tag);
                    path = Some(
                        reader
                            .read_text(tag.to_end().name())?
                            .trim()
                            .parse()
                            .unwrap_or_else(|_| unreachable!()),
                    );
                }
                (ResolveResult::Bound(ns), Event::Start(tag))
                    if ns == xmlns::BASE
                        && tag.local_name().as_ref() == b"error-message"
                        && message.is_none() =>
                {
                    tracing::debug!(?tag);
                    message = Some(
                        reader
                            .read_text(tag.to_end().name())?
                            .trim()
                            .parse()
                            .unwrap_or_else(|_| unreachable!()),
                    );
                }
                (ResolveResult::Bound(ns), Event::Start(tag))
                    if ns == xmlns::BASE
                        && tag.local_name().as_ref() == b"error-info"
                        && info.is_none() =>
                {
                    tracing::debug!(?tag);
                    info = Some(Info::read_xml(reader, &tag)?);
                }
                (_, Event::Comment(_)) => continue,
                (_, Event::End(tag)) if tag == end => break,
                (ns, event) => {
                    tracing::error!(?event, ?ns, "unexpected xml event");
                    return Err(ReadError::UnexpectedXmlEvent(event.into_owned()));
                }
            }
        }
        Ok(Self {
            error_type: error_type
                .ok_or_else(|| ReadError::missing_element("rpc-error", "error-type"))?,
            error_tag: error_tag
                .ok_or_else(|| ReadError::missing_element("rpc-error", "error-tag"))?,
            severity: severity
                .ok_or_else(|| ReadError::missing_element("rpc-error", "error-severity"))?,
            app_tag,
            path,
            message,
            info: info.unwrap_or_else(Info::new),
        })
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} {}: {}",
            self.error_type, self.severity, self.error_tag
        )
    }
}

impl std::error::Error for Error {}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Type {
    Transport,
    Rpc,
    Protocol,
    Application,
}

impl FromStr for Type {
    type Err = ReadError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "transport" => Ok(Self::Transport),
            "rpc" => Ok(Self::Rpc),
            "protocol" => Ok(Self::Protocol),
            "application" => Ok(Self::Application),
            _ => Err(Self::Err::UnknownErrorType(s.to_string())),
        }
    }
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let ty = match self {
            Self::Transport => "transport",
            Self::Rpc => "rpc",
            Self::Protocol => "protocol",
            Self::Application => "application",
        };
        f.write_str(ty)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Tag {
    InUse,
    InvalidValue,
    TooBig,
    MissingAttribute,
    BadAttribute,
    UnknownAttribute,
    MissingElement,
    BadElement,
    UnknownElement,
    UnknownNamespace,
    AccessDenied,
    LockDenied,
    ResourceDenied,
    RollbackFailed,
    DataExists,
    DataMissing,
    OperationNotSupported,
    OperationFailed,
    MalformedMessage,

    // Deprecated:
    PartialOperation,
}

impl FromStr for Tag {
    type Err = ReadError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "in-use" => Ok(Self::InUse),
            "invalid-value" => Ok(Self::InvalidValue),
            "too-big" => Ok(Self::TooBig),
            "missing-attribute" => Ok(Self::MissingAttribute),
            "bad-attribute" => Ok(Self::BadAttribute),
            "unknown-attribute" => Ok(Self::UnknownAttribute),
            "missing-element" => Ok(Self::MissingElement),
            "bad-element" => Ok(Self::BadElement),
            "unknown-element" => Ok(Self::UnknownElement),
            "unknown-namespace" => Ok(Self::UnknownNamespace),
            "access-denied" => Ok(Self::AccessDenied),
            "lock-denied" => Ok(Self::LockDenied),
            "resource-denied" => Ok(Self::ResourceDenied),
            "rollback-failed" => Ok(Self::RollbackFailed),
            "data-exists" => Ok(Self::DataExists),
            "data-missing" => Ok(Self::DataMissing),
            "operation-not-supported" => Ok(Self::OperationNotSupported),
            "operation-failed" => Ok(Self::OperationFailed),
            "malformed-message" => Ok(Self::MalformedMessage),
            "partial-operation" => Ok(Self::PartialOperation),
            _ => Err(Self::Err::UnknownErrorTag(s.to_string())),
        }
    }
}

impl fmt::Display for Tag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let msg = match self {
            Self::InUse => "The request requires a resource that already is in use",
            Self::InvalidValue => "The request specifies an unacceptable value for one or more parameters",
            Self::TooBig => "The request or response (that would be generated) is too large for the implementation to handle",
            Self::MissingAttribute => "An expected attribute is missing",
            Self::BadAttribute => "An attribute value is not correct; e.g., wrong type, out of range, pattern mismatch",
            Self::UnknownAttribute => "An unexpected attribute is present",
            Self::MissingElement => "An expected element is missing",
            Self::BadElement => "An element value is not correct; e.g., wrong type, out of range, pattern mismatch",
            Self::UnknownElement => "An unexpected element is present",
            Self::UnknownNamespace => "An unexpected namespace is present",
            Self::AccessDenied => "Access to the requested protocol operation or data model is denied because authorization failed",
            Self::LockDenied => "Access to the requested lock is denied because the lock is currently held by another entity",
            Self::ResourceDenied => "Request could not be completed because of insufficient resources",
            Self::RollbackFailed => "Request to roll back some configuration change (via rollback-on-error or <discard-changes> operations) was not completed for some reason",
            Self::DataExists => "Request could not be completed because the relevant data model content already exists",
            Self::DataMissing => "Request could not be completed because the relevant data model content does not exist",
            Self::OperationNotSupported => "Request could not be completed because the requested operation is not supported by this implementation",
            Self::OperationFailed => "Request could not be completed because the requested operation failed for some reason not covered by any other error condition",
            Self::MalformedMessage => "A message could not be handled because it failed to be parsed correctly",
            Self::PartialOperation => "Some part of the requested operation failed or was not attempted for some reason",
        };
        f.write_str(msg)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Severity {
    Warning,
    Error,
}

impl FromStr for Severity {
    type Err = ReadError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "error" => Ok(Self::Error),
            "warning" => Ok(Self::Warning),
            _ => Err(Self::Err::UnknownErrorSeverity(s.to_string())),
        }
    }
}

impl fmt::Display for Severity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let severity = match self {
            Self::Error => "error",
            Self::Warning => "warning",
        };
        f.write_str(severity)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AppTag {
    inner: Arc<str>,
}

impl FromStr for AppTag {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self { inner: s.into() })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Path {
    inner: Arc<str>,
}

impl FromStr for Path {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self { inner: s.into() })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Message {
    // TODO
    lang: (),
    inner: Arc<str>,
}

impl FromStr for Message {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self {
            lang: (),
            inner: s.into(),
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Info {
    inner: Vec<InfoElement>,
}

impl Info {
    const fn new() -> Self {
        Self { inner: Vec::new() }
    }
}

impl ReadXml for Info {
    #[tracing::instrument(skip_all, fields(tag = ?start.local_name()), level = "debug")]
    fn read_xml(reader: &mut NsReader<&[u8]>, start: &BytesStart<'_>) -> Result<Self, ReadError> {
        let end = start.to_end();
        let mut inner = Vec::new();
        tracing::debug!("expecting error-info element");
        loop {
            match reader.read_resolved_event()? {
                (ResolveResult::Bound(ns), Event::Start(tag)) if ns == xmlns::BASE => {
                    match tag.local_name().as_ref() {
                        b"bad-attribute" => inner.push(InfoElement::BadAttribute(
                            reader.read_text(tag.to_end().name())?.as_ref().into(),
                        )),
                        b"bad-element" => inner.push(InfoElement::BadElement(
                            reader.read_text(tag.to_end().name())?.as_ref().into(),
                        )),
                        b"bad-namespace" => inner.push(InfoElement::BadNamespace(
                            reader.read_text(tag.to_end().name())?.as_ref().into(),
                        )),
                        b"session-id" => inner.push(InfoElement::SessionId(
                            reader
                                .read_text(tag.to_end().name())?
                                .as_ref()
                                .parse()
                                .map_err(ReadError::SessionIdParse)
                                .map(|session_id| SessionId::new(session_id).ok())?,
                        )),
                        b"ok-element" => inner.push(InfoElement::OkElement(
                            reader.read_text(tag.to_end().name())?.as_ref().into(),
                        )),
                        b"err-element" => inner.push(InfoElement::ErrElement(
                            reader.read_text(tag.to_end().name())?.as_ref().into(),
                        )),
                        b"noop-element" => inner.push(InfoElement::NoopElement(
                            reader.read_text(tag.to_end().name())?.as_ref().into(),
                        )),
                        name => {
                            return Err(ReadError::UnknownErrorInfo(from_utf8(name)?.to_string()))
                        }
                    }
                }
                (_, Event::Comment(_)) => continue,
                (_, Event::End(tag)) if tag == end => break,
                (ns, event) => {
                    tracing::error!(?event, ?ns, "unexpected xml event");
                    return Err(ReadError::UnexpectedXmlEvent(event.into_owned()));
                }
            }
        }
        Ok(Self { inner })
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InfoElement {
    BadAttribute(Arc<str>),
    BadElement(Arc<str>),
    BadNamespace(Arc<str>),
    SessionId(Option<SessionId>),

    // Deprecated error-info elements:
    OkElement(Arc<str>),
    ErrElement(Arc<str>),
    NoopElement(Arc<str>),
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use quick_xml::Writer;

    use super::*;
    use crate::{
        capabilities::Requirements,
        message::{
            rpc::{operation, EmptyReply, MessageId, Operation, PartialReply, Reply},
            ServerMsg, WriteError, WriteXml,
        },
    };

    #[derive(Debug, PartialEq)]
    struct Dummy;

    impl Operation for Dummy {
        const NAME: &'static str = "dummy";
        const REQUIRED_CAPABILITIES: Requirements = Requirements::None;
        type Builder<'a> = Builder;
        type Reply = EmptyReply;
    }

    impl WriteXml for Dummy {
        fn write_xml<W: Write>(&self, _: &mut Writer<W>) -> Result<(), WriteError> {
            Ok(())
        }
    }

    #[derive(Debug)]
    struct Builder;

    impl operation::Builder<'_, Dummy> for Builder {
        fn new(_: &crate::session::Context) -> Self {
            Self
        }

        fn finish(self) -> Result<Dummy, crate::Error> {
            Ok(Dummy)
        }
    }

    #[test]
    fn deserialize_error_reply_rfc6241_s1_example1() {
        // message-id has been added, as we do not support it's omission
        let data = r#"
            <rpc-reply message-id="101"
              xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
              <rpc-error>
                <error-type>rpc</error-type>
                <error-tag>missing-attribute</error-tag>
                <error-severity>error</error-severity>
                <error-info>
                  <bad-attribute>message-id</bad-attribute>
                  <bad-element>rpc</bad-element>
                </error-info>
              </rpc-error>
            </rpc-reply>
        "#;
        let expect: Reply<Dummy> = Reply {
            message_id: MessageId(101),
            inner: EmptyReply::Errs(Errors {
                inner: vec![Error {
                    error_type: Type::Rpc,
                    error_tag: Tag::MissingAttribute,
                    severity: Severity::Error,
                    app_tag: None,
                    path: None,
                    message: None,
                    info: Info {
                        inner: vec![
                            InfoElement::BadAttribute("message-id".into()),
                            InfoElement::BadElement("rpc".into()),
                        ],
                    },
                }],
            }),
        };
        assert_eq!(
            expect,
            PartialReply::from_xml(data)
                .and_then(Reply::try_from)
                .unwrap()
        );
    }
    #[test]
    fn deserialize_error_reply_rfc6241_s1_example2() {
        let data = r#"
            <rpc-reply message-id="101"
              xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"
              xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">
              <rpc-error>
                <error-type>application</error-type>
                <error-tag>invalid-value</error-tag>
                <error-severity>error</error-severity>
                <error-path xmlns:t="http://example.com/schema/1.2/config">
                  /t:top/t:interface[t:name="Ethernet0/0"]/t:mtu
                </error-path>
                <error-message xml:lang="en">
                  MTU value 25000 is not within range 256..9192
                </error-message>
              </rpc-error>
              <rpc-error>
                <error-type>application</error-type>
                <error-tag>invalid-value</error-tag>
                <error-severity>error</error-severity>
                <error-path xmlns:t="http://example.com/schema/1.2/config">
                  /t:top/t:interface[t:name="Ethernet1/0"]/t:address/t:name
                </error-path>
                <error-message xml:lang="en">
                  Invalid IP address for interface Ethernet1/0
                </error-message>
              </rpc-error>
            </rpc-reply>
        "#;
        let expect: Reply<Dummy> = Reply {
            message_id: MessageId(101),
            inner: EmptyReply::Errs(Errors {
                inner: vec![
                    Error {
                        error_type: Type::Application,
                        error_tag: Tag::InvalidValue,
                        severity: Severity::Error,
                        app_tag: None,
                        path: Some(Path {
                            inner: r#"/t:top/t:interface[t:name="Ethernet0/0"]/t:mtu"#.into(),
                        }),
                        message: Some(Message {
                            lang: (),
                            inner: "MTU value 25000 is not within range 256..9192".into(),
                        }),
                        info: Info::new(),
                    },
                    Error {
                        error_type: Type::Application,
                        error_tag: Tag::InvalidValue,
                        severity: Severity::Error,
                        app_tag: None,
                        path: Some(Path {
                            inner: r#"/t:top/t:interface[t:name="Ethernet1/0"]/t:address/t:name"#
                                .into(),
                        }),
                        message: Some(Message {
                            lang: (),
                            inner: "Invalid IP address for interface Ethernet1/0".into(),
                        }),
                        info: Info::new(),
                    },
                ],
            }),
        };
        assert_eq!(
            expect,
            PartialReply::from_xml(data)
                .and_then(Reply::try_from)
                .unwrap()
        );
    }
}