use std::collections::VecDeque;
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::{Duration, Instant as StdInstant};
mod control;
mod files;
mod log;
mod rcb;
mod sg;
pub use control::{CONTROL_ATTRIBUTES, Control};
pub use files::FileEntry;
pub use log::{Lcb, LogEntry, LogPage};
pub use rcb::{Rcb, RcbSettings};
pub use sg::Sgcb;
pub use crate::proto::mms::control::{AddCause, Check, CommandTermination, ControlModel, LastApplError, Origin, OriginCategory};
pub use crate::proto::mms::report::{AssemblerStats, OptFlds, ReasonCode, Report, ReportAssembler, ReportEntry, TrgOps};
pub use crate::proto::mms::typespec::{Component, TypeSpec};
use crate::common::{Error, Fc, Instant, Limits, ObjectReference, Result};
use crate::proto::data::{DataView, Typed, Value};
use crate::proto::mms::association::{Association, AssociationConfig, AssociationEvent, CloseReason, PORT};
use crate::proto::mms::control::ControlRequest;
use crate::proto::mms::{
AccessResult, AlternateAccess, ConfirmedRequest, ConfirmedResponse, Mms, ObjectName, ObjectScope, ServiceError, Unconfirmed, VariableAccess,
VariableSpecification, delete_scope, object_class,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Backoff {
pub first: Duration,
pub max: Duration,
pub factor: u32,
pub attempts: usize,
}
impl Default for Backoff {
fn default() -> Backoff {
Backoff { first: Duration::from_millis(500), max: Duration::from_secs(30), factor: 2, attempts: 0 }
}
}
impl Backoff {
#[must_use]
pub const fn bounded(mut self, attempts: usize) -> Backoff {
self.attempts = attempts;
self
}
pub fn delay(&self, n: u32) -> Duration {
let scale = u64::from(self.factor.max(1)).checked_pow(n).unwrap_or(u64::MAX);
Duration::from_nanos(u64::try_from(self.first.as_nanos()).unwrap_or(u64::MAX).saturating_mul(scale)).min(self.max)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ServerStatus {
pub logical: i64,
pub physical: i64,
}
impl ServerStatus {
pub const fn is_healthy(self) -> bool {
self.logical == crate::proto::mms::vmd_logical::STATE_CHANGES_ALLOWED && self.physical == crate::proto::mms::vmd_physical::OPERATIONAL
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Identity {
pub vendor: String,
pub model: String,
pub revision: String,
}
#[derive(Clone, Debug, PartialEq)]
pub enum Unsolicited {
Report(Box<Report>),
CommandTermination(Box<CommandTermination>),
Other {
name: String,
values: Vec<Value>,
raw: Vec<u8>,
},
}
impl Unsolicited {
pub fn from_pdu(pdu: &[u8], limits: &Limits) -> Option<Unsolicited> {
let Ok(Mms::Unconfirmed(Unconfirmed::InformationReport { access, results })) = Mms::parse(pdu, limits) else {
return None;
};
let mut values = Vec::with_capacity(results.len());
let mut complete = true;
for r in &results {
match r {
AccessResult::Success(t) => match DataView::from_tlv(*t).ok().and_then(|d| d.to_owned(limits).ok()) {
Some(v) => values.push(v),
None => complete = false,
},
AccessResult::Failure(_) => complete = false,
}
}
if !complete {
let name = match &access {
VariableAccess::VariableListName(n) => object_name(n),
VariableAccess::ListOfVariable(names) => names.iter().map(specification_name).collect::<Vec<_>>().join(", "),
};
return Some(Unsolicited::Other { name, values: Vec::new(), raw: pdu.to_vec() });
}
Some(match &access {
VariableAccess::VariableListName(name) => {
let name = object_name(name);
match Report::from_values(&values) {
Ok(r) => Unsolicited::Report(Box::new(r)),
Err(_) => Unsolicited::Other { name, values, raw: pdu.to_vec() },
}
}
VariableAccess::ListOfVariable(names) => match termination(names, &values) {
Some(t) => Unsolicited::CommandTermination(Box::new(t)),
None => Unsolicited::Other { name: names.iter().map(specification_name).collect::<Vec<_>>().join(", "), values, raw: pdu.to_vec() },
},
})
}
pub fn report(&self) -> Option<&Report> {
match self {
Unsolicited::Report(r) => Some(r),
_ => None,
}
}
pub fn termination(&self) -> Option<&CommandTermination> {
match self {
Unsolicited::CommandTermination(t) => Some(t),
_ => None,
}
}
}
#[derive(Clone, Debug)]
pub struct ClientConfig {
pub association: AssociationConfig,
pub connect_timeout: Duration,
}
impl Default for ClientConfig {
fn default() -> ClientConfig {
ClientConfig { association: AssociationConfig::default(), connect_timeout: Duration::from_secs(10) }
}
}
#[cfg(feature = "scl")]
impl ClientConfig {
pub fn from_scl(scl: &crate::scl::Scl<'_>, ied: &str, access_point: Option<&str>) -> Result<(ClientConfig, Option<String>)> {
let model = scl.model(Some(ied))?;
let address = model.osi_address(access_point).ok_or(Error::NotFound("ConnectedAP address for this IED"))?;
let cfg = ClientConfig {
association: AssociationConfig { remote: crate::proto::mms::association::Selectors::from_address(address), ..AssociationConfig::default() },
..ClientConfig::default()
};
Ok((cfg, address.ip.clone()))
}
}
#[derive(Debug)]
pub struct Client<S = TcpStream> {
stream: Option<S>,
set_read_timeout: fn(&mut S, Duration) -> std::io::Result<()>,
assoc: Association,
limits: Limits,
unsolicited: VecDeque<Unsolicited>,
assembler: ReportAssembler,
ctl_num: u8,
epoch: StdInstant,
rx: Vec<u8>,
request_timeout: Duration,
origin: Option<(String, ClientConfig)>,
pub(crate) serving: Option<files::Serving>,
pub(crate) progress: Option<StdInstant>,
}
impl Client {
pub fn connect(addr: &str) -> Result<Client> {
Client::connect_with(addr, &ClientConfig::default())
}
pub fn connect_with(addr: &str, cfg: &ClientConfig) -> Result<Client> {
let with_port = with_default_port(addr);
let target =
with_port.to_socket_addrs().map_err(|e| Error::Io(format!("{addr}: {e}")))?.next().ok_or_else(|| Error::Io(format!("{addr}: no address")))?;
let stream = TcpStream::connect_timeout(&target, cfg.connect_timeout).map_err(|e| Error::Io(format!("{addr}: {e}")))?;
let mut c = Self::from_stream(stream, cfg)?;
c.origin = Some((String::from(addr), cfg.clone()));
Ok(c)
}
pub fn connect_retrying(addr: &str, cfg: &ClientConfig, backoff: &Backoff) -> Result<Client> {
let mut n = 0u32;
loop {
match Client::connect_with(addr, cfg) {
Ok(c) => return Ok(c),
Err(e) => {
if backoff.attempts != 0 && usize::try_from(n).unwrap_or(usize::MAX).saturating_add(1) >= backoff.attempts {
return Err(e);
}
std::thread::sleep(backoff.delay(n));
n = n.saturating_add(1);
}
}
}
}
pub fn reconnect(&mut self, backoff: &Backoff) -> Result<()> {
let (addr, cfg) = self.origin.clone().ok_or(Error::InvalidValue("this client was built from a socket, so it has nowhere to reconnect to"))?;
*self = Self::connect_retrying(&addr, &cfg, backoff)?;
Ok(())
}
pub fn from_stream(stream: TcpStream, cfg: &ClientConfig) -> Result<Client> {
stream.set_nodelay(true).map_err(|e| Error::Io(e.to_string()))?;
Self::with_transport(stream, cfg, |tcp, timeout| tcp.set_read_timeout(Some(timeout)))
}
#[cfg(feature = "scl")]
pub fn connect_scl(scl: &crate::scl::Scl<'_>, ied: &str, access_point: Option<&str>, host: Option<&str>) -> Result<Client> {
let (cfg, ip) = ClientConfig::from_scl(scl, ied, access_point)?;
let host = match (host, ip.as_deref()) {
(Some(h), _) => String::from(h),
(None, Some(ip)) => String::from(ip),
(None, None) => return Err(Error::NotFound("the SCL file gives this access point no IP address")),
};
Client::connect_with(&host, &cfg)
}
}
impl<S: Read + Write> Client<S> {
pub fn with_transport(stream: S, cfg: &ClientConfig, set_read_timeout: fn(&mut S, Duration) -> std::io::Result<()>) -> Result<Self> {
let limits = cfg.association.limits;
let mut c = Client {
stream: Some(stream),
set_read_timeout,
assoc: Association::client(cfg.association.clone()),
limits,
unsolicited: VecDeque::new(),
assembler: ReportAssembler::new(8),
ctl_num: 0,
epoch: StdInstant::now(),
rx: alloc_buffer(),
request_timeout: request_timeout(&cfg.association),
origin: None,
serving: None,
progress: None,
};
let now = c.now();
c.assoc.start(now)?;
c.flush()?;
c.pump_while(|a| !a.is_established(), Duration::from_millis(cfg.association.connect_timeout_ms))?;
Ok(c)
}
pub fn is_alive(&mut self) -> bool {
self.assoc.is_established() && self.status(false).is_ok()
}
pub fn read_control_model(&mut self, reference: &str) -> Result<ControlModel> {
let parsed = ObjectReference::parse(reference)?;
let (domain, item) = parsed.to_mms_under(Fc::CF);
let full = format!("{domain}/{item}$ctlModel");
let v = self.read(&full, Fc::CF)?;
let code = v.as_i64().or_else(|| v.as_u64().and_then(|u| i64::try_from(u).ok())).ok_or(Error::InvalidValue("ctlModel is not an integer"))?;
ControlModel::from_code(code).ok_or(Error::InvalidValue("ctlModel is outside the enumeration"))
}
pub fn negotiated(&self) -> Option<crate::proto::mms::association::Negotiated> {
self.assoc.negotiated()
}
pub fn stats(&self) -> crate::proto::mms::association::AssociationStats {
self.assoc.stats()
}
pub fn identify(&mut self) -> Result<Identity> {
let pdu = self.call(&ConfirmedRequest::Identify)?;
match Mms::parse(&pdu, &self.limits)? {
Mms::ConfirmedResponse { service: ConfirmedResponse::Identify { vendor, model, revision }, .. } => {
Ok(Identity { vendor: String::from(vendor), model: String::from(model), revision: String::from(revision) })
}
_ => Err(Error::InvalidValue("not an Identify response")),
}
}
pub fn status(&mut self, extended_derivation: bool) -> Result<ServerStatus> {
let pdu = self.call(&ConfirmedRequest::Status { extended_derivation })?;
match Mms::parse(&pdu, &self.limits)? {
Mms::ConfirmedResponse { service: ConfirmedResponse::Status { logical, physical, .. }, .. } => Ok(ServerStatus { logical, physical }),
_ => Err(Error::InvalidValue("not a Status response")),
}
}
pub fn capabilities(&mut self) -> Result<Vec<String>> {
let mut out: Vec<String> = Vec::new();
loop {
let after = out.last().cloned();
let pdu = self.call(&ConfirmedRequest::GetCapabilityList { continue_after: after.as_deref() })?;
let (page, more) = match Mms::parse(&pdu, &self.limits)? {
Mms::ConfirmedResponse { service: ConfirmedResponse::GetCapabilityList { capabilities, more_follows }, .. } => {
(capabilities.iter().map(|c| String::from(*c)).collect::<Vec<_>>(), more_follows)
}
_ => return Err(Error::InvalidValue("not a GetCapabilityList response")),
};
let empty = page.is_empty();
out.extend(page);
if !more || empty {
return Ok(out);
}
if out.len() > self.limits.max_dataset_members {
return Err(Error::LimitExceeded { limit: "max_dataset_members", value: out.len() });
}
}
}
pub fn server_directory(&mut self) -> Result<Vec<String>> {
self.name_list(object_class::DOMAIN, ObjectScope::VmdSpecific)
}
pub fn logical_device_directory(&mut self, ld: &str) -> Result<Vec<String>> {
self.name_list(object_class::NAMED_VARIABLE, ObjectScope::DomainSpecific(ld))
}
pub fn data_set_directory(&mut self, ld: &str) -> Result<Vec<String>> {
self.name_list(object_class::NAMED_VARIABLE_LIST, ObjectScope::DomainSpecific(ld))
}
pub fn log_directory(&mut self, ld: &str) -> Result<Vec<String>> {
self.name_list(object_class::JOURNAL, ObjectScope::DomainSpecific(ld))
}
pub fn data_set_members(&mut self, ld: &str, name: &str) -> Result<Vec<String>> {
let pdu = self.call(&ConfirmedRequest::GetNamedVariableListAttributes(ObjectName::DomainSpecific { domain: ld, item: name }))?;
match Mms::parse(&pdu, &self.limits)? {
Mms::ConfirmedResponse { service: ConfirmedResponse::GetNamedVariableListAttributes { variables, .. }, .. } => Ok(variables
.iter()
.filter_map(|v| {
let selected = v.access().map(ToString::to_string).unwrap_or_default();
match v.name()? {
ObjectName::DomainSpecific { domain, item } => Some(format!("{domain}/{item}{selected}")),
ObjectName::VmdSpecific(n) | ObjectName::AaSpecific(n) => Some(format!("{n}{selected}")),
}
})
.collect()),
_ => Err(Error::InvalidValue("not a GetNamedVariableListAttributes response")),
}
}
pub fn read(&mut self, reference: &str, fc: Fc) -> Result<Value> {
let addressed = Addressed::of(reference, fc)?;
let access = VariableAccess::ListOfVariable(vec![addressed.spec()]);
let mut values = self.read_access(&access)?;
if values.len() == 1 { Ok(values.remove(0)) } else { Err(Error::InvalidValue("server returned the wrong number of values")) }
}
pub fn read_many(&mut self, references: &[(&str, Fc)]) -> Result<Vec<Value>> {
let items = Addressed::all(references)?;
let access = VariableAccess::ListOfVariable(items.iter().map(Addressed::spec).collect());
self.read_access(&access)
}
pub fn read_many_results(&mut self, references: &[(&str, Fc)]) -> Result<Vec<Result<Value>>> {
let items = Addressed::all(references)?;
let access = VariableAccess::ListOfVariable(items.iter().map(Addressed::spec).collect());
self.read_access_results(&access)
}
pub fn read_data_set(&mut self, ld: &str, name: &str) -> Result<Vec<Value>> {
self.read_access(&VariableAccess::VariableListName(ObjectName::DomainSpecific { domain: ld, item: name }))
}
pub fn write(&mut self, reference: &str, fc: Fc, value: &Value) -> Result<()> {
let addressed = Addressed::of(reference, fc)?;
let encoded = Value::encode_all(std::slice::from_ref(value))?;
let element = crate::ber::Cursor::new(&encoded).next_required()?;
let access = VariableAccess::ListOfVariable(vec![addressed.spec()]);
let pdu = self.call(&ConfirmedRequest::Write { access, values: vec![element] })?;
match Mms::parse(&pdu, &self.limits)? {
Mms::ConfirmedResponse { service: ConfirmedResponse::Write(results), .. } => match results.first() {
Some(crate::proto::mms::WriteResult::Success) => Ok(()),
Some(crate::proto::mms::WriteResult::Failure(code)) => Err(Error::DataAccess(*code)),
None => Err(Error::InvalidValue("empty Write response")),
},
_ => Err(Error::InvalidValue("not a Write response")),
}
}
pub fn variable_type(&mut self, reference: &str, fc: Fc) -> Result<TypeSpec> {
let parsed = ObjectReference::parse(reference)?;
let (domain, item) = parsed.to_mms(fc);
let pdu = self.call(&ConfirmedRequest::GetVariableAccessAttributes(ObjectName::DomainSpecific { domain, item: &item }))?;
match Mms::parse(&pdu, &self.limits)? {
Mms::ConfirmedResponse { service: ConfirmedResponse::GetVariableAccessAttributes { type_spec, .. }, .. } => Ok(type_spec),
_ => Err(Error::InvalidValue("not a GetVariableAccessAttributes response")),
}
}
pub fn create_data_set(&mut self, name: &str, members: &[(&str, Fc)]) -> Result<()> {
let (ld, item) = split_data_set(name)?;
let mut items = Vec::with_capacity(members.len());
for (reference, fc) in members {
let parsed = ObjectReference::parse(reference)?;
let (domain, member) = parsed.to_mms(*fc);
items.push((String::from(domain), member));
}
let variables = items.iter().map(|(d, i)| VariableSpecification::Name(ObjectName::DomainSpecific { domain: d, item: i })).collect::<Vec<_>>();
let pdu = self.call(&ConfirmedRequest::DefineNamedVariableList { name: ObjectName::DomainSpecific { domain: &ld, item: &item }, variables })?;
match Mms::parse(&pdu, &self.limits)? {
Mms::ConfirmedResponse { service: ConfirmedResponse::DefineNamedVariableList, .. } => Ok(()),
_ => Err(Error::InvalidValue("not a DefineNamedVariableList response")),
}
}
pub fn delete_data_set(&mut self, name: &str) -> Result<()> {
let (ld, item) = split_data_set(name)?;
let pdu = self.call(&ConfirmedRequest::DeleteNamedVariableList {
scope: delete_scope::SPECIFIC,
names: vec![ObjectName::DomainSpecific { domain: &ld, item: &item }],
domain: None,
})?;
match Mms::parse(&pdu, &self.limits)? {
Mms::ConfirmedResponse { service: ConfirmedResponse::DeleteNamedVariableList { deleted: 1, .. }, .. } => Ok(()),
Mms::ConfirmedResponse { service: ConfirmedResponse::DeleteNamedVariableList { matched: 0, .. }, .. } => Err(Error::NotFound("data set")),
Mms::ConfirmedResponse { service: ConfirmedResponse::DeleteNamedVariableList { .. }, .. } => {
Err(Error::DataAccess(3))
}
_ => Err(Error::InvalidValue("not a DeleteNamedVariableList response")),
}
}
pub fn next_unsolicited(&mut self, timeout: Duration) -> Result<Option<Unsolicited>> {
self.take_unsolicited(timeout, |_| true)
}
pub fn next_report(&mut self, timeout: Duration) -> Result<Option<Report>> {
Ok(self.take_unsolicited(timeout, |u| matches!(u, Unsolicited::Report(_)))?.and_then(|u| match u {
Unsolicited::Report(r) => Some(*r),
_ => None,
}))
}
pub fn next_termination(&mut self, timeout: Duration) -> Result<Option<CommandTermination>> {
self.take_termination(timeout, None)
}
pub fn next_termination_for(&mut self, ctl_num: u8, timeout: Duration) -> Result<Option<CommandTermination>> {
self.take_termination(timeout, Some(ctl_num))
}
fn take_termination(&mut self, timeout: Duration, ctl_num: Option<u8>) -> Result<Option<CommandTermination>> {
let wanted = move |u: &Unsolicited| match u {
Unsolicited::CommandTermination(t) => ctl_num.is_none_or(|n| t.ctl_num() == n),
_ => false,
};
Ok(self.take_unsolicited(timeout, wanted)?.and_then(|u| match u {
Unsolicited::CommandTermination(t) => Some(*t),
_ => None,
}))
}
pub fn buffered_unsolicited(&self) -> usize {
self.unsolicited.len()
}
fn take_unsolicited(&mut self, timeout: Duration, wanted: impl Fn(&Unsolicited) -> bool) -> Result<Option<Unsolicited>> {
let deadline = StdInstant::now() + timeout;
loop {
if let Some(i) = self.unsolicited.iter().position(&wanted) {
return Ok(self.unsolicited.remove(i));
}
if StdInstant::now() >= deadline || !self.assoc.is_established() {
return Ok(None);
}
self.read_once(deadline.saturating_duration_since(StdInstant::now()))?;
self.drain_events()?;
}
}
pub fn release(&mut self) -> Result<()> {
let result = self.release_association();
self.stream.take();
result
}
fn release_association(&mut self) -> Result<()> {
if self.assoc.is_established() {
let now = self.now();
self.assoc.release(now)?;
self.flush()?;
let _ = self.pump_while(|a| !matches!(a.state(), crate::proto::mms::association::State::Closed), Duration::from_secs(2));
}
Ok(())
}
fn name_list(&mut self, class: i64, scope: ObjectScope<'_>) -> Result<Vec<String>> {
let mut out: Vec<String> = Vec::new();
loop {
let after = out.last().cloned();
let pdu = self.call(&ConfirmedRequest::GetNameList { object_class: class, scope, continue_after: after.as_deref() })?;
let Mms::ConfirmedResponse { service: ConfirmedResponse::GetNameList { identifiers, more_follows }, .. } = Mms::parse(&pdu, &self.limits)? else {
return Err(Error::InvalidValue("not a GetNameList response"));
};
let empty = identifiers.is_empty();
out.extend(identifiers.iter().map(|s| String::from(*s)));
if !more_follows || empty {
return Ok(out);
}
if out.len() > self.limits.max_dataset_members * 64 {
return Err(Error::LimitExceeded { limit: "GetNameList continuations", value: out.len() });
}
}
}
fn read_access(&mut self, access: &VariableAccess<'_>) -> Result<Vec<Value>> {
self.read_access_results(access)?.into_iter().collect()
}
fn read_access_results(&mut self, access: &VariableAccess<'_>) -> Result<Vec<Result<Value>>> {
let pdu = self.call(&ConfirmedRequest::Read { specification_with_result: false, access: access.clone() })?;
let Mms::ConfirmedResponse { service: ConfirmedResponse::Read { results, .. }, .. } = Mms::parse(&pdu, &self.limits)? else {
return Err(Error::InvalidValue("not a Read response"));
};
Ok(results
.iter()
.map(|r| match r {
AccessResult::Failure(code) => Err(Error::DataAccess(*code)),
AccessResult::Success(t) => DataView::from_tlv(*t)?.to_owned(&self.limits),
})
.collect())
}
pub(crate) fn write_many(&mut self, writes: &[(String, Value)]) -> Result<Vec<Result<()>>> {
let mut encoded = Vec::with_capacity(writes.len());
let mut items = Vec::with_capacity(writes.len());
for (reference, value) in writes {
let fc = ObjectReference::parse(reference)?.fc.ok_or(Error::InvalidReference("a write needs a functional constraint"))?;
items.push(Addressed::of(reference, fc)?);
encoded.push(Value::encode_all(core::slice::from_ref(value))?);
}
let access = VariableAccess::ListOfVariable(items.iter().map(Addressed::spec).collect());
let mut elements = Vec::with_capacity(encoded.len());
for bytes in &encoded {
elements.push(crate::ber::Cursor::new(bytes).next_required()?);
}
let pdu = self.call(&ConfirmedRequest::Write { access, values: elements })?;
let Mms::ConfirmedResponse { service: ConfirmedResponse::Write(results), .. } = Mms::parse(&pdu, &self.limits)? else {
return Err(Error::InvalidValue("not a Write response"));
};
Ok(results
.iter()
.map(|r| match r {
crate::proto::mms::WriteResult::Success => Ok(()),
crate::proto::mms::WriteResult::Failure(code) => Err(Error::DataAccess(*code)),
})
.collect())
}
pub(crate) fn next_ctl_num(&mut self) -> u8 {
self.ctl_num = self.ctl_num.wrapping_add(1);
self.ctl_num
}
pub(crate) const fn timeout(&self) -> Duration {
self.request_timeout
}
fn call(&mut self, service: &ConfirmedRequest<'_>) -> Result<Vec<u8>> {
if !self.assoc.is_established() {
return Err(Error::Io(String::from("association is not established")));
}
let now = self.now();
let invoke_id = self.assoc.call(now, service)?;
self.flush()?;
let mut deadline = StdInstant::now() + self.request_timeout;
loop {
if let Some(pdu) = self.take_answer(invoke_id)? {
return Ok(pdu);
}
if let Some(at) = self.progress.take() {
deadline = at + self.request_timeout;
}
if StdInstant::now() >= deadline {
return Err(Error::Io(String::from("request timed out")));
}
self.read_once(deadline.saturating_duration_since(StdInstant::now()))?;
}
}
fn take_answer(&mut self, invoke_id: i64) -> Result<Option<Vec<u8>>> {
let mut answer = None;
while let Some(event) = self.assoc.poll_event() {
match event {
AssociationEvent::Response { invoke_id: id, pdu } if id == invoke_id => {
if let Mms::ConfirmedError { error, .. } = Mms::parse(&pdu, &self.limits)? {
let e = ServiceError::parse(&error)?;
return Err(Error::Service { class: e.class, code: e.code });
}
answer = Some(pdu);
}
AssociationEvent::Timeout { invoke_id: id } if id == invoke_id => {
return Err(Error::Io(String::from("request timed out")));
}
AssociationEvent::Rejected { invoke_id: Some(id), reject } if id == invoke_id => return Err(rejected(&reject)),
AssociationEvent::Rejected { invoke_id: None, reject } => return Err(rejected(&reject)),
AssociationEvent::Cancelled { invoke_id: id } if id == invoke_id => {
return Err(Error::Io(String::from("the peer cancelled the request")));
}
AssociationEvent::Unconfirmed { pdu } => self.keep_unsolicited(&pdu),
AssociationEvent::Request { invoke_id: id, pdu } => {
self.answer_peer_request(id, &pdu)?;
if self.serving.is_some() {
let now = self.now();
self.assoc.extend_deadline(invoke_id, now);
}
}
AssociationEvent::Malformed { invoke_id: Some(id), error } if id == invoke_id => return Err(error),
AssociationEvent::Refused { layer, code } => {
return Err(Error::Io(format!("association refused at {layer}: {code:?}")));
}
AssociationEvent::Closed(reason) => return Err(closed(reason)),
AssociationEvent::Response { .. }
| AssociationEvent::Timeout { .. }
| AssociationEvent::Rejected { .. }
| AssociationEvent::Malformed { .. }
| AssociationEvent::Cancelled { .. }
| AssociationEvent::CancelRefused { .. }
| AssociationEvent::Established(_) => {}
}
}
self.flush()?;
Ok(answer)
}
pub const fn report_assembler_stats(&self) -> AssemblerStats {
self.assembler.stats()
}
fn keep_unsolicited(&mut self, pdu: &[u8]) {
let Some(item) = Unsolicited::from_pdu(pdu, &self.limits) else { return };
let item = match item {
Unsolicited::Report(r) => match self.assembler.push(*r) {
Some(whole) => Unsolicited::Report(Box::new(whole)),
None => return,
},
other => other,
};
if self.unsolicited.len() >= 256 {
self.unsolicited.pop_front();
}
self.unsolicited.push_back(item);
}
fn drain_events(&mut self) -> Result<()> {
while let Some(event) = self.assoc.poll_event() {
match event {
AssociationEvent::Unconfirmed { pdu } => self.keep_unsolicited(&pdu),
AssociationEvent::Request { invoke_id, pdu } => self.answer_peer_request(invoke_id, &pdu)?,
AssociationEvent::Closed(reason) => return Err(closed(reason)),
AssociationEvent::Refused { layer, code } => return Err(Error::Io(format!("association refused at {layer}: {code:?}"))),
AssociationEvent::Rejected { .. }
| AssociationEvent::Response { .. }
| AssociationEvent::Timeout { .. }
| AssociationEvent::Malformed { .. }
| AssociationEvent::Cancelled { .. }
| AssociationEvent::CancelRefused { .. }
| AssociationEvent::Established(_) => {}
}
}
self.flush()
}
fn read_once(&mut self, timeout: Duration) -> Result<()> {
let timeout = timeout.max(Duration::from_millis(1));
let stream = self.stream.as_mut().ok_or(Error::InvalidValue("association released"))?;
(self.set_read_timeout)(stream, timeout).map_err(|e| Error::Io(e.to_string()))?;
match stream.read(&mut self.rx) {
Ok(0) => {
self.assoc.abort();
Err(Error::Io(String::from("the peer closed the connection")))
}
Ok(n) => {
let now = self.now();
let buf = core::mem::take(&mut self.rx);
self.assoc.on_bytes(now, buf.get(..n).unwrap_or(&[]));
self.rx = buf;
Ok(())
}
Err(e) if matches!(e.kind(), std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {
let now = self.now();
self.assoc.on_timeout(now);
Ok(())
}
Err(e) => Err(Error::Io(e.to_string())),
}
}
fn pump_while(&mut self, keep_going: impl Fn(&Association) -> bool, timeout: Duration) -> Result<()> {
let deadline = StdInstant::now() + timeout;
while keep_going(&self.assoc) {
if StdInstant::now() >= deadline {
return Err(Error::Io(String::from("timed out waiting for the peer")));
}
self.read_once(deadline.saturating_duration_since(StdInstant::now()))?;
self.drain_events()?;
}
Ok(())
}
fn flush(&mut self) -> Result<()> {
let stream = self.stream.as_mut().ok_or(Error::InvalidValue("association released"))?;
while let Some(packet) = self.assoc.poll_transmit() {
stream.write_all(packet).map_err(|e| Error::Io(e.to_string()))?;
}
stream.flush().map_err(|e| Error::Io(e.to_string()))
}
fn now(&self) -> Instant {
Instant(self.epoch.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64)
}
}
fn object_name(name: &ObjectName<'_>) -> String {
match name {
ObjectName::DomainSpecific { domain, item } => format!("{domain}/{item}"),
ObjectName::VmdSpecific(n) | ObjectName::AaSpecific(n) => String::from(*n),
}
}
struct Addressed<'r> {
domain: String,
item: String,
access: AlternateAccess<'r>,
}
impl<'r> Addressed<'r> {
fn of(reference: &'r str, fc: Fc) -> Result<Addressed<'r>> {
let parsed = ObjectReference::parse(reference)?;
let (domain, item) = parsed.to_mms(fc);
Ok(Addressed { domain: String::from(domain), item, access: AlternateAccess::new(parsed.selection()) })
}
fn all(references: &[(&'r str, Fc)]) -> Result<Vec<Addressed<'r>>> {
references.iter().map(|(reference, fc)| Addressed::of(reference, *fc)).collect()
}
fn spec(&self) -> VariableSpecification<'_> {
VariableSpecification::of(ObjectName::DomainSpecific { domain: &self.domain, item: &self.item }, self.access.clone())
}
}
fn specification_name(spec: &VariableSpecification<'_>) -> String {
spec.name().map(object_name).unwrap_or_default()
}
fn termination(names: &[VariableSpecification<'_>], values: &[Value]) -> Option<CommandTermination> {
let named: Vec<String> = names.iter().map(specification_name).collect();
let is_oper = |n: &String| n.ends_with("$Oper") || n.ends_with("$SBOw") || n.ends_with("$Cancel");
match (named.as_slice(), values) {
([first], [oper]) if is_oper(first) => {
Some(CommandTermination::Positive { control_object: first.clone(), request: ControlRequest::from_value(oper).ok()? })
}
([first, second], [err, oper]) if first == "LastApplError" && is_oper(second) => {
Some(CommandTermination::Negative { error: LastApplError::from_value(err).ok()?, request: ControlRequest::from_value(oper).ok() })
}
([only], [err]) if only == "LastApplError" => Some(CommandTermination::Negative { error: LastApplError::from_value(err).ok()?, request: None }),
_ => None,
}
}
fn split_data_set(name: &str) -> Result<(String, String)> {
let (ld, rest) = name.split_once('/').ok_or(Error::InvalidReference("a data set is `LD/LN$dsName`"))?;
if ld.is_empty() || rest.is_empty() {
return Err(Error::InvalidReference("a data set is `LD/LN$dsName`"));
}
Ok((String::from(ld), rest.replace('.', "$")))
}
fn alloc_buffer() -> Vec<u8> {
vec![0u8; 8192]
}
fn with_default_port(addr: &str) -> String {
let has_port = match addr.rfind(']') {
Some(bracket) => addr.get(bracket + 1..).is_some_and(|rest| rest.starts_with(':')),
None => addr.matches(':').count() == 1,
};
if has_port {
String::from(addr)
} else if addr.contains(':') && !addr.starts_with('[') {
format!("[{addr}]:{PORT}")
} else {
format!("{addr}:{PORT}")
}
}
fn request_timeout(cfg: &AssociationConfig) -> Duration {
Duration::from_millis(if cfg.request_timeout_ms == 0 { 30_000 } else { cfg.request_timeout_ms })
}
fn rejected(reject: &crate::proto::mms::reject::Reject) -> Error {
let (invoke_id, reason_tag, code) = reject.to_error_parts();
Error::Rejected { invoke_id, reason_tag, code }
}
fn closed(reason: CloseReason) -> Error {
Error::Io(match reason {
CloseReason::Released | CloseReason::PeerReleased => String::from("the association was released"),
CloseReason::Aborted => String::from("the association was aborted"),
CloseReason::ConnectTimeout => String::from("the association handshake timed out"),
CloseReason::Refused => String::from("the peer refused the association"),
CloseReason::ProtocolError => String::from("the peer sent something that is not the protocol"),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_host_without_a_port_gets_102() {
let e = Client::connect("127.0.0.1").unwrap_err();
assert!(matches!(e, Error::Io(_)), "{e:?}");
}
#[test]
fn a_host_without_a_port_gets_one_whatever_family_it_is() {
assert_eq!(with_default_port("10.0.0.5"), "10.0.0.5:102");
assert_eq!(with_default_port("10.0.0.5:3782"), "10.0.0.5:3782");
assert_eq!(with_default_port("ied1.substation.local"), "ied1.substation.local:102");
assert_eq!(with_default_port("::1"), "[::1]:102");
assert_eq!(with_default_port("fe80::1"), "[fe80::1]:102");
assert_eq!(with_default_port("[::1]"), "[::1]:102");
assert_eq!(with_default_port("[::1]:102"), "[::1]:102");
}
#[test]
fn a_data_set_name_splits_into_the_domain_and_the_list() {
assert_eq!(split_data_set("IED1LD0/LLN0$dsTrip").unwrap(), (String::from("IED1LD0"), String::from("LLN0$dsTrip")));
assert_eq!(split_data_set("IED1LD0/LLN0.dsTrip").unwrap(), (String::from("IED1LD0"), String::from("LLN0$dsTrip")));
assert!(split_data_set("dsTrip").is_err());
}
#[test]
fn a_closed_reason_becomes_an_error_a_human_can_read() {
assert_eq!(closed(CloseReason::Refused), Error::Io(String::from("the peer refused the association")));
}
}