iso15118 0.5.0

ISO 15118 vehicle-to-grid (V2G) communication — EXI codec, message sets, session engines and Plug & Charge signatures; sans-I/O and no_std-capable, for both EVCC and SECC
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! V2G Transfer Protocol framing (ISO 15118-2 §7.8.3, ISO 15118-20 §9.3).
//!
//! Every byte that crosses the charging cable above TCP or UDP is wrapped in
//! the same eight-byte header:
//!
//! ```text
//! 0        1        2        3        4        5        6        7        8
//! +--------+--------+--------+--------+--------+--------+--------+--------+
//! |  0x01  |  0xFE  |   payload type  |            payload length         |
//! +--------+--------+--------+--------+--------+--------+--------+--------+
//!  version  ~version     big-endian              big-endian, in bytes
//! ```
//!
//! The payload length arrives before, and is not covered by, any
//! authentication. It is the first hostile number a charging station reads, so
//! [`Header::decode`] never allocates on the strength of it — the caller
//! compares it against its own limit and decides.

use core::fmt;

/// Length of the V2GTP header in bytes.
pub const HEADER_LEN: usize = 8;

/// The only protocol version defined for V2GTP.
pub const PROTOCOL_VERSION: u8 = 0x01;

/// UDP port the SECC Discovery Protocol listens on.
pub const SDP_PORT: u16 = 15118;

/// What the payload after the header contains.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum PayloadType {
    /// `0x8001` — an EXI-encoded V2G message.
    ///
    /// Shared by three schemas: the `supportedAppProtocol` handshake (all
    /// protocol generations), every DIN SPEC 70121 message, and every
    /// ISO 15118-2 message. Which grammar applies is session state, not
    /// something the frame tells you — one of the reasons the handshake has to
    /// be tracked rather than sniffed.
    ExiEncodedV2gMessage,
    /// `0x8002` — ISO 15118-20 mainstream (`CommonMessages`).
    Part20Main,
    /// `0x8003` — ISO 15118-20 AC mainstream.
    Part20Ac,
    /// `0x8004` — ISO 15118-20 DC mainstream.
    Part20Dc,
    /// `0x8005` — ISO 15118-20 ACDP (pantograph) mainstream.
    Part20Acdp,
    /// `0x8006` — ISO 15118-20 WPT (wireless) mainstream.
    Part20Wpt,
    /// `0x9000` — SDP request.
    SdpRequest,
    /// `0x9001` — SDP response.
    SdpResponse,
    /// `0x9002` — SDP request over a wireless link (ISO 15118-20).
    SdpWirelessRequest,
    /// `0x9003` — SDP response over a wireless link (ISO 15118-20).
    SdpWirelessResponse,
    /// `0xA000..=0xFFFF` — reserved for manufacturer use (Table 10).
    ///
    /// A legitimate code that this entity has no meaning for. \[V2G2-800\] says
    /// to ignore such a message, not to reject it, and
    /// [`Connection`](crate::session::Connection) does — a vendor extension on
    /// the wire must not end a charging session.
    ManufacturerSpecific(u16),
    /// A code Table 10 marks reserved: `0x0000..=0x8000`, `0x8007..=0x8FFF`
    /// and `0x9004..=0x9FFF`.
    ///
    /// Not a legitimate code, and still not a framing error. \[V2G2-092\] and
    /// \[V2G2-094\] have a receiver check the payload *type* and then the
    /// payload *length*, and \[V2G2-800\] has it ignore the message — so the
    /// header is intact, the length is trustworthy, and the frame boundary is
    /// exactly where the peer said it was. Failing here instead would end the
    /// session over a frame the standard says to skip, and would throw away a
    /// resynchronisation point that is known-good.
    Reserved(u16),
}

