iec61850-kit 0.7.0

IEC 61850 in Rust: GOOSE and Sampled Values on capture files and live interfaces, an MMS client and server over the full OSI stack, and SCL loading and editing. Panic-free, sans-IO, no_std-capable.
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
//! `TypeSpecification` — what `GetVariableAccessAttributes` answers with.
//!
//! This is how a client learns the *shape* of a variable before it writes one: that
//! `CSWI1$CO$Pos$Oper` is a structure of seven components whose first is a two-bit bit string
//! and whose fifth is a `utc-time`, or that `MMXU1$MX$TotW$mag$f` is a floating point. One
//! round trip turns "the write was refused with type-inconsistent" into something a tool can
//! explain.
//!
//! ```text
//! TypeSpecification ::= CHOICE {
//!   typeName [0] ObjectName, array [1] { packed, numberOfElements, elementType },
//!   structure [2] { packed, components [1] SEQUENCE OF { componentName [0]?, componentType [1] } },
//!   boolean [3] NULL, bit-string [4] Integer32, integer [5] Unsigned8, unsigned [6] Unsigned8,
//!   octet-string [9] Integer32, visible-string [10] Integer32, generalized-time [11] NULL,
//!   binary-time [12] BOOLEAN, bcd [13] Unsigned8, objId [15] NULL }
//! ```
//!
//! plus `floating-point [7] { format-width [0], exponent-width [1] }`, which ISO 9506-2 has
//! and Wireshark's stripped module drops, and `mMSString [16]` / `utc-time [17]`, which
//! IEC 61850-8-1 adds alongside the `Data` choices of the same numbers 🌐. Everything else is
//! ISO 9506-2 as Wireshark's `asn1/mms/mms.asn` states it ✅. `objId [15]` is not modelled
//! and arrives as [`TypeSpec::Other`]; nothing in IEC 61850 is one.
//!
//! A negative `bit-string`, `octet-string` or `visible-string` length means "at most that
//! many"; the sign is kept rather than normalised, because it is the difference between a
//! fixed-width field and a bounded one.

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;

use crate::ber::{Cursor, Encoder, Tag, Tlv};
use crate::common::{DecodeReason, Error, Limits, Result};
use crate::proto::data::tag;

/// One component of a structure type.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Component {
    /// `componentName`, when the server named it — IEC 61850 servers always do, because the
    /// name is the data attribute (`ctlVal`, `origin`, `ctlNum`, …).
    pub name: Option<String>,
    /// The component's own type.
    pub type_spec: TypeSpec,
}

/// The type of an MMS variable.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum TypeSpec {
    /// `typeName [0]` — a named type defined elsewhere in the VMD.
    Named {
        /// The domain, when the name is domain-specific.
        domain: Option<String>,
        /// The name.
        item: String,
    },
    /// `array [1]`.
    Array {
        /// `packed`.
        packed: bool,
        /// How many elements.
        elements: u32,
        /// What each element is.
        element_type: Box<TypeSpec>,
    },
    /// `structure [2]` — a data object or a functionally-constrained data attribute.
    Structure {
        /// `packed`.
        packed: bool,
        /// The components, in the order the server returns them, which is the order a
        /// `Read` returns their values in.
        components: Vec<Component>,
    },
    /// `boolean [3]`.
    Boolean,
    /// `bit-string [4]`, with its length in bits (negative = "at most").
    BitString(i32),
    /// `integer [5]`, with its width in bits.
    Integer(u8),
    /// `unsigned [6]`, with its width in bits.
    Unsigned(u8),
    /// `floating-point [7]`: total width and exponent width, in bits.
    FloatingPoint {
        /// Total format width in bits (32 or 64).
        format_width: u8,
        /// Exponent width in bits (8 or 11).
        exponent_width: u8,
    },
    /// `octet-string [9]`, with its length (negative = "at most").
    OctetString(i32),
    /// `visible-string [10]`, with its length (negative = "at most").
    VisibleString(i32),
    /// `generalized-time [11]`.
    GeneralizedTime,
    /// `binary-time [12]`: true when the six-octet form with a date.
    BinaryTime(bool),
    /// `bcd [13]`, with its number of digits.
    Bcd(u8),
    /// `mMSString [16]`, with its length (negative = "at most").
    MmsString(i32),
    /// `utc-time [17]` — the IEC 61850 `Timestamp`.
    UtcTime,
    /// A choice this codec does not model, kept as its tag number so a tool can name it.
    Other(u32),
}

