rustnetconf 0.13.1

An async-first NETCONF 1.0/1.1 client library for Rust
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
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
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
//! NETCONF RPC serialization and response parsing.
//!
//! Handles converting typed RPC operations into XML messages and
//! parsing XML responses back into typed results.

pub mod filter;
pub mod operations;

use crate::error::{ProtocolError, RpcError};
use crate::rpc::operations::escape_xml_text;
use crate::types::{ErrorSeverity, ErrorTag, RpcErrorType};

/// Validate that an XML fragment is well-formed before insertion into an RPC.
///
/// This library is a caller-controlled API — callers construct XML intentionally.
/// Validation here is not meant to sanitize untrusted content (callers bear that
/// responsibility), but to catch programming errors and malformed fragments early,
/// before they corrupt the framed NETCONF message on the wire.
///
/// The fragment is wrapped in a synthetic root element to allow multiple sibling
/// elements at the top level, and parsed with `check_end_names` enabled to catch
/// mismatched or unclosed tags.
///
/// An empty string passes validation (used to represent "no filter/content").
///
/// # Errors
///
/// Returns `ProtocolError::Xml` if the fragment contains XML parse errors such
/// as unclosed tags, mismatched element names, or invalid syntax.
///
/// # Examples
///
/// ```rust
/// use rustnetconf::rpc::validate_xml_fragment;
///
/// // Valid fragment
/// validate_xml_fragment("<interfaces><interface><name>ge-0/0/0</name></interface></interfaces>").unwrap();
///
/// // Empty string is allowed
/// validate_xml_fragment("").unwrap();
///
/// // Malformed fragment returns an error
/// assert!(validate_xml_fragment("<unclosed>").is_err());
/// ```
pub fn validate_xml_fragment(xml: &str) -> Result<(), ProtocolError> {
    if xml.is_empty() {
        return Ok(());
    }

    use quick_xml::events::Event;
    use quick_xml::Reader;

    // Wrap in a synthetic root so multi-sibling fragments parse as a single document.
    let wrapped = format!("<_>{xml}</_>");

    let mut reader = Reader::from_str(&wrapped);
    reader.config_mut().check_end_names = true;
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Eof) => break,
            Err(e) => {
                return Err(ProtocolError::Xml(format!(
                    "XML fragment is not well-formed: {e}"
                )));
            }
            _ => {}
        }
        buf.clear();
    }

    Ok(())
}

#[cfg(test)]
mod xml_validate_tests {
    use super::*;

    #[test]
    fn test_valid_xml_fragment() {
        assert!(validate_xml_fragment(
            "<interfaces><interface><name>ge-0/0/0</name></interface></interfaces>"
        )
        .is_ok());
    }

    #[test]
    fn test_valid_self_closing() {
        assert!(validate_xml_fragment("<filter/>").is_ok());
    }

    #[test]
    fn test_valid_multiple_siblings() {
        assert!(validate_xml_fragment("<a/><b/><c/>").is_ok());
    }

    #[test]
    fn test_empty_string_is_valid() {
        assert!(validate_xml_fragment("").is_ok());
    }

    #[test]
    fn test_unclosed_tag_is_invalid() {
        let result = validate_xml_fragment("<unclosed>");
        assert!(result.is_err(), "unclosed tag should fail validation");
        let err = format!("{}", result.unwrap_err());
        assert!(
            err.contains("not well-formed"),
            "error should mention not well-formed: {err}"
        );
    }

    #[test]
    fn test_mismatched_tags_is_invalid() {
        let result = validate_xml_fragment("<a></b>");
        assert!(result.is_err(), "mismatched tags should fail validation");
    }

    #[test]
    fn test_malformed_attribute_is_invalid() {
        let result = validate_xml_fragment("<a b=broken>");
        assert!(
            result.is_err(),
            "malformed attribute should fail validation"
        );
    }
}

/// A parsed NETCONF `<rpc-reply>` response.
#[derive(Debug)]
pub enum RpcReply {
    /// Success with data (from `<get>`, `<get-config>`).
    Data(String),
    /// Success with data, but the device also returned warnings.
    DataWithWarnings(String, Vec<RpcErrorInfo>),
    /// Success with no data (`<ok/>`).
    Ok,
    /// Success (`<ok/>`), but the device also returned warnings.
    OkWithWarnings(Vec<RpcErrorInfo>),
}