impl PayloadType {
    /// The on-the-wire code.
    #[must_use]
    pub const fn as_u16(self) -> u16 {
        match self {
            Self::ExiEncodedV2gMessage => 0x8001,
            Self::Part20Main => 0x8002,
            Self::Part20Ac => 0x8003,
            Self::Part20Dc => 0x8004,
            Self::Part20Acdp => 0x8005,
            Self::Part20Wpt => 0x8006,
            Self::SdpRequest => 0x9000,
            Self::SdpResponse => 0x9001,
            Self::SdpWirelessRequest => 0x9002,
            Self::SdpWirelessResponse => 0x9003,
            Self::ManufacturerSpecific(v) | Self::Reserved(v) => v,
        }
    }

    /// Classifies a payload type code. Every `u16` is one.
    ///
    /// Infallible on purpose. A code outside Table 10's assignments is not a
    /// malformed *header* — the sync pattern matched and the length field is
    /// where it belongs — so refusing to parse it would discard the one thing
    /// that makes the message skippable. \[V2G2-800\] asks for the message to
    /// be ignored, and ignoring it needs its length.
    #[must_use]
    pub const fn from_u16(value: u16) -> Self {
        match value {
            0x8001 => Self::ExiEncodedV2gMessage,
            0x8002 => Self::Part20Main,
            0x8003 => Self::Part20Ac,
            0x8004 => Self::Part20Dc,
            0x8005 => Self::Part20Acdp,
            0x8006 => Self::Part20Wpt,
            0x9000 => Self::SdpRequest,
            0x9001 => Self::SdpResponse,
            0x9002 => Self::SdpWirelessRequest,
            0x9003 => Self::SdpWirelessResponse,
            0xA000..=0xFFFF => Self::ManufacturerSpecific(value),
            other => Self::Reserved(other),
        }
    }

    /// True for a code this entity has no processing for — manufacturer-specific
    /// or reserved.
    ///
    /// The set \[V2G2-800\] says to ignore.
    #[must_use]
    pub const fn is_ignorable(self) -> bool {
        matches!(self, Self::ManufacturerSpecific(_) | Self::Reserved(_))
    }

    /// Whether a session speaking `protocol` carries its messages under this
    /// payload type.
    ///
    /// The question \[V2G2-800\] turns on, and it is **not** "can this build
    /// decode it". `0x8001` belongs to a DIN SPEC 70121 session whether or not
    /// this crate has that message set; `0x8002` does not belong to an
    /// ISO 15118-2 session however many features are enabled. The first is a
    /// missing codec, which the caller can supply through
    /// [`Connection::next_frame`](crate::session::Connection::next_frame); the
    /// second is a message for somebody else, which is ignored.
    ///
    /// `None` is a session that has not negotiated yet, where only the
    /// `supportedAppProtocol` handshake belongs.
    #[must_use]
    #[allow(
        clippy::match_same_arms,
        reason = "one arm per generation's payload types; merging them by their \
                  shared `true` would hide which types belong to which"
    )]
    pub const fn belongs_to(self, protocol: Option<crate::Protocol>) -> bool {
        use crate::Protocol as P;
        match (self, protocol) {
            // `0x8001` is the handshake before negotiation, and afterwards the
            // one type the two first-generation protocols share.
            (Self::ExiEncodedV2gMessage, None | Some(P::Iso2 | P::Din70121)) => true,
            // ISO 15118-20 gives each schema set its own type, and uses none of
            // them before it has been negotiated.
            (
                Self::Part20Main
                | Self::Part20Ac
                | Self::Part20Dc
                | Self::Part20Acdp
                | Self::Part20Wpt,
                Some(P::Iso20),
            ) => true,
            // Everything else, including every SDP type: SDP is a datagram
            // exchange that happens before a session exists, so no session
            // carries one.
            _ => false,
        }
    }

    /// True for the payload types that carry an EXI-encoded V2G message, as
    /// opposed to the fixed-layout SDP datagrams.
    #[must_use]
    pub const fn is_exi(self) -> bool {
        matches!(
            self,
            Self::ExiEncodedV2gMessage
                | Self::Part20Main
                | Self::Part20Ac
                | Self::Part20Dc
                | Self::Part20Acdp
                | Self::Part20Wpt
        )
    }

    /// True for the two SDP request types.
    #[must_use]
    pub const fn is_sdp_request(self) -> bool {
        matches!(self, Self::SdpRequest | Self::SdpWirelessRequest)
    }

    /// True for the two SDP response types.
    #[must_use]
    pub const fn is_sdp_response(self) -> bool {
        matches!(self, Self::SdpResponse | Self::SdpWirelessResponse)
    }
}