/// `floating-point [7] IMPLICIT SEQUENCE { format-width [0] Unsigned8, exponent-width [1] Unsigned8 }`.
const FLOATING_POINT: u32 = 7;

impl TypeSpec {
    /// Decode one `TypeSpecification`.
    pub fn parse(t: &Tlv<'_>, limits: &Limits) -> Result<TypeSpec> {
        TypeSpec::parse_depth(t, limits, 0)
    }

    fn parse_depth(t: &Tlv<'_>, limits: &Limits, depth: usize) -> Result<TypeSpec> {
        if depth > limits.max_depth {
            return Err(Error::LimitExceeded { limit: "max_depth", value: depth });
        }
        if t.tag.class != crate::ber::Class::Context {
            return Err(Error::decode(DecodeReason::UnexpectedTag, t.offset));
        }
        Ok(match t.tag.number {
            0 => {
                let name = super::ObjectName::parse(&t.children().next_required()?)?;
                match name {
                    super::ObjectName::DomainSpecific { domain, item } => TypeSpec::Named { domain: Some(String::from(domain)), item: String::from(item) },
                    super::ObjectName::VmdSpecific(n) | super::ObjectName::AaSpecific(n) => TypeSpec::Named { domain: None, item: String::from(n) },
                }
            }
            1 => {
                let mut c = t.children();
                let packed = c.next_if_tag(Tag::context(0))?.map(|t| t.boolean()).transpose()?.unwrap_or(false);
                let elements = c.next_tag(Tag::context(1))?.unsigned_lenient_u32()?;
                let element_type = TypeSpec::parse_depth(&c.next_tag(Tag::context_constructed(2))?.children().next_required()?, limits, depth + 1)?;
                TypeSpec::Array { packed, elements, element_type: Box::new(element_type) }
            }
            2 => {
                let mut c = t.children();
                let packed = c.next_if_tag(Tag::context(0))?.map(|t| t.boolean()).transpose()?.unwrap_or(false);
                let list = c.next_tag(Tag::context_constructed(1))?;
                let mut components = Vec::new();
                for item in list.children() {
                    if components.len() >= limits.max_dataset_members {
                        return Err(Error::LimitExceeded { limit: "max_dataset_members", value: components.len() + 1 });
                    }
                    let mut m = item?.expect(Tag::universal(crate::ber::universal::SEQUENCE, true))?.children();
                    let name = m.next_if_tag(Tag::context(0))?.map(|t| t.visible_string()).transpose()?.map(String::from);
                    let type_spec = TypeSpec::parse_depth(&m.next_tag(Tag::context_constructed(1))?.children().next_required()?, limits, depth + 1)?;
                    components.push(Component { name, type_spec });
                }
                TypeSpec::Structure { packed, components }
            }
            tag::BOOLEAN => TypeSpec::Boolean,
            tag::BIT_STRING => TypeSpec::BitString(t.integer_i32()?),
            tag::INTEGER => TypeSpec::Integer(width(t)?),
            tag::UNSIGNED => TypeSpec::Unsigned(width(t)?),
            FLOATING_POINT => {
                // The two widths are **unnamed** members of the SEQUENCE, so ISO 9506-2
                // encodes them as universal INTEGERs — not as `[0]`/`[1]`. Wireshark's
                // stripped module has no `floating-point` in `TypeSpecification` at all, so
                // the oracle cannot tell the two apart and only a second stack can: this is
                // what libiec61850 writes and reads 🌐. The context-tagged form is accepted
                // too: a peer's octets that can be understood are understood.
                let mut c = t.children();
                let format_width = width(&next_width(&mut c, 0)?)?;
                let exponent_width = width(&next_width(&mut c, 1)?)?;
                TypeSpec::FloatingPoint { format_width, exponent_width }
            }
            tag::OCTET_STRING => TypeSpec::OctetString(t.integer_i32()?),
            tag::VISIBLE_STRING => TypeSpec::VisibleString(t.integer_i32()?),
            tag::GENERALIZED_TIME => TypeSpec::GeneralizedTime,
            tag::BINARY_TIME => TypeSpec::BinaryTime(t.boolean()?),
            tag::BCD => TypeSpec::Bcd(width(t)?),
            tag::MMS_STRING => TypeSpec::MmsString(t.integer_i32()?),
            tag::UTC_TIME => TypeSpec::UtcTime,
            other => TypeSpec::Other(other),
        })
    }