/// A fully parsed `<rpc-error>` from the device.
#[derive(Debug, Clone)]
pub struct RpcErrorInfo {
    pub error_type: Option<RpcErrorType>,
    pub tag: ErrorTag,
    pub severity: Option<ErrorSeverity>,
    pub app_tag: Option<String>,
    pub path: Option<String>,
    pub message: String,
    pub info: Option<String>,
}

/// Re-escape a raw attribute value for emission inside double quotes.
///
/// The raw value keeps its original entity escaping but may contain a raw
/// `"` (when the source used single quotes). Decode entities best-effort,
/// then escape fully so the reconstructed attribute is always well-formed.
fn reescape_attr_value(raw: &str) -> String {
    let decoded = quick_xml::escape::unescape(raw)
        .map(|cow| cow.into_owned())
        .unwrap_or_else(|_| raw.to_string());
    crate::rpc::operations::escape_xml_attr(&decoded)
}

/// Parse an `<rpc-reply>` XML response.
///
/// Returns `Ok(RpcReply)` for successful responses, or `Err(RpcError)` if
/// the reply contains `<rpc-error>` elements.
pub fn parse_rpc_reply(xml: &str, expected_message_id: &str) -> Result<RpcReply, RpcError> {
    use crate::xml_entity::{raw_entity_ref, resolve_entity_ref};
    use quick_xml::events::Event;
    use quick_xml::Reader;

    let mut reader = Reader::from_str(xml);
    let mut buf = Vec::new();

    let mut found_message_id: Option<String> = None;
    let mut found_ok = false;
    let mut data_content: Option<String> = None;
    let mut errors: Vec<RpcErrorInfo> = Vec::new();

    // State for parsing rpc-error
    let mut in_rpc_error = false;
    let mut in_rpc_reply = false;
    let mut in_data = false;
    let mut data_depth: u32 = 0;
    let mut data_xml = String::new();

    // rpc-error field tracking
    let mut current_error: Option<RpcErrorBuilder> = None;
    let mut current_field: Option<ErrorField> = None;
    // Element text accumulates across events: quick-xml 0.38+ splits text
    // around entity references (`GeneralRef`), so a field's value may span
    // several Text/GeneralRef events before the closing tag.
    let mut field_text = String::new();
    // error-info can contain child elements — accumulate inner XML
    let mut in_error_info = false;
    let mut _error_info_depth: u32 = 0;
    let mut error_info_xml = String::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(ref tag)) => {
                let local = tag.local_name();
                let name = std::str::from_utf8(local.as_ref()).unwrap_or("");

                match name {
                    "rpc-reply" => {
                        in_rpc_reply = true;
                        // Extract message-id attribute
                        for attr in tag.attributes().flatten() {
                            if attr.key.local_name().as_ref() == b"message-id" {
                                found_message_id =
                                    Some(String::from_utf8_lossy(&attr.value).to_string());
                            }
                        }
                    }
                    "data" if in_rpc_reply && !in_rpc_error => {
                        in_data = true;
                        data_depth = 1;
                        data_xml.clear();
                    }
                    "rpc-error" if in_rpc_reply => {
                        in_rpc_error = true;
                        current_error = Some(RpcErrorBuilder::new());
                    }
                    _ if in_data => {
                        data_depth += 1;
                        // Reconstruct the inner XML, keeping the qualified
                        // name so namespace prefixes survive.
                        let tag_name = tag.name();
                        let qname = std::str::from_utf8(tag_name.as_ref()).unwrap_or(name);
                        data_xml.push('<');
                        data_xml.push_str(qname);
                        for attr in tag.attributes().flatten() {
                            data_xml.push(' ');
                            data_xml.push_str(std::str::from_utf8(attr.key.as_ref()).unwrap_or(""));
                            data_xml.push_str("=\"");
                            data_xml.push_str(&reescape_attr_value(&String::from_utf8_lossy(
                                &attr.value,
                            )));
                            data_xml.push('"');
                        }
                        data_xml.push('>');
                    }
                    _ if in_error_info => {
                        // Inside <error-info>: accumulate child elements as XML
                        _error_info_depth += 1;
                        let tag_name = tag.name();
                        let qname = std::str::from_utf8(tag_name.as_ref()).unwrap_or(name);
                        error_info_xml.push('<');
                        error_info_xml.push_str(qname);
                        error_info_xml.push('>');
                    }
                    _ if in_rpc_error => {
                        if name == "error-info" {
                            in_error_info = true;
                            _error_info_depth = 1;
                            error_info_xml.clear();
                        } else {
                            current_field = ErrorField::from_name(name);
                            field_text.clear();
                        }
                    }
                    _ => {}
                }
            }
            Ok(Event::Empty(ref tag)) => {
                let local = tag.local_name();
                let name = std::str::from_utf8(local.as_ref()).unwrap_or("");

                if name == "ok" && in_rpc_reply {
                    found_ok = true;
                } else if in_data {
                    let tag_name = tag.name();
                    let qname = std::str::from_utf8(tag_name.as_ref()).unwrap_or(name);
                    data_xml.push('<');
                    data_xml.push_str(qname);
                    for attr in tag.attributes().flatten() {
                        data_xml.push(' ');
                        data_xml.push_str(std::str::from_utf8(attr.key.as_ref()).unwrap_or(""));
                        data_xml.push_str("=\"");
                        data_xml
                            .push_str(&reescape_attr_value(&String::from_utf8_lossy(&attr.value)));
                        data_xml.push('"');
                    }
                    data_xml.push_str("/>");
                } else if in_error_info {
                    let tag_name = tag.name();
                    let qname = std::str::from_utf8(tag_name.as_ref()).unwrap_or(name);
                    error_info_xml.push('<');
                    error_info_xml.push_str(qname);
                    error_info_xml.push_str("/>");
                }
            }
            Ok(Event::CData(ref cdata)) => {
                // CDATA is ordinary character data; re-escape it as text when
                // reconstructing XML, capture it raw for field values.
                let value = cdata.decode().unwrap_or_default();
                if in_data {
                    data_xml.push_str(&escape_xml_text(&value));
                } else if in_error_info {
                    error_info_xml.push_str(&escape_xml_text(&value));
                } else if in_rpc_error && current_field.is_some() {
                    field_text.push_str(&value);
                }
            }
            Ok(Event::Text(ref text)) => {
                // Text events never contain entity refs (those arrive as
                // GeneralRef), so decoding the encoding is all that's needed.
                let value = text.decode().unwrap_or_default();

                if in_data {
                    // Re-escape any raw special chars so the reconstructed
                    // XML stays well-formed.
                    data_xml.push_str(&escape_xml_text(&value));
                } else if in_error_info {
                    error_info_xml.push_str(&escape_xml_text(&value));
                } else if in_rpc_error && current_field.is_some() {
                    field_text.push_str(&value);
                }
            }
            Ok(Event::GeneralRef(ref entity)) => {
                if in_data {
                    // Keep the reference escaped verbatim in reconstructed XML.
                    data_xml.push_str(&raw_entity_ref(entity));
                } else if in_error_info {
                    error_info_xml.push_str(&raw_entity_ref(entity));
                } else if in_rpc_error && current_field.is_some() {
                    if let Some(resolved) = resolve_entity_ref(entity) {
                        field_text.push_str(&resolved);
                    }
                }
            }
            Ok(Event::End(ref tag)) => {
                let local = tag.local_name();
                let name = std::str::from_utf8(local.as_ref()).unwrap_or("");

                match name {
                    "rpc-reply" => {
                        in_rpc_reply = false;
                    }
                    "data" if in_data && data_depth == 1 => {
                        in_data = false;
                        data_content = Some(data_xml.clone());
                    }
                    "rpc-error" => {
                        in_rpc_error = false;
                        if let Some(builder) = current_error.take() {
                            errors.push(builder.build());
                        }
                    }
                    _ if in_data => {
                        data_depth -= 1;
                        let tag_name = tag.name();
                        let qname = std::str::from_utf8(tag_name.as_ref()).unwrap_or(name);
                        data_xml.push_str("</");
                        data_xml.push_str(qname);
                        data_xml.push('>');
                    }
                    "error-info" if in_error_info => {
                        in_error_info = false;
                        if let Some(ref mut builder) = current_error {
                            let trimmed = error_info_xml.trim().to_string();
                            if !trimmed.is_empty() {
                                builder.info = Some(trimmed);
                            }
                        }
                    }
                    _ if in_error_info => {
                        _error_info_depth -= 1;
                        let tag_name = tag.name();
                        let qname = std::str::from_utf8(tag_name.as_ref()).unwrap_or(name);
                        error_info_xml.push_str("</");
                        error_info_xml.push_str(qname);
                        error_info_xml.push('>');
                    }
                    _ if in_rpc_error => {
                        // Field text is complete at the closing tag; flush the
                        // accumulated value into the builder.
                        if let (Some(ref mut builder), Some(field)) =
                            (&mut current_error, current_field.take())
                        {
                            builder.set_field(&field, &field_text);
                        }
                        field_text.clear();
                    }
                    _ => {}
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(RpcError::ParseError(format!("XML parse error: {e}"))),
            _ => {}
        }
        buf.clear();
    }

    // Check message-id
    if let Some(ref msg_id) = found_message_id {
        if msg_id != expected_message_id {
            return Err(RpcError::MessageIdMismatch {
                expected: expected_message_id.to_string(),
                actual: msg_id.clone(),
            });
        }
    }

    // Partition errors into hard errors and warnings
    let (hard_errors, warnings): (Vec<_>, Vec<_>) = errors
        .into_iter()
        .partition(|e| e.severity != Some(ErrorSeverity::Warning));

    // Hard errors always fail the RPC
    if let Some(first_error) = hard_errors.into_iter().next() {
        return Err(RpcError::ServerError {
            error_type: first_error.error_type,
            tag: first_error.tag,
            severity: first_error.severity,
            app_tag: first_error.app_tag,
            path: first_error.path,
            message: first_error.message,
            info: first_error.info,
        });
    }

    // Log warnings so they're visible even when the caller ignores them
    if !warnings.is_empty() {
        for w in &warnings {
            tracing::warn!(tag = ?w.tag, message = %w.message, "device returned RPC warning");
        }
    }

    // Return data or ok, attaching any warnings
    if let Some(data) = data_content {
        if warnings.is_empty() {
            return Ok(RpcReply::Data(data));
        }
        return Ok(RpcReply::DataWithWarnings(data, warnings));
    }

    if found_ok {
        if warnings.is_empty() {
            return Ok(RpcReply::Ok);
        }
        return Ok(RpcReply::OkWithWarnings(warnings));
    }

    // Junos custom RPCs return content directly under <rpc-reply> without a
    // <data> wrapper (e.g. <software-information>, <route-engine-information>).
    // Re-parse to extract any non-error, non-ok child elements as data.
    if in_rpc_reply || found_message_id.is_some() {
        if let Some(inner) = extract_rpc_reply_inner_content(xml) {
            return Ok(RpcReply::Data(inner));
        }
    }

    // An empty <rpc-reply> with no errors is a success (RFC 6241 §4.3).
    if in_rpc_reply || found_message_id.is_some() {
        return Ok(RpcReply::Ok);
    }

    Err(RpcError::ParseError(
        "rpc-reply contained no <ok/>, <data>, or <rpc-error>".to_string(),
    ))
}