/// A decoded V2GTP header.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Header {
    /// What the payload holds.
    pub payload_type: PayloadType,
    /// Declared payload length in bytes — **not yet validated against any
    /// buffer**.
    pub payload_len: u32,
}

impl Header {
    /// Builds a header for a payload of `payload_len` bytes.
    #[must_use]
    pub const fn new(payload_type: PayloadType, payload_len: u32) -> Self {
        Self { payload_type, payload_len }
    }

    /// Serialises the header into eight bytes.
    #[must_use]
    pub const fn to_bytes(self) -> [u8; HEADER_LEN] {
        let ty = self.payload_type.as_u16().to_be_bytes();
        let len = self.payload_len.to_be_bytes();
        [PROTOCOL_VERSION, !PROTOCOL_VERSION, ty[0], ty[1], len[0], len[1], len[2], len[3]]
    }

    /// Writes the header into `out`, which must be at least [`HEADER_LEN`].
    pub fn write_to(self, out: &mut [u8]) -> Result<(), V2gtpError> {
        let bytes = self.to_bytes();
        out.get_mut(..HEADER_LEN).ok_or(V2gtpError::BufferTooSmall)?.copy_from_slice(&bytes);
        Ok(())
    }

    /// Parses a header from the first eight bytes of `input`.
    ///
    /// Succeeds even when `input` is shorter than the declared payload — that
    /// is the normal case while a TCP reader is still accumulating bytes.
    pub fn decode(input: &[u8]) -> Result<Self, V2gtpError> {
        let head: &[u8; HEADER_LEN] =
            input.get(..HEADER_LEN).ok_or(V2gtpError::Incomplete)?.try_into().unwrap();

        if head[0] != PROTOCOL_VERSION {
            return Err(V2gtpError::UnsupportedVersion(head[0]));
        }
        // The inverse byte is the spec's own framing check; a mismatch means we
        // are not looking at a V2GTP header at all.
        if head[1] != !PROTOCOL_VERSION {
            return Err(V2gtpError::VersionMismatch { version: head[0], inverse: head[1] });
        }

        let payload_type = PayloadType::from_u16(u16::from_be_bytes([head[2], head[3]]));
        let payload_len = u32::from_be_bytes([head[4], head[5], head[6], head[7]]);

        Ok(Self { payload_type, payload_len })
    }
}

/// Splits one complete V2GTP frame off the front of `input`.
///
/// Returns the header, the payload, and the unconsumed remainder — the shape a
/// stream reader wants. `max_payload_len` is the caller's policy limit;
/// anything larger is refused before the payload is touched.
pub fn split_frame(
    input: &[u8],
    max_payload_len: usize,
) -> Result<(Header, &[u8], &[u8]), V2gtpError> {
    let header = Header::decode(input)?;
    let len = usize::try_from(header.payload_len).map_err(|_| V2gtpError::PayloadTooLarge {
        declared: header.payload_len,
        limit: max_payload_len,
    })?;
    if len > max_payload_len {
        return Err(V2gtpError::PayloadTooLarge {
            declared: header.payload_len,
            limit: max_payload_len,
        });
    }
    let end = HEADER_LEN.checked_add(len).ok_or(V2gtpError::Incomplete)?;
    if input.len() < end {
        return Err(V2gtpError::Incomplete);
    }
    Ok((header, &input[HEADER_LEN..end], &input[end..]))
}

