Skip to main content

netconf_async/
connection.rs

1//! NETCONF session: hello exchange, typed RPCs, and teardown.
2
3use crate::error::{NetconfClientError, NetconfClientResult};
4use crate::message::{
5    CopySource, Datastore, DefaultOperation, EditContent, ErrorOption, Filter, Hello, Rpc,
6    RpcOperation, RpcReply, Source, TestOption, WithDefaultsValue, capability_id, from_xml,
7};
8use crate::transport::Transport;
9use crate::{INTERLEAVE_CAP, NETCONF_BASE_11_CAP, NETCONF_URN, NOTIFICATION_CAP};
10use core::fmt;
11#[cfg(feature = "tokio")]
12use core::time::Duration;
13use log::{debug, trace, warn};
14use std::collections::VecDeque;
15#[cfg(feature = "tokio")]
16use tokio::sync::mpsc::Sender;
17
18/// Drop the oldest notification when this many sit unread.
19const MAX_NOTIFICATION_BUFFER: usize = 256;
20
21/// Active NETCONF session on top of a [`Transport`].
22///
23/// Constructed via [`Connection::new`], which exchanges `<hello>` and upgrades
24/// to 1.1 framing when the server advertises [`crate::NETCONF_BASE_11_CAP`].
25///
26/// Call [`Connection::close_session`] when finished; dropping a session that is
27/// still open only logs a warning, because a clean shutdown needs to await I/O.
28pub struct Connection {
29    pub(crate) transport: Box<dyn Transport + Send + 'static>,
30
31    session_id: Option<u64>,
32    capabilities: Vec<String>,
33    parse_replies: bool,
34    warnings_as_errors: bool,
35    next_message_id: u64,
36    is_closed: bool,
37    desynchronized: bool,
38    notification_buffer: VecDeque<String>,
39    #[cfg(feature = "tokio")]
40    timeout: Option<Duration>,
41}
42
43impl fmt::Debug for Connection {
44    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45        let mut dbg = f.debug_struct("Connection");
46        dbg.field("session_id", &self.session_id)
47            .field("capabilities", &self.capabilities)
48            .field("parse_replies", &self.parse_replies)
49            .field("warnings_as_errors", &self.warnings_as_errors)
50            .field("is_closed", &self.is_closed)
51            .field("desynchronized", &self.desynchronized)
52            .field("notification_buffer", &self.notification_buffer.len());
53        #[cfg(feature = "tokio")]
54        dbg.field("timeout", &self.timeout);
55        dbg.finish_non_exhaustive()
56    }
57}
58
59impl Connection {
60    /// Open a session: send client `<hello>`, parse the server hello, upgrade
61    /// the framer if the server advertised `:base:1.1`.
62    pub async fn new<T>(transport: T) -> NetconfClientResult<Connection>
63    where
64        T: Transport + 'static,
65    {
66        let mut conn = Connection {
67            transport: Box::from(transport),
68            session_id: None,
69            capabilities: Vec::new(),
70            parse_replies: true,
71            warnings_as_errors: false,
72            next_message_id: 1,
73            is_closed: false,
74            desynchronized: false,
75            notification_buffer: VecDeque::new(),
76            #[cfg(feature = "tokio")]
77            timeout: None,
78        };
79        conn.session_id = conn.hello().await?;
80        Ok(conn)
81    }
82
83    /// Whether replies are parsed as [`RpcReply`]; on by default.
84    ///
85    /// With parsing off, [`raw_rpc`](Self::raw_rpc) and the typed operations
86    /// return the device's XML untouched and an `<rpc-error>` is *not* turned
87    /// into [`NetconfClientError::Netconf`]. `message-id` is still checked
88    /// when the reply can be parsed.
89    pub fn set_parse_replies(&mut self, parse_replies: bool) {
90        self.parse_replies = parse_replies;
91    }
92
93    /// True when replies are parsed and error-severity `<rpc-error>` is surfaced.
94    pub fn parse_replies(&self) -> bool {
95        self.parse_replies
96    }
97
98    /// Treat warning-severity `<rpc-error>` as [`NetconfClientError::Netconf`].
99    ///
100    /// Off by default: `<rpc-error severity="warning">` plus `<ok/>` is
101    /// success, and the warnings stay in the returned XML (or come back from
102    /// [`Self::raw_rpc_with_warnings`]). Turn this on to fail the RPC instead.
103    pub fn set_warnings_as_errors(&mut self, warnings_as_errors: bool) {
104        self.warnings_as_errors = warnings_as_errors;
105    }
106
107    /// True when warning-severity `<rpc-error>` fails the RPC.
108    pub fn warnings_as_errors(&self) -> bool {
109        self.warnings_as_errors
110    }
111
112    /// Fail an RPC that gets no reply within `timeout`; unlimited by default.
113    ///
114    /// A timed-out RPC leaves the session unusable, because the reply may still
115    /// arrive and would be read as the answer to the next request. Later calls
116    /// fail with [`NetconfClientError::SessionDesynchronized`].
117    #[cfg(feature = "tokio")]
118    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
119    pub fn set_timeout(&mut self, timeout: Option<Duration>) {
120        self.timeout = timeout;
121    }
122
123    /// Server-assigned session-id from `<hello>`, if the server sent one.
124    pub fn session_id(&self) -> Option<u64> {
125        self.session_id
126    }
127
128    /// Server capabilities from the `<hello>` exchange.
129    pub fn capabilities(&self) -> &[String] {
130        &self.capabilities
131    }
132
133    /// True if the server advertised `capability` (query string ignored).
134    pub fn has_capability(&self, capability: &str) -> bool {
135        self.capabilities
136            .iter()
137            .any(|cap| capability_id(cap) == capability)
138    }
139
140    async fn hello(&mut self) -> NetconfClientResult<Option<u64>> {
141        let hello = Hello::new();
142        let response = self.write_and_receive(&hello.to_string(), false).await?;
143        trace!("hello:\n{}", response);
144
145        let hello: Hello = from_xml(&response)?;
146        self.capabilities = hello.capabilities();
147        if hello.has_capability(NETCONF_BASE_11_CAP) {
148            debug!("server advertised :base:1.1; switching to chunked framing");
149            self.transport.upgrade().await;
150        } else {
151            debug!("server did not advertise :base:1.1; staying on 1.0 framing");
152        }
153        Ok(hello.session_id())
154    }
155
156    /// GetConfig implements the `<get-config>` rpc operation defined in [RFC6241 7.1].
157    /// `source` is the datastore to query.
158    ///
159    /// [RFC6241 7.1]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.1
160    pub async fn get_config(
161        &mut self,
162        datastore: Datastore,
163        filter: Option<Filter>,
164        defaults: Option<WithDefaultsValue>,
165    ) -> NetconfClientResult<String> {
166        let get_config =
167            Rpc::new_with_operation(RpcOperation::new_get_config(datastore, filter, defaults));
168        self.run_rpc(get_config).await
169    }
170
171    /// `<get>` operational state ([RFC6241 7.7](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.7)).
172    pub async fn get(
173        &mut self,
174        filter: Option<Filter>,
175        defaults: Option<WithDefaultsValue>,
176    ) -> NetconfClientResult<String> {
177        let get = Rpc::new_with_operation(RpcOperation::new_get(filter, defaults));
178        self.run_rpc(get).await
179    }
180
181    /// `<validate>` ([RFC6241 8.6.4.1](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.6.4.1)).
182    pub async fn validate(&mut self, datastore: Datastore) -> NetconfClientResult<String> {
183        let validate = Rpc::new_with_operation(RpcOperation::Validate {
184            source: Source { datastore },
185        });
186        self.run_rpc(validate).await
187    }
188
189    /// EditConfig implements the `<edit-config>` rpc operation defined in [RFC6241 7.2].
190    ///
191    /// [RFC6241 7.2]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.2
192    pub async fn edit_config(
193        &mut self,
194        target: Datastore,
195        content: EditContent,
196        default_operation: Option<DefaultOperation>,
197        test_option: Option<TestOption>,
198        error_option: Option<ErrorOption>,
199    ) -> NetconfClientResult<String> {
200        let rpc = Rpc::new_with_operation(RpcOperation::new_edit_config(
201            target,
202            content,
203            default_operation,
204            test_option,
205            error_option,
206        ));
207        self.run_rpc(rpc).await
208    }
209
210    /// CopyConfig implements the `<copy-config>` rpc operation defined in [RFC6241 7.3].
211    ///
212    /// [RFC6241 7.3]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.3
213    pub async fn copy_config(
214        &mut self,
215        source: CopySource,
216        target: Datastore,
217    ) -> NetconfClientResult<String> {
218        let rpc = Rpc::new_with_operation(RpcOperation::new_copy_config(source, target));
219        self.run_rpc(rpc).await
220    }
221
222    /// DeleteConfig implements the `<delete-config>` rpc operation defined in [RFC6241 7.4].
223    ///
224    /// [RFC6241 7.4]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.4
225    pub async fn delete_config(&mut self, target: Datastore) -> NetconfClientResult<String> {
226        let rpc = Rpc::new_with_operation(RpcOperation::new_delete_config(target));
227        self.run_rpc(rpc).await
228    }
229
230    /// Lock implements the `<lock>` rpc operation defined in [RFC6241 7.5].
231    ///
232    /// [RFC6241 7.5]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.5
233    pub async fn lock(&mut self, target: Datastore) -> NetconfClientResult<String> {
234        let rpc = Rpc::new_with_operation(RpcOperation::new_lock(target));
235        self.run_rpc(rpc).await
236    }
237
238    /// Unlock implements the `<unlock>` rpc operation defined in [RFC6241 7.6].
239    ///
240    /// [RFC6241 7.6]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.6
241    pub async fn unlock(&mut self, target: Datastore) -> NetconfClientResult<String> {
242        let rpc = Rpc::new_with_operation(RpcOperation::new_unlock(target));
243        self.run_rpc(rpc).await
244    }
245
246    /// `<commit>` of the candidate datastore ([RFC6241 8.3.4.1](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.3.4.1)).
247    pub async fn commit(&mut self) -> NetconfClientResult<String> {
248        let commit = Rpc::new_with_operation(RpcOperation::new_commit(None, None, None, None));
249        self.run_rpc(commit).await
250    }
251
252    /// Confirmed `<commit>` ([RFC6241 8.4](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.4)).
253    ///
254    /// `persist` lets another session confirm later via [`Self::confirm_commit`].
255    pub async fn confirmed_commit(
256        &mut self,
257        confirm_timeout: Option<i32>,
258        persist: Option<String>,
259        persist_id: Option<String>,
260    ) -> NetconfClientResult<String> {
261        let commit = Rpc::new_with_operation(RpcOperation::new_commit(
262            Some(()),
263            confirm_timeout,
264            persist,
265            persist_id,
266        ));
267        self.run_rpc(commit).await
268    }
269
270    /// Confirm a previous persist confirmed-commit ([RFC6241 8.4.4.2](https://www.rfc-editor.org/rfc/rfc6241.html#section-8.4.4.2)).
271    pub async fn confirm_commit(&mut self, persist_id: String) -> NetconfClientResult<String> {
272        let commit =
273            Rpc::new_with_operation(RpcOperation::new_commit(None, None, None, Some(persist_id)));
274        self.run_rpc(commit).await
275    }
276
277    /// CancelCommit implements the `<cancel-commit>` rpc operation defined in [RFC6241 8.4.4.1].
278    ///
279    /// [RFC6241 8.4.4.1]: https://www.rfc-editor.org/rfc/rfc6241.html#section-8.4.4.1
280    pub async fn cancel_commit(
281        &mut self,
282        persist_id: Option<String>,
283    ) -> NetconfClientResult<String> {
284        let rpc = Rpc::new_with_operation(RpcOperation::new_cancel_commit(persist_id));
285        self.run_rpc(rpc).await
286    }
287
288    /// DiscardChanges implements the `<discard-changes>` rpc operation defined in [RFC6241 8.3.4.2].
289    ///
290    /// [RFC6241 8.3.4.2]: https://www.rfc-editor.org/rfc/rfc6241.html#section-8.3.4.2
291    pub async fn discard_changes(&mut self) -> NetconfClientResult<String> {
292        let rpc = Rpc::new_with_operation(RpcOperation::new_discard_changes());
293        self.run_rpc(rpc).await
294    }
295
296    /// `<close-session>` ([RFC6241 7.8](https://www.rfc-editor.org/rfc/rfc6241.html#section-7.8)).
297    ///
298    /// Also tears the transport down. A transport that fails to close is logged
299    /// rather than returned, because the device has already ended the session.
300    pub async fn close_session(&mut self) -> NetconfClientResult<String> {
301        let close_session = Rpc::new_with_operation(RpcOperation::CloseSession);
302        self.is_closed = true;
303        let reply = self.run_rpc(close_session).await;
304        if let Err(err) = self.transport.close().await {
305            debug!("transport close after <close-session> failed: {}", err);
306        }
307        reply
308    }
309
310    /// KillSession implements the `<kill-session>` rpc operation defined in [RFC6241 7.9].
311    /// Terminates another NETCONF session; this connection stays open.
312    ///
313    /// [RFC6241 7.9]: https://www.rfc-editor.org/rfc/rfc6241.html#section-7.9
314    pub async fn kill_session(&mut self, session_id: u64) -> NetconfClientResult<String> {
315        let kill_session = Rpc::new_with_operation(RpcOperation::KillSession { session_id });
316        self.run_rpc(kill_session).await
317    }
318
319    /// Sends a raw XML RPC document and returns the reply.
320    ///
321    /// A document whose root is not `<rpc>` is wrapped in
322    /// `<rpc xmlns="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="N">`.
323    /// An existing `<rpc>` (any prefix) is sent as-is.
324    pub async fn raw_rpc(&mut self, xml: &str) -> NetconfClientResult<String> {
325        let xml = self.ensure_rpc_envelope(xml);
326        self.exchange(
327            &xml,
328            request_message_id(&xml).as_deref(),
329            request_is_commit(&xml),
330            self.warnings_as_errors,
331            &request_operation(&xml),
332        )
333        .await
334    }
335
336    /// Like [`Self::raw_rpc`], but returns warning-severity `<rpc-error>`s
337    /// alongside the raw reply XML.
338    ///
339    /// Error-severity replies still become [`NetconfClientError::Netconf`]
340    /// (unless [`Self::set_parse_replies`] is off). Warning-only replies
341    /// succeed even when [`Self::set_warnings_as_errors`] is on, because this
342    /// method exists to collect them.
343    pub async fn raw_rpc_with_warnings(
344        &mut self,
345        xml: &str,
346    ) -> NetconfClientResult<(String, Vec<crate::message::Error>)> {
347        let xml = self.ensure_rpc_envelope(xml);
348        let response = self
349            .exchange(
350                &xml,
351                request_message_id(&xml).as_deref(),
352                request_is_commit(&xml),
353                false,
354                &request_operation(&xml),
355            )
356            .await?;
357        let warnings = match from_xml::<RpcReply>(&response) {
358            Ok(reply) => reply.warnings().into_iter().cloned().collect(),
359            Err(_) => Vec::new(),
360        };
361        Ok((response, warnings))
362    }
363
364    /// `<create-subscription>` ([RFC5277 2.1.1](https://www.rfc-editor.org/rfc/rfc5277.html#section-2.1.1)).
365    ///
366    /// Does not take over the session. Later RPCs (`get`, `edit_config`, …) stay
367    /// legal; notifications that arrive while those RPCs wait are buffered and
368    /// come back from [`Self::drain_notifications`] / [`Self::recv_notification`].
369    ///
370    /// Missing `:interleave` is logged, not refused. Some devices advertise it
371    /// and then ignore RPCs on the subscribed session — use a second connection
372    /// there. `start_time` / `stop_time` are RFC 3339 replay bounds; `stop_time`
373    /// requires `start_time`.
374    pub async fn create_subscription(
375        &mut self,
376        stream: Option<&str>,
377        filter: Option<Filter>,
378        start_time: Option<&str>,
379        stop_time: Option<&str>,
380    ) -> NetconfClientResult<String> {
381        if !self.has_capability(NOTIFICATION_CAP) {
382            debug!("server did not advertise :notification; create-subscription may fail");
383        }
384        if !self.has_capability(INTERLEAVE_CAP) {
385            debug!("server did not advertise :interleave; RPCs during this subscription may fail");
386        }
387        let rpc = Rpc::new_with_operation(RpcOperation::new_create_subscription(
388            stream, filter, start_time, stop_time,
389        )?);
390        self.run_rpc(rpc).await
391    }
392
393    /// Take every notification buffered during earlier RPCs.
394    pub fn drain_notifications(&mut self) -> Vec<String> {
395        self.notification_buffer.drain(..).collect()
396    }
397
398    /// True when [`Self::drain_notifications`] would return a non-empty list.
399    pub fn has_notifications(&self) -> bool {
400        !self.notification_buffer.is_empty()
401    }
402
403    /// Next notification: buffer first, otherwise one framed message.
404    ///
405    /// Unexpected `<rpc-reply>` / other documents are logged and skipped.
406    /// Transport EOF is an error. This wait is not bounded by
407    /// [`Self::set_timeout`].
408    pub async fn recv_notification(&mut self) -> NetconfClientResult<String> {
409        if let Some(notification) = self.notification_buffer.pop_front() {
410            return Ok(notification);
411        }
412        if self.desynchronized {
413            return Err(NetconfClientError::SessionDesynchronized);
414        }
415        loop {
416            let message = self.transport.receive().await?;
417            if classify_incoming(&message) == Incoming::Notification {
418                return Ok(message);
419            }
420            warn!("Discarding unexpected message while waiting for notification");
421        }
422    }
423
424    /// Subscribe, then forward notifications to `sender` until the device
425    /// closes or the receiver is dropped.
426    ///
427    /// Holds `&mut self` for the whole listen loop, so this connection cannot
428    /// run other RPCs until the future ends. For interleaved RPCs (MCP, a
429    /// caller that `get`s after subscribe) use [`Self::create_subscription`]
430    /// and [`Self::drain_notifications`] / [`Self::recv_notification`] instead.
431    ///
432    /// Cancel-safe to drop; wire shutdown with `tokio::select!`.
433    #[cfg(feature = "tokio")]
434    #[cfg_attr(docsrs, doc(cfg(feature = "tokio")))]
435    pub async fn notification(
436        &mut self,
437        sender: Sender<String>,
438        stream: Option<&str>,
439        filter: Option<Filter>,
440        start_time: Option<&str>,
441        stop_time: Option<&str>,
442    ) -> NetconfClientResult<()> {
443        self.create_subscription(stream, filter, start_time, stop_time)
444            .await?;
445        self.run_notification_loop(sender).await
446    }
447
448    #[cfg(feature = "tokio")]
449    async fn run_notification_loop(&mut self, sender: Sender<String>) -> NetconfClientResult<()> {
450        loop {
451            let notification = self.recv_notification().await?;
452            if sender.send(notification).await.is_err() {
453                // Receiver is gone, so nothing is listening any more.
454                return Ok(());
455            }
456        }
457    }
458
459    fn buffer_notification(&mut self, notification: String) {
460        if self.notification_buffer.len() >= MAX_NOTIFICATION_BUFFER {
461            warn!("Notification buffer full ({MAX_NOTIFICATION_BUFFER}); dropping oldest");
462            self.notification_buffer.pop_front();
463        }
464        self.notification_buffer.push_back(notification);
465    }
466
467    async fn run_rpc(&mut self, mut rpc: Rpc) -> NetconfClientResult<String> {
468        let is_commit = rpc.is_commit();
469        let message_id = self.allocate_message_id();
470        rpc.set_message_id(&message_id);
471        self.exchange(
472            &rpc.to_string(),
473            Some(&message_id),
474            is_commit,
475            self.warnings_as_errors,
476            rpc.operation_name(),
477        )
478        .await
479    }
480
481    fn allocate_message_id(&mut self) -> String {
482        let id = self.next_message_id;
483        self.next_message_id += 1;
484        id.to_string()
485    }
486
487    fn ensure_rpc_envelope(&mut self, xml: &str) -> String {
488        if root_is_rpc(xml) {
489            xml.to_string()
490        } else {
491            wrap_in_rpc(xml, &self.allocate_message_id())
492        }
493    }
494
495    async fn exchange(
496        &mut self,
497        request: &str,
498        expected_message_id: Option<&str>,
499        is_commit: bool,
500        warnings_as_errors: bool,
501        operation: &str,
502    ) -> NetconfClientResult<String> {
503        if self.desynchronized {
504            return Err(NetconfClientError::SessionDesynchronized);
505        }
506        let response = self.write_and_receive(request, is_commit).await?;
507        trace!("rpc:\n{response}");
508
509        let reply = match from_xml::<RpcReply>(&response) {
510            Ok(reply) => reply,
511            Err(err) if self.parse_replies => return Err(err),
512            Err(_) => return Ok(response),
513        };
514
515        if let Some(expected) = expected_message_id
516            && let Some(actual) = reply.message_id()
517            && actual != expected
518        {
519            // The mismatched message is already consumed; the real reply may
520            // still arrive and would be read as the next answer.
521            self.desynchronized = true;
522            return Err(NetconfClientError::MessageIdMismatch {
523                expected: expected.to_string(),
524                actual: actual.to_string(),
525            });
526        }
527
528        if self.parse_replies && reply_is_failure(&reply, warnings_as_errors) {
529            return Err(NetconfClientError::Netconf {
530                operation: operation.to_string(),
531                reply,
532            });
533        }
534        Ok(response)
535    }
536
537    #[cfg(feature = "tokio")]
538    async fn write_and_receive(
539        &mut self,
540        request: &str,
541        is_commit: bool,
542    ) -> NetconfClientResult<String> {
543        let result = if let Some(timeout) = self.timeout {
544            match tokio::time::timeout(timeout, self.write_and_read_reply(request)).await {
545                Ok(result) => result,
546                Err(_) => {
547                    // The reply may still land and would be read as the answer to
548                    // whatever is sent next.
549                    self.desynchronized = true;
550                    return Err(NetconfClientError::Timeout { timeout });
551                }
552            }
553        } else {
554            self.write_and_read_reply(request).await
555        };
556        map_commit_eof(result, is_commit)
557    }
558
559    #[cfg(not(feature = "tokio"))]
560    async fn write_and_receive(
561        &mut self,
562        request: &str,
563        is_commit: bool,
564    ) -> NetconfClientResult<String> {
565        map_commit_eof(self.write_and_read_reply(request).await, is_commit)
566    }
567
568    async fn write_and_read_reply(&mut self, request: &str) -> NetconfClientResult<String> {
569        if let Err(err) = self.transport.write(request).await {
570            return Err(self.invalidate_on_eof(err));
571        }
572        loop {
573            let response = match self.transport.receive().await {
574                Ok(response) => response,
575                Err(err) => return Err(self.invalidate_on_eof(err)),
576            };
577            if classify_incoming(&response) == Incoming::Notification {
578                debug!("buffered notification during rpc");
579                self.buffer_notification(response);
580                continue;
581            }
582            return Ok(response);
583        }
584    }
585
586    fn invalidate_on_eof(&mut self, err: NetconfClientError) -> NetconfClientError {
587        if err.is_unexpected_eof() {
588            self.desynchronized = true;
589        }
590        err
591    }
592}
593
594#[derive(Debug, Clone, Copy, PartialEq, Eq)]
595enum Incoming {
596    Notification,
597    Other,
598}
599
600fn classify_incoming(xml: &str) -> Incoming {
601    match first_element_local_name(xml) {
602        Some("notification") => Incoming::Notification,
603        _ => Incoming::Other,
604    }
605}
606
607fn first_element_local_name(xml: &str) -> Option<&str> {
608    let mut rest = xml;
609    while let Some(idx) = rest.find('<') {
610        rest = &rest[idx + 1..];
611        if rest.starts_with('!') || rest.starts_with('?') || rest.starts_with('/') {
612            continue;
613        }
614        let name_end = rest
615            .find(|c: char| c.is_whitespace() || c == '>' || c == '/')
616            .unwrap_or(rest.len());
617        let name = &rest[..name_end];
618        let local = name.rsplit(':').next().unwrap_or(name);
619        if !local.is_empty() {
620            return Some(local);
621        }
622    }
623    None
624}
625
626fn reply_is_failure(reply: &RpcReply, warnings_as_errors: bool) -> bool {
627    reply.has_errors() || (warnings_as_errors && reply.has_warnings())
628}
629
630fn map_commit_eof(
631    result: NetconfClientResult<String>,
632    is_commit: bool,
633) -> NetconfClientResult<String> {
634    match result {
635        Err(err) if is_commit && err.is_unexpected_eof() => Err(NetconfClientError::CommitUnknown),
636        other => other,
637    }
638}
639
640fn root_local_name(xml: &str) -> Option<&str> {
641    let mut rest = xml;
642    while let Some(idx) = rest.find('<') {
643        rest = &rest[idx + 1..];
644        if rest.starts_with('!') || rest.starts_with('?') || rest.starts_with('/') {
645            continue;
646        }
647        let name_end = rest
648            .find(|c: char| c.is_whitespace() || c == '>' || c == '/')
649            .unwrap_or(rest.len());
650        let name = &rest[..name_end];
651        let local = name.rsplit(':').next().unwrap_or(name);
652        if !local.is_empty() {
653            return Some(local);
654        }
655    }
656    None
657}
658
659fn root_is_rpc(xml: &str) -> bool {
660    root_local_name(xml) == Some("rpc")
661}
662
663fn xml_body_start(xml: &str) -> usize {
664    if let Some(decl) = xml.find("<?xml")
665        && let Some(end) = xml[decl..].find("?>")
666    {
667        return decl + end + 2;
668    }
669    0
670}
671
672fn wrap_in_rpc(xml: &str, message_id: &str) -> String {
673    let (prolog, body) = xml.split_at(xml_body_start(xml));
674    format!("{prolog}<rpc xmlns=\"{NETCONF_URN}\" message-id=\"{message_id}\">{body}</rpc>")
675}
676
677fn request_message_id(xml: &str) -> Option<String> {
678    for key in ["message-id=\"", "message-id='"] {
679        if let Some(start) = xml.find(key) {
680            let rest = &xml[start + key.len()..];
681            let quote = key.chars().next_back()?;
682            if let Some(end) = rest.find(quote) {
683                let id = &rest[..end];
684                if !id.is_empty() {
685                    return Some(id.to_string());
686                }
687            }
688        }
689    }
690    None
691}
692
693/// Local-name of the first child of `<rpc>`, or `"rpc"` if none is found.
694fn request_operation(xml: &str) -> String {
695    let mut rest = xml;
696    let mut seen_rpc = false;
697    while let Some(idx) = rest.find('<') {
698        rest = &rest[idx + 1..];
699        if rest.starts_with('!') || rest.starts_with('?') || rest.starts_with('/') {
700            continue;
701        }
702        let name_end = rest
703            .find(|c: char| c.is_whitespace() || c == '>' || c == '/')
704            .unwrap_or(rest.len());
705        let name = &rest[..name_end];
706        let local = name.rsplit(':').next().unwrap_or(name);
707        if !seen_rpc {
708            if local == "rpc" {
709                seen_rpc = true;
710            }
711            continue;
712        }
713        if !local.is_empty() {
714            return local.to_string();
715        }
716    }
717    "rpc".to_string()
718}
719
720/// True when the document contains a `<commit>` or `<commit-configuration>`.
721///
722/// `<cancel-commit>` and `<commit-id>` do not match: their local names differ.
723fn request_is_commit(xml: &str) -> bool {
724    let mut rest = xml;
725    while let Some(idx) = rest.find('<') {
726        rest = &rest[idx + 1..];
727        if rest.starts_with('!') || rest.starts_with('?') || rest.starts_with('/') {
728            continue;
729        }
730        let name_end = rest
731            .find(|c: char| c.is_whitespace() || c == '>' || c == '/')
732            .unwrap_or(rest.len());
733        let name = &rest[..name_end];
734        let local = name.rsplit(':').next().unwrap_or(name);
735        if local == "commit" || local == "commit-configuration" {
736            return true;
737        }
738    }
739    false
740}
741
742impl Drop for Connection {
743    fn drop(&mut self) {
744        if !self.is_closed {
745            warn!("NETCONF session dropped without close_session; the device may hold it open");
746        }
747    }
748}
749
750#[cfg(test)]
751mod tests {
752    use super::{
753        Incoming, classify_incoming, request_is_commit, request_message_id, request_operation,
754        root_is_rpc, wrap_in_rpc,
755    };
756    use crate::message::capability_id;
757    use crate::{CANDIDATE_CAP, URL_CAP};
758
759    #[test]
760    fn capability_id_strips_query() {
761        assert_eq!(capability_id(CANDIDATE_CAP), CANDIDATE_CAP);
762        assert_eq!(
763            capability_id(&format!("{URL_CAP}?scheme=http,ftp,file")),
764            URL_CAP
765        );
766    }
767
768    #[test]
769    fn request_message_id_reads_double_and_single_quotes() {
770        assert_eq!(
771            request_message_id(r#"<rpc message-id="abc-123"><get/></rpc>"#).as_deref(),
772            Some("abc-123")
773        );
774        assert_eq!(
775            request_message_id("<rpc message-id='x'><get/></rpc>").as_deref(),
776            Some("x")
777        );
778        assert_eq!(request_message_id("<rpc><get/></rpc>"), None);
779    }
780
781    #[test]
782    fn request_is_commit_matches_commit_and_junos_not_cancel() {
783        assert!(request_is_commit("<rpc><commit/></rpc>"));
784        assert!(request_is_commit(
785            r#"<rpc><nc:commit xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"/></rpc>"#
786        ));
787        assert!(request_is_commit("<rpc><commit-configuration/></rpc>"));
788        assert!(request_is_commit("<rpc><commit confirmed/></rpc>"));
789        assert!(!request_is_commit("<rpc><cancel-commit/></rpc>"));
790        assert!(!request_is_commit(
791            "<rpc><get><commit-id>1</commit-id></get></rpc>"
792        ));
793        assert!(!request_is_commit("<rpc><get/></rpc>"));
794    }
795
796    #[test]
797    fn wrap_in_rpc_adds_envelope_and_keeps_existing_rpc() {
798        assert!(root_is_rpc("<rpc><get/></rpc>"));
799        assert!(root_is_rpc(
800            r#"<nc:rpc xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"><nc:get/></nc:rpc>"#
801        ));
802        assert!(!root_is_rpc("<get-interface-information/>"));
803
804        let wrapped = wrap_in_rpc("<get-interface-information/>", "3");
805        assert_eq!(
806            wrapped,
807            concat!(
808                "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"3\">",
809                "<get-interface-information/>",
810                "</rpc>",
811            )
812        );
813        assert_eq!(request_operation(&wrapped), "get-interface-information");
814        assert_eq!(request_message_id(&wrapped).as_deref(), Some("3"));
815
816        let with_decl = wrap_in_rpc("<?xml version=\"1.0\"?>\n<get-interface-information/>", "1");
817        assert!(with_decl.starts_with("<?xml version=\"1.0\"?>"));
818        assert!(root_is_rpc(&with_decl));
819        assert_eq!(request_operation(&with_decl), "get-interface-information");
820    }
821
822    #[test]
823    fn request_operation_reads_first_child_of_rpc() {
824        assert_eq!(request_operation("<rpc><get-config/></rpc>"), "get-config");
825        assert_eq!(
826            request_operation(
827                r#"<nc:rpc xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0"><nc:edit-config/></nc:rpc>"#
828            ),
829            "edit-config"
830        );
831        assert_eq!(
832            request_operation("<rpc message-id='1'><lock/></rpc>"),
833            "lock"
834        );
835        assert_eq!(request_operation("<rpc/>"), "rpc");
836        assert_eq!(request_operation("<hello/>"), "rpc");
837    }
838
839    #[test]
840    fn classify_incoming_uses_root_local_name() {
841        assert_eq!(
842            classify_incoming(
843                r#"<notification xmlns="urn:ietf:params:xml:ns:netconf:notification:1.0"/>"#
844            ),
845            Incoming::Notification
846        );
847        assert_eq!(
848            classify_incoming(
849                r#"<nc:notification xmlns:nc="urn:ietf:params:xml:ns:netconf:notification:1.0"><eventTime>t</eventTime></nc:notification>"#
850            ),
851            Incoming::Notification
852        );
853        assert_eq!(
854            classify_incoming(r#"<?xml version="1.0"?><notification/>"#),
855            Incoming::Notification
856        );
857        assert_eq!(
858            classify_incoming(r#"<rpc-reply message-id="1"><ok/></rpc-reply>"#),
859            Incoming::Other
860        );
861        assert_eq!(
862            classify_incoming(
863                r#"<rpc-reply><notification xmlns="urn:ietf:params:xml:ns:netconf:notification:1.0"/></rpc-reply>"#
864            ),
865            Incoming::Other
866        );
867    }
868}