/// Fields within an `<rpc-error>` element.
#[allow(clippy::enum_variant_names)]
enum ErrorField {
    ErrorType,
    ErrorTag,
    ErrorSeverity,
    ErrorAppTag,
    ErrorPath,
    ErrorMessage,
    ErrorInfo,
}

impl ErrorField {
    fn from_name(name: &str) -> Option<Self> {
        match name {
            "error-type" => Some(ErrorField::ErrorType),
            "error-tag" => Some(ErrorField::ErrorTag),
            "error-severity" => Some(ErrorField::ErrorSeverity),
            "error-app-tag" => Some(ErrorField::ErrorAppTag),
            "error-path" => Some(ErrorField::ErrorPath),
            "error-message" => Some(ErrorField::ErrorMessage),
            "error-info" => Some(ErrorField::ErrorInfo),
            _ => None,
        }
    }
}

/// Builder for constructing RpcErrorInfo from parsed XML fields.
struct RpcErrorBuilder {
    error_type: Option<RpcErrorType>,
    tag: Option<ErrorTag>,
    severity: Option<ErrorSeverity>,
    app_tag: Option<String>,
    path: Option<String>,
    message: Option<String>,
    info: Option<String>,
}

impl RpcErrorBuilder {
    fn new() -> Self {
        Self {
            error_type: None,
            tag: None,
            severity: None,
            app_tag: None,
            path: None,
            message: None,
            info: None,
        }
    }