/// Writes header and payload into `out`, returning the total frame length.
pub fn write_frame(
    payload_type: PayloadType,
    payload: &[u8],
    out: &mut [u8],
) -> Result<usize, V2gtpError> {
    // The length field is 32 bits wide, so a payload that does not fit one is
    // not a frame at all. `declared` is what the caller asked for, capped at the
    // field's width; `limit` is the width itself.
    let len = u32::try_from(payload.len()).map_err(|_| V2gtpError::PayloadTooLarge {
        declared: u32::MAX,
        limit: u32::MAX as usize,
    })?;
    // Checked, and the symmetry with `split_frame` is the point rather than the
    // arithmetic: both sides of one rule should agree about whether it can
    // overflow. CVE-2026-54169 is this exact sum done the other way — a payload
    // measured against the buffer and then written at `buffer + 8`.
    let total = HEADER_LEN.checked_add(payload.len()).ok_or(V2gtpError::BufferTooSmall)?;
    if out.len() < total {
        return Err(V2gtpError::BufferTooSmall);
    }
    Header::new(payload_type, len).write_to(out)?;
    out[HEADER_LEN..total].copy_from_slice(payload);
    Ok(total)
}

/// Errors from V2GTP framing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum V2gtpError {
    /// Fewer bytes are available than the frame needs; read more and retry.
    Incomplete,
    /// The destination buffer is too small.
    BufferTooSmall,
    /// The protocol version byte is not `0x01`.
    UnsupportedVersion(u8),
    /// The version byte and its inverse do not agree.
    VersionMismatch {
        /// The version byte as received.
        version: u8,
        /// The inverse-version byte as received.
        inverse: u8,
    },
    /// The declared payload exceeds the caller's limit.
    PayloadTooLarge {
        /// Length the header declared.
        declared: u32,
        /// Limit the caller allows.
        limit: usize,
    },
}

