Skip to main content

opcua_kit/
server.rs

1//! Serve host-owned scalar variables in an OPC UA address space.
2//! The application owns the event loop, values and shutdown signal.
3mod address;
4mod services;
5mod subscriptions;
6mod transport;
7
8pub use crate::secure_channel::SecurityPolicy;
9use crate::secure_channel::{Identity, Peer};
10use crate::ua::{DataValue, StatusCode, Variant, VariantType};
11use std::{
12    collections::{BTreeMap, btree_map::Entry},
13    io,
14    marker::PhantomData,
15    net::{SocketAddr, TcpListener},
16    num::NonZeroU16,
17    sync::{Arc, RwLock},
18};
19
20/// Failure to configure, run or update an embedded server.
21#[derive(Debug, thiserror::Error)]
22pub enum ServerError {
23    /// Invalid namespace URI or variable name.
24    #[error("invalid namespace URI or variable name")]
25    InvalidName,
26    /// Endpoint or credentials failed local validation.
27    #[error("{0}")]
28    Configuration(&'static str),
29    /// A variable already uses this browse name and NodeId.
30    #[error("variable already exists")]
31    DuplicateVariable,
32    /// OPC UA value or credential validation failed.
33    #[error("{0}")]
34    Protocol(StatusCode),
35    /// Listening socket or connection worker failed.
36    #[error(transparent)]
37    Io(#[from] io::Error),
38}
39
40/// Host-provisioned server identity, single client pin and explicit bind address.
41/// Secrets are borrowed during configuration and excluded from Debug output.
42pub struct SecureServerConfig<'a> {
43    /// One concrete listening IP and port. Its IP must match the server certificate SAN.
44    pub bind: std::net::SocketAddr,
45    /// Application URI from the server certificate.
46    pub application_uri: &'a str,
47    /// Public DER certificate for this server.
48    pub certificate_der: &'a [u8],
49    /// Matching unencrypted private key, encoded as DER.
50    pub private_key_der: &'a [u8],
51    /// Application URI from the provisioned client certificate.
52    pub trusted_client_uri: &'a str,
53    /// Exact DER leaf certificate of the one permitted application.
54    pub trusted_client_certificate_der: &'a [u8],
55}
56
57const UA_NAMESPACE: &str = "http://opcfoundation.org/UA/";
58const LOCAL_URI: &str = "urn:opcua-kit:server";
59const NONE: &str = "http://opcfoundation.org/UA/SecurityPolicy#None";
60const TRANSPORT: &str = "http://opcfoundation.org/UA-Profile/Transport/uatcp-uasc-uabinary";
61
62struct Credentials {
63    policy: SecurityPolicy,
64    server: Identity,
65    client: Peer,
66    client_uri: String,
67}
68
69type Sample = Arc<RwLock<DataValue>>;
70
71struct Host {
72    started: crate::ua::DateTime,
73    namespace: String,
74    application_uri: String,
75    bind: SocketAddr,
76    credentials: Option<Credentials>,
77    variables: RwLock<BTreeMap<String, (u32, Sample)>>,
78}
79
80/// A host-owned address space with one application namespace.
81pub struct Server(Arc<Host>);
82
83/// A blocking server event loop that can run on a host worker thread.
84pub struct ServerRunner(Arc<Host>);
85
86impl ServerRunner {
87    /// Bind the selected endpoint and serve until the callback returns true.
88    /// All active connections close before this method returns.
89    pub fn run_until(self, shutdown: impl FnMut() -> bool) -> Result<(), ServerError> {
90        let socket = TcpListener::bind(self.0.bind)?;
91        transport::run(socket, self.0, shutdown)?;
92        Ok(())
93    }
94}
95
96/// Host-side handle to one scalar. Its Rust type fixes the OPC UA value type.
97pub struct Variable<T> {
98    sample: Sample,
99    marker: PhantomData<fn(T)>,
100}
101
102impl<T: Into<Variant> + VariantType> Variable<T> {
103    /// Update the value and its source timestamp atomically.
104    pub fn set(&self, value: T) -> Result<(), ServerError> {
105        let sample = scalar(value)?;
106        *self.sample.write().unwrap_or_else(|e| e.into_inner()) = sample;
107        Ok(())
108    }
109}
110
111fn scalar<T: Into<Variant> + VariantType>(value: T) -> Result<DataValue, ServerError> {
112    let value = value.into();
113    if value.scalar_type_id() != Some(T::variant_type_id())
114        || matches!(value, Variant::ExtensionObject(_))
115    {
116        return Err(ServerError::Protocol(StatusCode::BadTypeMismatch));
117    }
118    let limits = crate::ua::ContextOwned::default();
119    if crate::ua::BinaryEncodable::encoded_len(&value, &limits.context())
120        .map_err(ServerError::Protocol)?
121        > transport::MESSAGE_LIMIT - 128
122    {
123        return Err(ServerError::Protocol(StatusCode::BadEncodingLimitsExceeded));
124    }
125    Ok(DataValue::new_now(value))
126}
127
128impl Server {
129    /// Configure anonymous connections on the IPv4 loopback interface.
130    pub fn loopback(
131        port: NonZeroU16,
132        namespace_uri: &str,
133    ) -> Result<(Self, ServerRunner), ServerError> {
134        Self::build(
135            ([127, 0, 0, 1], port.get()).into(),
136            LOCAL_URI,
137            namespace_uri,
138            None,
139        )
140    }
141
142    /// Configure a Basic256Sha256 SignAndEncrypt endpoint for one pinned reader.
143    pub fn secure(
144        config: SecureServerConfig<'_>,
145        namespace_uri: &str,
146    ) -> Result<(Self, ServerRunner), ServerError> {
147        Self::secure_with_policy(config, namespace_uri, SecurityPolicy::Basic256Sha256)
148    }
149
150    /// Configure one SignAndEncrypt policy for the pinned client and server identities.
151    pub fn secure_with_policy(
152        config: SecureServerConfig<'_>,
153        namespace_uri: &str,
154        policy: SecurityPolicy,
155    ) -> Result<(Self, ServerRunner), ServerError> {
156        if !is_unicast(config.bind.ip()) || config.bind.port() == 0 {
157            return Err(ServerError::Configuration(
158                "expected a concrete unicast bind IP and nonzero port",
159            ));
160        }
161        for der in [
162            config.certificate_der,
163            config.private_key_der,
164            config.trusted_client_certificate_der,
165        ] {
166            if !(1..=65535).contains(&der.len()) {
167                return Err(ServerError::Configuration(
168                    "credential length must be 1 to 65535 bytes",
169                ));
170            }
171        }
172        crate::certificate::application_certificate(
173            config.certificate_der,
174            config.application_uri,
175            Some(&config.bind.ip().to_string()),
176            true,
177        )
178        .map_err(ServerError::Configuration)?;
179        crate::certificate::application_certificate(
180            config.trusted_client_certificate_der,
181            config.trusted_client_uri,
182            None,
183            true,
184        )
185        .map_err(ServerError::Configuration)?;
186        let credentials = Credentials {
187            policy,
188            server: Identity::new(config.certificate_der, config.private_key_der)
189                .map_err(ServerError::Protocol)?,
190            client: Peer::new(config.trusted_client_certificate_der)
191                .map_err(ServerError::Protocol)?,
192            client_uri: config.trusted_client_uri.into(),
193        };
194        Self::build(
195            config.bind,
196            config.application_uri,
197            namespace_uri,
198            Some(credentials),
199        )
200    }
201
202    fn build(
203        bind: SocketAddr,
204        uri: &str,
205        namespace: &str,
206        credentials: Option<Credentials>,
207    ) -> Result<(Self, ServerRunner), ServerError> {
208        if !valid_name(namespace) || namespace == UA_NAMESPACE || namespace == uri {
209            return Err(ServerError::InvalidName);
210        }
211        let host = Arc::new(Host {
212            started: crate::ua::DateTime::now(),
213            bind,
214            application_uri: uri.into(),
215            namespace: namespace.into(),
216            credentials,
217            variables: RwLock::default(),
218        });
219        Ok((Self(host.clone()), ServerRunner(host)))
220    }
221
222    /// Add a typed, read-only scalar under Objects. Its browse name and string
223    /// NodeId both equal `name`. A duplicate leaves the existing value intact.
224    pub fn add_variable<T: Into<Variant> + VariantType>(
225        &self,
226        name: &str,
227        initial: T,
228    ) -> Result<Variable<T>, ServerError> {
229        if !valid_name(name) {
230            return Err(ServerError::InvalidName);
231        }
232        let mut variables = self.0.variables.write().unwrap_or_else(|e| e.into_inner());
233        let Entry::Vacant(entry) = variables.entry(name.to_owned()) else {
234            return Err(ServerError::DuplicateVariable);
235        };
236        let sample = Arc::new(RwLock::new(scalar(initial)?));
237        entry.insert((T::variant_type_id() as u32, sample.clone()));
238        Ok(Variable {
239            sample,
240            marker: PhantomData,
241        })
242    }
243}
244
245fn is_unicast(ip: std::net::IpAddr) -> bool {
246    match ip {
247        std::net::IpAddr::V4(ip) => {
248            !ip.is_unspecified() && !ip.is_multicast() && !ip.is_broadcast()
249        }
250        std::net::IpAddr::V6(ip) => {
251            !ip.is_unspecified() && !ip.is_multicast() && ip.to_ipv4_mapped().is_none()
252        }
253    }
254}
255
256fn valid_name(name: &str) -> bool {
257    !name.trim().is_empty() && name.len() <= 4096 && !name.chars().any(char::is_control)
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    #[test]
265    fn rejects_unspecified_multicast_broadcast_and_mapped_bind_addresses() {
266        for text in [
267            "0.0.0.0",
268            "::",
269            "224.0.0.1",
270            "ff02::1",
271            "255.255.255.255",
272            "::ffff:0.0.0.0",
273        ] {
274            assert!(!is_unicast(text.parse().unwrap()), "{text}");
275        }
276        assert!(is_unicast("127.0.0.1".parse().unwrap()));
277        assert!(is_unicast("::1".parse().unwrap()));
278    }
279
280    #[test]
281    fn invalid_and_duplicate_names_cannot_replace_application_variables() {
282        let port = NonZeroU16::new(4840).unwrap();
283        for namespace in ["", "x\0y", "http://opcfoundation.org/UA/"] {
284            assert!(matches!(
285                Server::loopback(port, namespace),
286                Err(ServerError::InvalidName)
287            ));
288        }
289        let (host, _runner) = Server::loopback(port, "urn:line").unwrap();
290        assert!(matches!(
291            host.add_variable("bad\nname", false),
292            Err(ServerError::InvalidName)
293        ));
294        let counter = host.add_variable("Counter", 10_u64).unwrap();
295        assert!(host.add_variable("Counter", true).is_err());
296        counter.set(20).unwrap();
297    }
298}