    fn set_field(&mut self, field: &ErrorField, value: &str) {
        match field {
            ErrorField::ErrorType => {
                self.error_type = Some(match value {
                    "transport" => RpcErrorType::Transport,
                    "rpc" => RpcErrorType::Rpc,
                    "protocol" => RpcErrorType::Protocol,
                    "application" => RpcErrorType::Application,
                    _ => RpcErrorType::Application,
                });
            }
            ErrorField::ErrorTag => {
                self.tag = Some(value.parse().unwrap_or(ErrorTag::Other(value.to_string())));
            }
            ErrorField::ErrorSeverity => {
                self.severity = Some(match value {
                    "warning" => ErrorSeverity::Warning,
                    _ => ErrorSeverity::Error,
                });
            }
            ErrorField::ErrorAppTag => {
                self.app_tag = Some(value.to_string());
            }
            ErrorField::ErrorPath => {
                self.path = Some(value.to_string());
            }
            ErrorField::ErrorMessage => {
                self.message = Some(value.to_string());
            }
            ErrorField::ErrorInfo => {
                self.info = Some(value.to_string());
            }
        }
    }

    fn build(self) -> RpcErrorInfo {
        RpcErrorInfo {
            error_type: self.error_type,
            tag: self.tag.unwrap_or(ErrorTag::OperationFailed),
            severity: self.severity,
            app_tag: self.app_tag,
            path: self.path,
            message: self.message.unwrap_or_else(|| "unknown error".to_string()),
            info: self.info,
        }
    }
}

