Skip to main content

opcua_kit/discovery/
mod.rs

1//! Synchronous OPC UA GetEndpoints over UA TCP. Uses the Rust standard library.
2#![forbid(unsafe_code)]
3mod binary;
4mod transport;
5
6use binary::{Decoder, Encoder};
7use std::{
8    error::Error,
9    fmt, io,
10    time::{Duration, SystemTime, UNIX_EPOCH},
11};
12use transport::Connection;
13
14const POLICY_NONE: &str = "http://opcfoundation.org/UA/SecurityPolicy#None";
15const OPEN_REQUEST: u16 = 446;
16const OPEN_RESPONSE: u16 = 449;
17const ENDPOINTS_REQUEST: u16 = 428;
18const ENDPOINTS_RESPONSE: u16 = 431;
19const CLOSE_REQUEST: u16 = 452;
20
21/// Errors from address validation, UA TCP transport or the discovery service.
22#[derive(Debug)]
23pub enum DiscoveryError {
24    /// Expected an explicit OPC TCP host and port.
25    InvalidEndpoint,
26    /// The socket timeout must be between one millisecond and one minute.
27    InvalidTimeout,
28    /// Address resolution or socket I/O failed.
29    Io(io::Error),
30    /// The response was malformed, out of sequence, or exceeded a local limit.
31    Protocol(&'static str),
32    /// Raw UA TCP, chunk-abort or service status supplied by the peer.
33    Status(u32),
34}
35impl From<io::Error> for DiscoveryError {
36    fn from(e: io::Error) -> Self {
37        Self::Io(e)
38    }
39}
40impl fmt::Display for DiscoveryError {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        match self {
43            Self::InvalidEndpoint => {
44                f.write_str("expected opc.tcp://HOST:PORT with an optional path")
45            }
46            Self::InvalidTimeout => f.write_str("discovery timeout must be between 1 ms and 60 s"),
47            Self::Io(e) => write!(f, "discovery transport: {e}"),
48            Self::Protocol(reason) => write!(f, "invalid discovery response: {reason}"),
49            Self::Status(status) => write!(f, "discovery returned OPC UA status 0x{status:08X}"),
50        }
51    }
52}
53impl Error for DiscoveryError {
54    fn source(&self) -> Option<&(dyn Error + 'static)> {
55        match self {
56            Self::Io(e) => Some(e),
57            _ => None,
58        }
59    }
60}
61
62/// Server-advertised user token policy. Token kinds 0, 1, 2 and 3 denote
63/// anonymous, user name, certificate and issued token, respectively.
64#[derive(Clone, Debug, Eq, PartialEq)]
65#[cfg_attr(feature = "commissioning", derive(serde::Serialize))]
66pub struct EndpointToken {
67    /// Policy identifier chosen by the server.
68    pub policy_id: String,
69    /// Raw OPC UA UserTokenType.
70    pub kind: u32,
71    /// Empty means to inherit the endpoint policy.
72    pub security_policy_uri: String,
73}
74
75/// Unauthenticated discovery information. Independently approve the server leaf and URI before connecting.
76#[derive(Clone, Debug, Eq, PartialEq)]
77#[cfg_attr(feature = "commissioning", derive(serde::Serialize))]
78pub struct EndpointInfo {
79    /// Unverified certificate chain supplied in GetEndpoints.
80    #[cfg(feature = "client")]
81    #[cfg_attr(feature = "commissioning", serde(skip))]
82    pub(crate) certificate: Vec<u8>,
83    /// Server-advertised endpoint URL.
84    pub endpoint_url: String,
85    /// Server-advertised application identity.
86    pub application_uri: String,
87    /// Raw MessageSecurityMode (1 None, 2 Sign, 3 SignAndEncrypt).
88    pub security_mode: u32,
89    /// Advertised secure-channel policy.
90    pub security_policy_uri: String,
91    /// Advertised transport profile.
92    pub transport_profile_uri: String,
93    /// User token policies in server order.
94    pub user_tokens: Vec<EndpointToken>,
95}
96
97#[cfg(feature = "client")]
98pub(crate) use transport::{address, secure_socket};
99
100fn request(kind: u16, handle: u32, timeout: Duration) -> Encoder {
101    let mut out = Encoder::default();
102    out.node(kind);
103    out.node(0); // Discovery has no session authentication token.
104    let since_epoch = SystemTime::now()
105        .duration_since(UNIX_EPOCH)
106        .unwrap_or_default();
107    let ticks = since_epoch.as_nanos() / 100 + 116_444_736_000_000_000;
108    out.0.extend_from_slice(&(ticks as i64).to_le_bytes());
109    out.u32(handle);
110    out.u32(0); // No diagnostics requested.
111    out.null();
112    out.u32(timeout.as_millis() as u32);
113    out.0.extend_from_slice(&[0, 0, 0]); // Null additional header.
114    out
115}
116
117/// Discover up to 64 endpoints at one explicit URL without sending credentials.
118/// The timeout covers socket operations after system DNS resolution. Returned
119/// identities, policies and URLs are advertisements requiring independent review.
120pub fn discover_endpoints(
121    endpoint: &str,
122    timeout: Duration,
123) -> Result<Vec<EndpointInfo>, DiscoveryError> {
124    if !(Duration::from_millis(1)..=Duration::from_secs(60)).contains(&timeout) {
125        return Err(DiscoveryError::InvalidTimeout);
126    }
127    let mut conn = Connection::connect(endpoint, timeout)?;
128    let mut open = request(OPEN_REQUEST, 1, timeout);
129    open.u32(0); // ProtocolVersion.
130    open.u32(0); // Issue.
131    open.u32(1); // MessageSecurityMode None for discovery.
132    open.null();
133    open.u32(60_000);
134    conn.send(b"OPN", 1, &open)?;
135    let body = conn.receive(b"OPN", 1)?;
136    let mut r = Decoder::new(&body);
137    r.response(OPEN_RESPONSE, 1)?;
138    if r.u32()? != 0 {
139        return Err(DiscoveryError::Protocol("unsupported protocol version"));
140    }
141    let channel = r.u32()?;
142    let token = r.u32()?;
143    r.take(8)?; // CreatedAt.
144    let lifetime = r.u32()?;
145    r.blob(4096)?;
146    r.finish()?;
147    if channel != conn.channel || token == 0 || lifetime == 0 {
148        return Err(DiscoveryError::Protocol("invalid security token"));
149    }
150    conn.token = token;
151    let mut query = request(ENDPOINTS_REQUEST, 2, timeout);
152    query.blob(endpoint.as_bytes());
153    query.u32(0); // All locales.
154    query.u32(0); // All transport profiles.
155    conn.send(b"MSG", 2, &query)?;
156    let body = conn.receive(b"MSG", 2)?;
157    let mut r = Decoder::new(&body);
158    r.response(ENDPOINTS_RESPONSE, 2)?;
159    let mut endpoints = Vec::new();
160    for _ in 0..r.count(64)? {
161        endpoints.push(read_endpoint(&mut r)?);
162    }
163    r.finish()?;
164    // CloseSecureChannel has no response. The socket also closes on every error path.
165    let _ = conn.send(b"CLO", 3, &request(CLOSE_REQUEST, 3, timeout));
166    Ok(endpoints)
167}
168
169fn read_endpoint(r: &mut Decoder<'_>) -> Result<EndpointInfo, DiscoveryError> {
170    let endpoint_url = r.text()?.to_owned();
171    let application_uri = r.text()?.to_owned();
172    r.text()?; // ProductUri.
173    r.localized_text()?;
174    r.u32()?; // ApplicationType.
175    r.text()?; // GatewayServerUri.
176    r.text()?; // DiscoveryProfileUri.
177    for _ in 0..r.count(256)? {
178        r.text()?;
179    }
180    let certificate = r.blob(1024 * 1024)?;
181    #[cfg(not(feature = "client"))]
182    let _ = certificate;
183    let security_mode = r.u32()?;
184    let security_policy_uri = r.text()?.to_owned();
185    let mut user_tokens = Vec::new();
186    for _ in 0..r.count(64)? {
187        let policy_id = r.text()?.to_owned();
188        let kind = r.u32()?;
189        r.text()?; // IssuedTokenType.
190        r.text()?; // IssuerEndpointUrl.
191        user_tokens.push(EndpointToken {
192            policy_id,
193            kind,
194            security_policy_uri: r.text()?.to_owned(),
195        });
196    }
197    let transport_profile_uri = r.text()?.to_owned();
198    r.take(1)?; // SecurityLevel.
199    Ok(EndpointInfo {
200        #[cfg(feature = "client")]
201        certificate: certificate.to_owned(),
202        endpoint_url,
203        application_uri,
204        security_mode,
205        security_policy_uri,
206        user_tokens,
207        transport_profile_uri,
208    })
209}