    /// Encode this type specification into `e`.
    pub fn write(&self, e: &mut Encoder) -> Result<()> {
        match self {
            TypeSpec::Named { domain, item } => {
                e.constructed(Tag::context_constructed(0), |e| match domain {
                    Some(d) => super::ObjectName::DomainSpecific { domain: d, item }.write(e),
                    None => super::ObjectName::VmdSpecific(item).write(e),
                })?;
            }
            TypeSpec::Array { packed, elements, element_type } => {
                e.constructed(Tag::context_constructed(1), |e| {
                    if *packed {
                        e.boolean(Tag::context(0), true)?;
                    }
                    e.unsigned(Tag::context(1), u64::from(*elements))?;
                    e.constructed(Tag::context_constructed(2), |e| element_type.write(e))?;
                    Ok(())
                })?;
            }
            TypeSpec::Structure { packed, components } => {
                e.constructed(Tag::context_constructed(2), |e| {
                    if *packed {
                        e.boolean(Tag::context(0), true)?;
                    }
                    e.constructed(Tag::context_constructed(1), |e| {
                        for c in components {
                            e.constructed(Tag::universal(crate::ber::universal::SEQUENCE, true), |e| {
                                if let Some(n) = &c.name {
                                    e.visible_string(Tag::context(0), n)?;
                                }
                                e.constructed(Tag::context_constructed(1), |e| c.type_spec.write(e))?;
                                Ok(())
                            })?;
                        }
                        Ok(())
                    })?;
                    Ok(())
                })?;
            }
            TypeSpec::Boolean => {
                e.primitive(Tag::context(tag::BOOLEAN), &[])?;
            }
            TypeSpec::BitString(n) => {
                e.integer(Tag::context(tag::BIT_STRING), i64::from(*n))?;
            }
            TypeSpec::Integer(w) => {
                e.unsigned(Tag::context(tag::INTEGER), u64::from(*w))?;
            }
            TypeSpec::Unsigned(w) => {
                e.unsigned(Tag::context(tag::UNSIGNED), u64::from(*w))?;
            }
            TypeSpec::FloatingPoint { format_width, exponent_width } => {
                e.constructed(Tag::context_constructed(FLOATING_POINT), |e| {
                    e.unsigned(Tag::universal(crate::ber::universal::INTEGER, false), u64::from(*format_width))?;
                    e.unsigned(Tag::universal(crate::ber::universal::INTEGER, false), u64::from(*exponent_width))?;
                    Ok(())
                })?;
            }
            TypeSpec::OctetString(n) => {
                e.integer(Tag::context(tag::OCTET_STRING), i64::from(*n))?;
            }
            TypeSpec::VisibleString(n) => {
                e.integer(Tag::context(tag::VISIBLE_STRING), i64::from(*n))?;
            }
            TypeSpec::GeneralizedTime => {
                e.primitive(Tag::context(tag::GENERALIZED_TIME), &[])?;
            }
            TypeSpec::BinaryTime(dated) => {
                e.boolean(Tag::context(tag::BINARY_TIME), *dated)?;
            }
            TypeSpec::Bcd(n) => {
                e.unsigned(Tag::context(tag::BCD), u64::from(*n))?;
            }
            TypeSpec::MmsString(n) => {
                e.integer(Tag::context(tag::MMS_STRING), i64::from(*n))?;
            }
            TypeSpec::UtcTime => {
                e.primitive(Tag::context(tag::UTC_TIME), &[])?;
            }
            TypeSpec::Other(n) => {
                e.primitive(Tag::context(*n), &[])?;
            }
        }
        Ok(())
    }