/// Extract inner content from `<rpc-reply>` for Junos custom RPC responses.
///
/// Junos custom RPCs (e.g., `<get-software-information>`) return their data
/// directly under `<rpc-reply>` without a `<data>` wrapper. This function
/// extracts all child element content from the reply.
fn extract_rpc_reply_inner_content(xml: &str) -> Option<String> {
    use crate::xml_entity::raw_entity_ref;
    use quick_xml::events::Event;
    use quick_xml::Reader;

    let mut reader = Reader::from_str(xml);
    let mut buf = Vec::new();

    let mut in_rpc_reply = false;
    let mut depth: u32 = 0;
    let mut content = String::new();
    let mut has_content = false;

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(ref tag)) => {
                let local = tag.local_name();
                let name = std::str::from_utf8(local.as_ref()).unwrap_or("");

                if name == "rpc-reply" {
                    in_rpc_reply = true;
                } else if in_rpc_reply && (depth > 0 || (name != "ok" && name != "rpc-error")) {
                    if depth == 0 {
                        has_content = true;
                    }
                    depth += 1;
                    let tag_name = tag.name();
                    let qname = std::str::from_utf8(tag_name.as_ref()).unwrap_or(name);
                    content.push('<');
                    content.push_str(qname);
                    for attr in tag.attributes().flatten() {
                        content.push(' ');
                        content.push_str(std::str::from_utf8(attr.key.as_ref()).unwrap_or(""));
                        content.push_str("=\"");
                        content
                            .push_str(&reescape_attr_value(&String::from_utf8_lossy(&attr.value)));
                        content.push('"');
                    }
                    content.push('>');
                }
            }
            Ok(Event::Empty(ref tag)) if in_rpc_reply => {
                let local = tag.local_name();
                let name = std::str::from_utf8(local.as_ref()).unwrap_or("");
                // A top-level empty element (other than <ok/> / <rpc-error/>)
                // is still reply content.
                if depth > 0 || (name != "ok" && name != "rpc-error") {
                    if depth == 0 {
                        has_content = true;
                    }
                    let tag_name = tag.name();
                    let qname = std::str::from_utf8(tag_name.as_ref()).unwrap_or(name);
                    content.push('<');
                    content.push_str(qname);
                    for attr in tag.attributes().flatten() {
                        content.push(' ');
                        content.push_str(std::str::from_utf8(attr.key.as_ref()).unwrap_or(""));
                        content.push_str("=\"");
                        content
                            .push_str(&reescape_attr_value(&String::from_utf8_lossy(&attr.value)));
                        content.push('"');
                    }
                    content.push_str("/>");
                }
            }
            Ok(Event::Text(ref text)) if in_rpc_reply && depth > 0 => {
                let value = text.decode().unwrap_or_default();
                // Re-escape any raw special chars so the reconstructed XML
                // stays well-formed.
                content.push_str(&escape_xml_text(&value));
            }
            Ok(Event::GeneralRef(ref entity)) if in_rpc_reply && depth > 0 => {
                // Keep entity references escaped verbatim.
                content.push_str(&raw_entity_ref(entity));
            }
            Ok(Event::CData(ref cdata)) if in_rpc_reply && depth > 0 => {
                // CDATA is character data; re-escape it as ordinary text.
                let value = cdata.decode().unwrap_or_default();
                content.push_str(&escape_xml_text(&value));
            }
            Ok(Event::End(ref tag)) => {
                let local = tag.local_name();
                let name = std::str::from_utf8(local.as_ref()).unwrap_or("");
                if name == "rpc-reply" {
                    break;
                }
                if in_rpc_reply && depth > 0 {
                    depth -= 1;
                    let tag_name = tag.name();
                    let qname = std::str::from_utf8(tag_name.as_ref()).unwrap_or(name);
                    content.push_str("</");
                    content.push_str(qname);
                    content.push('>');
                }
            }
            Ok(Event::Eof) => break,
            Err(_) => return None,
            _ => {}
        }
        buf.clear();
    }

    if has_content {
        Some(content)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_ok_reply() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1">
  <ok/>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "1").unwrap();
        assert!(matches!(result, RpcReply::Ok));
    }

    #[test]
    fn test_parse_data_reply() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="2">
  <data>
    <configuration><interfaces><interface><name>ge-0/0/0</name></interface></interfaces></configuration>
  </data>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "2").unwrap();
        match result {
            RpcReply::Data(data) => {
                assert!(data.contains("ge-0/0/0"));
                assert!(data.contains("<configuration>"));
            }
            _ => panic!("expected Data reply"),
        }
    }

    #[test]
    fn test_parse_rpc_error() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="3">
  <rpc-error>
    <error-type>application</error-type>
    <error-tag>invalid-value</error-tag>
    <error-severity>error</error-severity>
    <error-path>/configuration/interfaces/interface[name='ge-0/0/0']</error-path>
    <error-message>invalid interface name</error-message>
  </rpc-error>