impl fmt::Display for V2gtpError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Incomplete => f.write_str("incomplete V2GTP frame"),
            Self::BufferTooSmall => f.write_str("output buffer too small for V2GTP frame"),
            Self::UnsupportedVersion(v) => write!(f, "unsupported V2GTP protocol version {v:#04x}"),
            Self::VersionMismatch { version, inverse } => {
                write!(f, "V2GTP version {version:#04x} does not match its inverse {inverse:#04x}")
            }
            Self::PayloadTooLarge { declared, limit } => {
                write!(f, "V2GTP payload of {declared} bytes exceeds the {limit} byte limit")
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for V2gtpError {}

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

    #[test]
    fn header_bytes_match_the_spec_layout() {
        let h = Header::new(PayloadType::ExiEncodedV2gMessage, 0x1234);
        assert_eq!(h.to_bytes(), [0x01, 0xFE, 0x80, 0x01, 0x00, 0x00, 0x12, 0x34]);
    }

    #[test]
    fn header_roundtrips() {
        for ty in [
            PayloadType::ExiEncodedV2gMessage,
            PayloadType::Part20Main,
            PayloadType::Part20Ac,
            PayloadType::Part20Dc,
            PayloadType::Part20Acdp,
            PayloadType::Part20Wpt,
            PayloadType::SdpRequest,
            PayloadType::SdpResponse,
            PayloadType::SdpWirelessRequest,
            PayloadType::SdpWirelessResponse,
            PayloadType::ManufacturerSpecific(0xA123),
        ] {
            let h = Header::new(ty, 42);
            assert_eq!(Header::decode(&h.to_bytes()).unwrap(), h);
            assert_eq!(PayloadType::from_u16(ty.as_u16()), ty);
        }
    }

    #[test]
    fn a_bad_inverse_version_is_rejected() {
        let bytes = [0x01, 0x00, 0x80, 0x01, 0, 0, 0, 0];
        assert_eq!(
            Header::decode(&bytes),
            Err(V2gtpError::VersionMismatch { version: 0x01, inverse: 0x00 })
        );
    }

    /// \[V2G2-800\]: a reserved payload type is a message to *ignore*, not a
    /// header to reject. Classifying it keeps the length field, which is the
    /// only thing that makes ignoring it possible.
    #[test]
    fn reserved_payload_types_classify_rather_than_fail() {
        for value in [0x0000, 0x8000, 0x8007, 0x8FFF, 0x9004, 0x9FFF] {
            let ty = PayloadType::from_u16(value);
            assert_eq!(ty, PayloadType::Reserved(value));
            assert!(ty.is_ignorable());
            assert!(!ty.is_exi());
            assert_eq!(ty.as_u16(), value, "the code round-trips so a log can name it");
        }
        for value in [0xA000, 0xA123, 0xFFFF] {
            let ty = PayloadType::from_u16(value);
            assert_eq!(ty, PayloadType::ManufacturerSpecific(value));
            assert!(ty.is_ignorable());
        }
        assert!(!PayloadType::from_u16(0x8001).is_ignorable());
        assert!(!PayloadType::from_u16(0x9000).is_ignorable());
    }

    /// A reserved frame is still a *frame*: the header is intact, so the next
    /// one starts exactly where its length says.
    #[test]
    fn a_reserved_frame_does_not_lose_the_frame_boundary() {
        let mut buf = [0u8; 64];
        let n = write_frame(PayloadType::Reserved(0x8007), &[1, 2, 3], &mut buf).unwrap();
        let (header, payload, rest) = split_frame(&buf[..n], 1024).unwrap();
        assert_eq!(header.payload_type, PayloadType::Reserved(0x8007));
        assert_eq!(payload, &[1, 2, 3]);
        assert!(rest.is_empty());
    }

    #[test]
    fn a_short_buffer_is_incomplete_not_invalid() {
        assert_eq!(Header::decode(&[0x01, 0xFE, 0x80]), Err(V2gtpError::Incomplete));
    }

    #[test]
    fn split_frame_returns_payload_and_remainder() {
        let mut buf = [0u8; 32];
        let n = write_frame(PayloadType::Part20Main, &[1, 2, 3, 4], &mut buf).unwrap();
        assert_eq!(n, HEADER_LEN + 4);
        buf[n] = 0xFF; // a second frame starting

        let (h, payload, rest) = split_frame(&buf[..=n], 1024).unwrap();
        assert_eq!(h.payload_type, PayloadType::Part20Main);
        assert_eq!(payload, &[1, 2, 3, 4]);
        assert_eq!(rest, &[0xFF]);
    }

    #[test]
    fn an_oversized_declared_payload_is_refused_before_reading() {
        // Header claims 4 GiB; only the header itself is present.
        let bytes = [0x01, 0xFE, 0x80, 0x01, 0xFF, 0xFF, 0xFF, 0xFF];
        assert_eq!(
            split_frame(&bytes, 65536),
            Err(V2gtpError::PayloadTooLarge { declared: u32::MAX, limit: 65536 })
        );
    }

    #[test]
    fn a_truncated_payload_is_incomplete() {
        let bytes = [0x01, 0xFE, 0x80, 0x01, 0x00, 0x00, 0x00, 0x10, 0xAA];
        assert_eq!(split_frame(&bytes, 65536), Err(V2gtpError::Incomplete));
    }

    #[test]
    fn payload_type_classification() {
        assert!(PayloadType::Part20Dc.is_exi());
        assert!(!PayloadType::SdpRequest.is_exi());
        assert!(PayloadType::SdpWirelessRequest.is_sdp_request());
        assert!(PayloadType::SdpResponse.is_sdp_response());
        assert!(!PayloadType::SdpResponse.is_sdp_request());
    }
}