    /// The component with this name, for a structure.
    pub fn component(&self, name: &str) -> Option<&TypeSpec> {
        match self {
            TypeSpec::Structure { components, .. } => components.iter().find(|c| c.name.as_deref() == Some(name)).map(|c| &c.type_spec),
            _ => None,
        }
    }

    /// The component names of a structure, in order.
    pub fn component_names(&self) -> Vec<&str> {
        match self {
            TypeSpec::Structure { components, .. } => components.iter().filter_map(|c| c.name.as_deref()).collect(),
            _ => Vec::new(),
        }
    }
}

/// One width of a `floating-point` type specification, in either encoding.
///
/// ISO 9506-2 leaves `format-width` and `exponent-width` unnamed, so the conformant octets are
/// universal INTEGERs; `tag` is the context-tagged alternative, which is accepted on the way
/// in.
fn next_width<'a>(c: &mut Cursor<'a>, tag: u32) -> Result<Tlv<'a>> {
    let t = c.next_required()?;
    if t.tag == Tag::universal(crate::ber::universal::INTEGER, false) || t.tag == Tag::context(tag) {
        Ok(t)
    } else {
        Err(Error::decode(DecodeReason::UnexpectedTag, t.offset))
    }
}

fn width(t: &Tlv<'_>) -> Result<u8> {
    u8::try_from(t.unsigned_lenient_u32()?).map_err(|_| Error::decode(DecodeReason::BadValue, t.value_offset))
}

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

    fn round_trip(spec: &TypeSpec) -> TypeSpec {
        let mut e = Encoder::new();
        spec.write(&mut e).unwrap();
        let bytes = e.into_vec();
        let back = TypeSpec::parse(&Cursor::new(&bytes).next_required().unwrap(), &Limits::DEFAULT).unwrap();
        assert_eq!(&back, spec);
        back
    }

    /// The octets a second stack actually puts on the wire for `MMXU1$MX$TotW$mag`.
    ///
    /// `floating-point [7]`'s two widths are **unnamed** members of the SEQUENCE, so they are
    /// universal INTEGERs and not `[0]`/`[1]`. Nothing in this repository could have caught
    /// the difference: Wireshark's stripped module has no `floating-point` in
    /// `TypeSpecification` at all, so the oracle dissects either form without complaint, and
    /// both halves of this crate shared the wrong encoder. libiec61850 refused what we wrote
    /// and we refused what it wrote — in both directions, silently, as a timeout.
    #[test]
    fn a_floating_point_type_is_the_octets_the_field_writes() {
        // libiec61850 1.6.2, `GetVariableAccessAttributes` for `GGIO1$MX$AnIn1` 🌐.
        const VENDOR: &[u8] = &[
            0xa2, 0x31, 0xa1, 0x2f, 0x30, 0x1a, 0x80, 0x03, b'm', b'a', b'g', 0xa1, 0x13, 0xa2, 0x11, 0xa1, 0x0f, 0x30, 0x0d, 0x80, 0x01, b'f', 0xa1, 0x08,
            0xa7, 0x06, 0x02, 0x01, 0x20, 0x02, 0x01, 0x08, 0x30, 0x08, 0x80, 0x01, b'q', 0xa1, 0x03, 0x84, 0x01, 0xf3, 0x30, 0x07, 0x80, 0x01, b't', 0xa1,
            0x02, 0x91, 0x00,
        ];
        let spec = TypeSpec::parse(&Cursor::new(VENDOR).next_required().unwrap(), &Limits::DEFAULT).expect("the field's octets decode");
        assert_eq!(spec.component_names(), ["mag", "q", "t"]);
        assert_eq!(spec.component("mag").and_then(|m| m.component("f")), Some(&TypeSpec::FloatingPoint { format_width: 32, exponent_width: 8 }));
        // And we write what it writes, byte for byte — which is the half a round trip through
        // our own encoder can never prove.
        let mut e = Encoder::new();
        spec.write(&mut e).unwrap();
        assert_eq!(e.into_vec(), VENDOR);
    }

    /// The context-tagged widths are read too, because a peer's octets that can be understood
    /// are understood.
    #[test]
    fn the_older_context_tagged_widths_are_still_accepted() {
        const LEGACY: &[u8] = &[0xa7, 0x06, 0x80, 0x01, 0x40, 0x81, 0x01, 0x0b];
        let spec = TypeSpec::parse(&Cursor::new(LEGACY).next_required().unwrap(), &Limits::DEFAULT).expect("decode");
        assert_eq!(spec, TypeSpec::FloatingPoint { format_width: 64, exponent_width: 11 });
        // Anything else in that position is still a refusal rather than a guess.
        assert!(TypeSpec::parse(&Cursor::new(&[0xa7, 0x06, 0x83, 0x01, 0x40, 0x81, 0x01, 0x0b]).next_required().unwrap(), &Limits::DEFAULT).is_err());
    }

    #[test]
    fn the_shape_of_an_oper_is_what_a_client_needs_before_it_writes_one() {
        // What a server answers for `CSWI1$CO$Pos$Oper`: the structure a control is.
        let oper = TypeSpec::Structure {
            packed: false,
            components: alloc::vec![
                Component { name: Some(String::from("ctlVal")), type_spec: TypeSpec::BitString(2) },
                Component {
                    name: Some(String::from("origin")),
                    type_spec: TypeSpec::Structure {
                        packed: false,
                        components: alloc::vec![
                            Component { name: Some(String::from("orCat")), type_spec: TypeSpec::Integer(8) },
                            Component { name: Some(String::from("orIdent")), type_spec: TypeSpec::OctetString(-64) },
                        ],
                    },
                },
                Component { name: Some(String::from("ctlNum")), type_spec: TypeSpec::Unsigned(8) },
                Component { name: Some(String::from("T")), type_spec: TypeSpec::UtcTime },
                Component { name: Some(String::from("Test")), type_spec: TypeSpec::Boolean },
                Component { name: Some(String::from("Check")), type_spec: TypeSpec::BitString(2) },
            ],
        };
        let back = round_trip(&oper);
        assert_eq!(back.component_names(), ["ctlVal", "origin", "ctlNum", "T", "Test", "Check"]);
        assert_eq!(back.component("Check"), Some(&TypeSpec::BitString(2)));
        // A bounded string keeps its sign: -64 is "at most 64", 64 would be "exactly 64".
        assert_eq!(back.component("origin").and_then(|o| o.component("orIdent")), Some(&TypeSpec::OctetString(-64)));
    }

    #[test]
    fn every_simple_type_round_trips() {
        for spec in [
            TypeSpec::Boolean,
            TypeSpec::BitString(13),
            TypeSpec::Integer(32),
            TypeSpec::Unsigned(16),
            TypeSpec::FloatingPoint { format_width: 32, exponent_width: 8 },
            TypeSpec::OctetString(-8),
            TypeSpec::VisibleString(129),
            TypeSpec::GeneralizedTime,
            TypeSpec::BinaryTime(true),
            TypeSpec::Bcd(4),
            TypeSpec::MmsString(-255),
            TypeSpec::UtcTime,
            TypeSpec::Named { domain: Some(String::from("LD0")), item: String::from("MyType") },
            TypeSpec::Named { domain: None, item: String::from("Global") },
            TypeSpec::Array { packed: false, elements: 4, element_type: Box::new(TypeSpec::Boolean) },
        ] {
            round_trip(&spec);
        }
    }

    #[test]
    fn a_type_nested_deeper_than_the_limit_is_refused_rather_than_recursed() {
        let deep =
            (0..40).fold(TypeSpec::Boolean, |t, _| TypeSpec::Structure { packed: false, components: alloc::vec![Component { name: None, type_spec: t }] });
        let mut e = Encoder::new();
        deep.write(&mut e).unwrap();
        let bytes = e.into_vec();
        assert!(matches!(
            TypeSpec::parse(&Cursor::new(&bytes).next_required().unwrap(), &Limits::DEFAULT),
            Err(Error::LimitExceeded { limit: "max_depth", .. })
        ));
    }
}