</rpc-reply>"#;
        let err = parse_rpc_reply(xml, "3").unwrap_err();
        match err {
            RpcError::ServerError {
                tag, message, path, ..
            } => {
                assert_eq!(tag, ErrorTag::InvalidValue);
                assert_eq!(message, "invalid interface name");
                assert!(path.unwrap().contains("ge-0/0/0"));
            }
            _ => panic!("expected ServerError, got {err:?}"),
        }
    }

    #[test]
    fn test_parse_message_id_mismatch() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="99">
  <ok/>
</rpc-reply>"#;
        let err = parse_rpc_reply(xml, "1").unwrap_err();
        assert!(matches!(err, RpcError::MessageIdMismatch { .. }));
    }

    #[test]
    fn test_parse_lock_denied_error() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="5">
  <rpc-error>
    <error-type>protocol</error-type>
    <error-tag>lock-denied</error-tag>
    <error-severity>error</error-severity>
    <error-message>Lock failed, lock is already held</error-message>
    <error-info>session-id: 42</error-info>
  </rpc-error>
</rpc-reply>"#;
        let err = parse_rpc_reply(xml, "5").unwrap_err();
        match err {
            RpcError::ServerError {
                tag, info, message, ..
            } => {
                assert_eq!(tag, ErrorTag::LockDenied);
                assert!(message.contains("Lock failed"));
                assert!(info.unwrap().contains("42"));
            }
            _ => panic!("expected ServerError"),
        }
    }

    #[test]
    fn test_parse_junos_custom_rpc_reply() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="7">
  <software-information>
    <host-name>vsrx1</host-name>
    <product-model>vSRX</product-model>
    <product-name>vsrx</product-name>
    <junos-version>21.4R3.15</junos-version>
  </software-information>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "7").unwrap();
        match result {
            RpcReply::Data(data) => {
                assert!(data.contains("<software-information>"));
                assert!(data.contains("vsrx1"));
                assert!(data.contains("21.4R3.15"));
            }
            _ => panic!("expected Data reply for Junos custom RPC"),
        }
    }

    #[test]
    fn test_parse_junos_multi_re_reply() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="8">
  <multi-routing-engine-results>
    <multi-routing-engine-item>
      <re-name>node0</re-name>
      <software-information>
        <host-name>vsrx-node0</host-name>
      </software-information>
    </multi-routing-engine-item>
  </multi-routing-engine-results>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "8").unwrap();
        match result {
            RpcReply::Data(data) => {
                assert!(data.contains("<multi-routing-engine-results>"));
                assert!(data.contains("node0"));
            }
            _ => panic!("expected Data reply for multi-RE response"),
        }
    }

    #[test]
    fn test_parse_warning_with_ok() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="10">
  <rpc-error>
    <error-type>application</error-type>
    <error-tag>operation-failed</error-tag>
    <error-severity>warning</error-severity>
    <error-message>statement not found</error-message>
  </rpc-error>
  <ok/>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "10").unwrap();
        match result {
            RpcReply::OkWithWarnings(warnings) => {
                assert_eq!(warnings.len(), 1);
                assert_eq!(warnings[0].severity, Some(ErrorSeverity::Warning));
                assert!(warnings[0].message.contains("statement not found"));
            }
            _ => panic!("expected OkWithWarnings, got {result:?}"),
        }
    }

    #[test]
    fn test_parse_warning_with_data() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="11">
  <rpc-error>
    <error-type>application</error-type>
    <error-tag>operation-failed</error-tag>
    <error-severity>warning</error-severity>
    <error-message>some warning</error-message>
  </rpc-error>
  <data><configuration><system/></configuration></data>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "11").unwrap();
        match result {
            RpcReply::DataWithWarnings(data, warnings) => {
                assert!(data.contains("<configuration>"));
                assert_eq!(warnings.len(), 1);
                assert!(warnings[0].message.contains("some warning"));
            }
            _ => panic!("expected DataWithWarnings, got {result:?}"),
        }
    }

    #[test]
    fn test_parse_mixed_warning_and_error() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="12">
  <rpc-error>
    <error-type>application</error-type>
    <error-tag>operation-failed</error-tag>
    <error-severity>warning</error-severity>
    <error-message>just a warning</error-message>
  </rpc-error>
  <rpc-error>
    <error-type>application</error-type>
    <error-tag>invalid-value</error-tag>
    <error-severity>error</error-severity>
    <error-message>real error</error-message>
  </rpc-error>
