fix(abcip): harden Ab.Transport CIP codec and EncapsulationClient (#564, #565)

CIP codec (#564): PatchU16 bounds guard; CipReply content equality; CipPath
port/length/ASCII/odd/oversize validation with ArgumentException for malformed
tag names and routes; CipPath.MessageRouter/ConnectionManager are now
ReadOnlySpan<byte>; refused Forward Open surfaces ForwardOpenRefusedException
with structured general/extended status; test CaptureFile uses BinaryPrimitives.

EncapsulationClient (#565): frame write bounded by the exchange timeout, which
faults (never cancels) the connection; finite positive timeouts enforced at
every entry point; gate wait bounded by the timeout; deterministic reorder of
the 300 ms test; new dispose-during-drain, gate-wait and RegisterSession
zero-context tests.

Claude-Session: https://claude.ai/code/session_01Ef2ozxS7QPanGT8uoATbTe
This commit is contained in:
Joseph Doherty
2026-10-07 22:54:32 -04:00
parent 04b6563286
commit 7892eb13a8
15 changed files with 379 additions and 30 deletions
@@ -15,24 +15,34 @@ public static class CipPath
if (parts.Length % 2 != 0) throw new ArgumentException($"CIP path '{cipPath}' must be port,link pairs.", nameof(cipPath));
for (var i = 0; i < parts.Length; i += 2)
{
var port = int.Parse(parts[i], CultureInfo.InvariantCulture);
if (!ushort.TryParse(parts[i], NumberStyles.None, CultureInfo.InvariantCulture, out var port))
throw new ArgumentException($"CIP path '{cipPath}' has a port '{parts[i]}' that is not 0..65535.", nameof(cipPath));
var link = parts[i + 1];
// A link is a slot byte or an IP address/hostname; neither contains whitespace. Without this a
// typo like "1,2 3" would be sent as an ASCII link "2 3" instead of failing here.
if (link.Length == 0 || link.Any(char.IsWhiteSpace))
throw new ArgumentException($"CIP path '{cipPath}' has an empty or malformed link '{link}'.", nameof(cipPath));
var isByte = byte.TryParse(link, NumberStyles.None, CultureInfo.InvariantCulture, out var linkByte);
byte[] a = [];
if (!isByte)
{
// The link-address length rides in one byte, and a non-ASCII char would be sent as '?'.
a = EncodeAscii(link, cipPath, nameof(cipPath), "link");
}
if (port < 15)
{
if (isByte) w.U8((byte)port).U8(linkByte);
else { var a = Encoding.ASCII.GetBytes(link); w.U8((byte)(0x10 | port)).U8((byte)a.Length).Bytes(a).PadToEven(); }
else w.U8((byte)(0x10 | port)).U8((byte)a.Length).Bytes(a).PadToEven();
}
else
{
if (isByte) w.U8(0x0F).U16((ushort)port).U8(linkByte);
else { var a = Encoding.ASCII.GetBytes(link); w.U8(0x1F).U8((byte)a.Length).U16((ushort)port).Bytes(a).PadToEven(); }
if (isByte) w.U8(0x0F).U16(port).U8(linkByte);
else w.U8(0x1F).U8((byte)a.Length).U16(port).Bytes(a).PadToEven();
}
}
// The route size is carried in words in one byte (Unconnected Send / Forward Open paths).
if (w.Length > MaxPathBytes)
throw new ArgumentException($"CIP path '{cipPath}' encodes to {w.Length} bytes; the maximum is {MaxPathBytes}.", nameof(cipPath));
return w.ToArray();
}
@@ -41,12 +51,20 @@ public static class CipPath
{
var dot = tagName.LastIndexOf('.');
if (dot > 0 && dot < tagName.Length - 1 && tagName[(dot + 1)..].All(char.IsAsciiDigit))
return (tagName[..dot], int.Parse(tagName[(dot + 1)..], CultureInfo.InvariantCulture));
{
if (!int.TryParse(tagName[(dot + 1)..], NumberStyles.None, CultureInfo.InvariantCulture, out var bit))
throw new ArgumentException($"Bit selector in '{tagName}' is out of range.", nameof(tagName));
return (tagName[..dot], bit);
}
return (tagName, null);
}
/// <exception cref="ArgumentException">The name is empty, has an empty member, an over-long (&gt; 255) or
/// non-ASCII member, an unterminated / non-numeric subscript, or ends in a bit selector.</exception>
public static byte[] EncodeSymbolic(string tagName)
{
if (string.IsNullOrEmpty(tagName))
throw new ArgumentException("Tag name is empty.", nameof(tagName));
if (SplitBitSelector(tagName).Bit is not null)
throw new ArgumentException($"'{tagName}' ends in a bit selector; strip it with SplitBitSelector first.", nameof(tagName));
var w = new CipWriter();
@@ -54,13 +72,19 @@ public static class CipPath
{
var bracket = part.IndexOf('[');
var name = bracket < 0 ? part : part[..bracket];
var a = Encoding.ASCII.GetBytes(name);
if (name.Length == 0)
throw new ArgumentException($"Tag name '{tagName}' has an empty member.", nameof(tagName));
var a = EncodeAscii(name, tagName, nameof(tagName), "member");
w.U8(0x91).U8((byte)a.Length).Bytes(a).PadToEven();
if (bracket >= 0)
{
foreach (var idxText in part[(bracket + 1)..part.IndexOf(']')].Split(',', StringSplitOptions.TrimEntries))
var close = part.IndexOf(']', bracket);
if (close != part.Length - 1)
throw new ArgumentException($"Tag name '{tagName}' has an unterminated or misplaced subscript in '{part}'.", nameof(tagName));
foreach (var idxText in part[(bracket + 1)..close].Split(',', StringSplitOptions.TrimEntries))
{
var idx = uint.Parse(idxText, CultureInfo.InvariantCulture);
if (!uint.TryParse(idxText, NumberStyles.None, CultureInfo.InvariantCulture, out var idx))
throw new ArgumentException($"Tag name '{tagName}' has a subscript '{idxText}' that is not an unsigned integer.", nameof(tagName));
if (idx < 0x100) w.U8(0x28).U8((byte)idx);
else if (idx < 0x10000) w.U8(0x29).U8(0).U16((ushort)idx);
else w.U8(0x2A).U8(0).U32(idx);
@@ -70,6 +94,17 @@ public static class CipPath
return w.ToArray();
}
/// <summary>ASCII bytes of a name / link whose length rides in a single byte.</summary>
private static byte[] EncodeAscii(string text, string whole, string paramName, string what)
{
if (text.Length > byte.MaxValue)
throw new ArgumentException($"'{whole}' has a {what} longer than 255 characters.", paramName);
foreach (var c in text)
if (!char.IsAscii(c))
throw new ArgumentException($"'{whole}' has a {what} with a non-ASCII character.", paramName);
return Encoding.ASCII.GetBytes(text);
}
/// <summary>Split on '.' outside brackets, keeping "Program:X" whole.</summary>
private static IEnumerable<string> SplitMembers(string name)
{
@@ -94,16 +129,25 @@ public static class CipPath
}
/// <summary>Prefixes the path with its size in 16-bit words.</summary>
/// <exception cref="ArgumentException">The segments are not a whole number of 16-bit words, or exceed
/// the 255-word maximum the one-byte size field can carry.</exception>
public static byte[] WithPathSize(byte[] segments)
{
if ((segments.Length & 1) != 0)
throw new ArgumentException($"A CIP path is whole 16-bit words; got {segments.Length} bytes.", nameof(segments));
if (segments.Length > MaxPathBytes)
throw new ArgumentException($"A CIP path is at most {MaxPathBytes} bytes (255 words); got {segments.Length}.", nameof(segments));
var w = new CipWriter();
w.U8((byte)(segments.Length / 2)).Bytes(segments);
return w.ToArray();
}
/// <summary>The path-size field is one byte of 16-bit words.</summary>
private const int MaxPathBytes = 255 * 2;
/// <summary>Message Router (class 2, instance 1).</summary>
public static readonly byte[] MessageRouter = [0x20, 0x02, 0x24, 0x01];
public static ReadOnlySpan<byte> MessageRouter => [0x20, 0x02, 0x24, 0x01];
/// <summary>Connection Manager (class 6, instance 1).</summary>
public static readonly byte[] ConnectionManager = [0x20, 0x06, 0x24, 0x01];
public static ReadOnlySpan<byte> ConnectionManager => [0x20, 0x06, 0x24, 0x01];
}
@@ -5,6 +5,25 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Ab.Transport.Cip;
/// status, extended status words, and the reply data.</summary>
public sealed record CipReply(byte Service, byte GeneralStatus, ushort[] ExtendedStatus, ReadOnlyMemory<byte> Data)
{
// Record equality over an array / ReadOnlyMemory is reference equality; two parses of the same wire
// bytes must compare equal, so compare the extended-status words and the data by content.
public bool Equals(CipReply? other) =>
other is not null
&& Service == other.Service
&& GeneralStatus == other.GeneralStatus
&& ExtendedStatus.AsSpan().SequenceEqual(other.ExtendedStatus)
&& Data.Span.SequenceEqual(other.Data.Span);
public override int GetHashCode()
{
var h = new HashCode();
h.Add(Service);
h.Add(GeneralStatus);
foreach (var e in ExtendedStatus) h.Add(e);
h.AddBytes(Data.Span);
return h.ToHashCode();
}
public AbStatus Status => AbStatusCodes.FromCip(GeneralStatus, ExtendedStatus);
public static CipReply Parse(ReadOnlyMemory<byte> raw)
@@ -9,6 +9,24 @@ public sealed record ForwardOpenParams(
public sealed record ForwardOpenReply(uint OTConnectionId, uint TOConnectionId, uint OTApiMicros, uint TOApiMicros);
/// <summary>A target refused a Forward Open. The refusal is data, not just message text: callers (and
/// diagnostics) read <see cref="GeneralStatus"/> / <see cref="ExtendedStatus"/> directly.</summary>
public sealed class ForwardOpenRefusedException : AbTransportException
{
public ForwardOpenRefusedException(AbStatus status, byte generalStatus, IReadOnlyList<ushort> extendedStatus)
: base(status, $"Forward Open refused: general 0x{generalStatus:X2}, extended {string.Join(",", extendedStatus.Select(e => $"0x{e:X4}"))}.")
{
GeneralStatus = generalStatus;
ExtendedStatus = [.. extendedStatus]; // defensive copy: the exception is immutable
}
/// <summary>The CIP general status of the refusal.</summary>
public byte GeneralStatus { get; }
/// <summary>The CIP extended-status words of the refusal (may be empty).</summary>
public IReadOnlyList<ushort> ExtendedStatus { get; }
}
/// <summary>Connection Manager (class 6) request builders and reply parsers.</summary>
public static class ConnectionManagerServices
{
@@ -52,8 +70,8 @@ public static class ConnectionManagerServices
public static ForwardOpenReply ParseForwardOpenReply(CipReply reply)
{
if (reply.GeneralStatus != 0)
throw new AbTransportException(reply.Status == AbStatus.BadReply ? AbStatus.BadConnection : reply.Status,
$"Forward Open refused: general 0x{reply.GeneralStatus:X2}, extended {string.Join(",", reply.ExtendedStatus.Select(e => $"0x{e:X4}"))}.");
throw new ForwardOpenRefusedException(reply.Status == AbStatus.BadReply ? AbStatus.BadConnection : reply.Status,
reply.GeneralStatus, reply.ExtendedStatus);
var r = new CipReader(reply.Data.Span);
var ot = r.U32(); var to = r.U32(); r.U16(); r.U16(); r.U32();
return new ForwardOpenReply(ot, to, r.U32(), r.U32());