</rpc-reply>"#;
        let err = parse_rpc_reply(xml, "12").unwrap_err();
        match err {
            RpcError::ServerError { tag, message, .. } => {
                assert_eq!(tag, ErrorTag::InvalidValue);
                assert_eq!(message, "real error");
            }
            _ => panic!("expected ServerError for hard error, got {err:?}"),
        }
    }

    #[test]
    fn test_parse_empty_rpc_reply_returns_ok() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="42">
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "42").unwrap();
        assert!(matches!(result, RpcReply::Ok));
    }

    #[test]
    fn test_reconstructed_data_reescapes_special_chars() {
        // A device returns text containing XML special characters (encoded on
        // the wire). The reconstructed `data` must re-escape them so the result
        // is itself well-formed XML, not a corrupted string.
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="1">
  <data><description>a &amp; b &lt; c</description></data>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "1").unwrap();
        let data = match result {
            RpcReply::Data(data) => data,
            other => panic!("expected Data, got {other:?}"),
        };
        // The raw `&` / `<` must NOT appear unescaped in element text.
        assert!(
            data.contains("a &amp; b &lt; c"),
            "special chars must be re-escaped: {data}"
        );
        // The reconstructed fragment must re-parse as well-formed XML.
        validate_xml_fragment(&data).expect("reconstructed data must be well-formed");
    }

    #[test]
    fn test_reconstructed_junos_inner_reescapes_special_chars() {
        // Same guarantee for the Junos custom-RPC path (no <data> wrapper).
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="2">
  <output>value with &amp; ampersand</output>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "2").unwrap();
        let data = match result {
            RpcReply::Data(data) => data,
            other => panic!("expected Data, got {other:?}"),
        };
        assert!(
            data.contains("&amp;"),
            "ampersand must stay escaped: {data}"
        );
        validate_xml_fragment(&data).expect("reconstructed inner content must be well-formed");
    }

    #[test]
    fn test_error_message_with_entities_is_fully_decoded() {
        // Junos error messages routinely contain <, >, & (e.g. quoting config
        // syntax). The decoded message must contain the full text, not a
        // truncated fragment around the entity.
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="5">
  <rpc-error>
    <error-type>protocol</error-type>
    <error-tag>operation-failed</error-tag>
    <error-severity>error</error-severity>
    <error-message>syntax error before &lt;get&gt; &amp; after</error-message>
  </rpc-error>
</rpc-reply>"#;
        let err = parse_rpc_reply(xml, "5").unwrap_err();
        match err {
            RpcError::ServerError { message, .. } => {
                assert_eq!(message, "syntax error before <get> & after");
            }
            other => panic!("expected ServerError, got {other:?}"),
        }
    }

    #[test]
    fn test_data_text_with_char_ref_roundtrips() {
        // Numeric character references must survive data reconstruction.
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="6">
  <data><description>A &#38; B &#x3C; C</description></data>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "6").unwrap();
        let data = match result {
            RpcReply::Data(data) => data,
            other => panic!("expected Data, got {other:?}"),
        };
        validate_xml_fragment(&data).expect("reconstructed data must be well-formed");
        // Semantic check: independently unescaping the reconstructed XML must
        // yield the full original text (no truncation around the refs).
        let decoded = quick_xml::escape::unescape(&data).expect("must unescape");
        assert!(
            decoded.contains("A & B < C"),
            "char refs must round-trip: {decoded}"
        );
    }

    #[test]
    fn test_error_info_with_entities_stays_well_formed() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="7">
  <rpc-error>
    <error-type>application</error-type>
    <error-tag>operation-failed</error-tag>
    <error-severity>error</error-severity>
    <error-message>bad element</error-message>
    <error-info><bad-element>a &amp; b</bad-element></error-info>
  </rpc-error>
</rpc-reply>"#;
        let err = parse_rpc_reply(xml, "7").unwrap_err();
        match err {
            RpcError::ServerError {
                info: Some(info), ..
            } => {
                validate_xml_fragment(&info).expect("error-info must stay well-formed");
                let decoded = quick_xml::escape::unescape(&info).expect("must unescape");
                assert!(
                    decoded.contains("a & b"),
                    "entity in error-info must round-trip: {decoded}"
                );
            }
            other => panic!("expected ServerError with info, got {other:?}"),
        }
    }

    #[test]
    fn test_data_preserves_namespace_prefixes() {
        // Prefixed elements must keep their prefix in reconstructed data;
        // stripping it detaches the element from its namespace.
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="8">
  <data><if:interfaces xmlns:if="urn:ietf:params:xml:ns:yang:ietf-interfaces"><if:interface/></if:interfaces></data>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "8").unwrap();
        let data = match result {
            RpcReply::Data(data) => data,
            other => panic!("expected Data, got {other:?}"),
        };
        assert!(
            data.contains("<if:interfaces") && data.contains("</if:interfaces>"),
            "namespace prefix must be preserved: {data}"
        );
        assert!(
            data.contains("<if:interface/>"),
            "prefix on empty element must be preserved: {data}"
        );
    }

    #[test]
    fn test_data_preserves_cdata_content() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="9">
  <data><description><![CDATA[uplink & transit]]></description></data>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "9").unwrap();
        let data = match result {
            RpcReply::Data(data) => data,
            other => panic!("expected Data, got {other:?}"),
        };
        validate_xml_fragment(&data).expect("reconstructed data must be well-formed");
        let decoded = quick_xml::escape::unescape(&data).expect("must unescape");
        assert!(
            decoded.contains("uplink & transit"),
            "CDATA content must not be dropped: {decoded}"
        );
    }

    #[test]
    fn test_error_message_cdata_is_captured() {
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="10">
  <rpc-error>
    <error-type>application</error-type>
    <error-tag>operation-failed</error-tag>
    <error-severity>error</error-severity>
    <error-message><![CDATA[bad & input]]></error-message>
  </rpc-error>
</rpc-reply>"#;
        let err = parse_rpc_reply(xml, "10").unwrap_err();
        match err {
            RpcError::ServerError { message, .. } => {
                assert_eq!(message, "bad & input");
            }
            other => panic!("expected ServerError, got {other:?}"),
        }
    }

    #[test]
    fn test_data_escapes_double_quote_in_attribute() {
        // A single-quoted source attribute may contain a raw double quote;
        // reconstruction wraps attributes in double quotes, so it must be
        // escaped or the output is malformed.
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="11">
  <data><x note='he said "up"'/></data>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "11").unwrap();
        let data = match result {
            RpcReply::Data(data) => data,
            other => panic!("expected Data, got {other:?}"),
        };
        validate_xml_fragment(&data).expect("reconstructed data must be well-formed");
        assert!(
            data.contains("&quot;up&quot;"),
            "double quotes in attribute values must be escaped: {data}"
        );
    }

    #[test]
    fn test_top_level_empty_element_is_data() {
        // A Junos custom RPC can answer with a single empty element directly
        // under <rpc-reply>; that is data, not a bare <ok/>.
        let xml = r#"<rpc-reply xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="12">
  <software-information/>
</rpc-reply>"#;
        let result = parse_rpc_reply(xml, "12").unwrap();
        match result {
            RpcReply::Data(data) => {
                assert!(
                    data.contains("<software-information/>"),
                    "empty element must be captured: {data}"
                );
            }
            other => panic!("expected Data, got {other:?}"),
        }
    }
}