- Wrap all JsonDocument.Parse calls in using blocks and Clone() each retained JsonElement to eliminate UAF hazard after GC. - Use JsonSerializer.Serialize with UnsafeRelaxedJsonEscaping so event names with " or \ produce \" / \ rather than " / plain \; avoids malformed JSON on Encode(). - Guard the [ ] block in Encode() behind EventName-or-args check so Connect/Disconnect packets round-trip as bare "0"/"1" not "0[]". - Add three regression tests: Connect no-bracket, Event round-trip, special-char event name escaping. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
198 lines
7.3 KiB
C#
198 lines
7.3 KiB
C#
using System.Text;
|
|
using System.Text.Encodings.Web;
|
|
using System.Text.Json;
|
|
|
|
namespace SVSim.BattleNode.Wire;
|
|
|
|
file static class SocketIoJsonOptions
|
|
{
|
|
internal static readonly JsonSerializerOptions EventNameOptions = new()
|
|
{
|
|
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Socket.IO v2 packet. Wire form: <c><type><N>-<ackId?>[json-args]</c> where
|
|
/// <c><N>-</c> appears only on binary types (5/6). For binary events/acks, the JSON contains
|
|
/// placeholders <c>{"_placeholder":true,"num":N}</c> that index into <see cref="BinaryAttachments"/>.
|
|
/// </summary>
|
|
public sealed class SocketIoFrame
|
|
{
|
|
public SocketIoPacketType Type { get; }
|
|
public int? AckId { get; }
|
|
public int AttachmentCount { get; }
|
|
public string? EventName { get; }
|
|
public JsonElement[] RawArgs { get; }
|
|
public IReadOnlyList<byte[]> BinaryAttachments { get; }
|
|
|
|
public SocketIoFrame(
|
|
SocketIoPacketType type,
|
|
int? ackId,
|
|
int attachmentCount,
|
|
string? eventName,
|
|
JsonElement[] rawArgs,
|
|
IReadOnlyList<byte[]> binaryAttachments)
|
|
{
|
|
Type = type;
|
|
AckId = ackId;
|
|
AttachmentCount = attachmentCount;
|
|
EventName = eventName;
|
|
RawArgs = rawArgs;
|
|
BinaryAttachments = binaryAttachments;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parse the text portion of a SIO frame. For binary events the attachments arrive as separate
|
|
/// WS frames after the text — the caller wires them up via <see cref="WithAttachments"/>.
|
|
/// </summary>
|
|
public static SocketIoFrame Parse(string raw)
|
|
{
|
|
if (string.IsNullOrEmpty(raw))
|
|
throw new ArgumentException("Empty SIO payload", nameof(raw));
|
|
|
|
var type = (SocketIoPacketType)(raw[0] - '0');
|
|
var cursor = 1;
|
|
|
|
var attachmentCount = 0;
|
|
if (type is SocketIoPacketType.BinaryEvent or SocketIoPacketType.BinaryAck)
|
|
{
|
|
var dashIdx = raw.IndexOf('-', cursor);
|
|
if (dashIdx < 0)
|
|
throw new ArgumentException("Binary frame missing '-' separator", nameof(raw));
|
|
if (!int.TryParse(raw.AsSpan(cursor, dashIdx - cursor), out attachmentCount))
|
|
throw new ArgumentException("Binary frame attachment count not parseable", nameof(raw));
|
|
cursor = dashIdx + 1;
|
|
}
|
|
|
|
// Skip namespace (only present if a '/' starts here, terminated by ',').
|
|
if (cursor < raw.Length && raw[cursor] == '/')
|
|
{
|
|
var commaIdx = raw.IndexOf(',', cursor);
|
|
cursor = commaIdx >= 0 ? commaIdx + 1 : raw.Length;
|
|
}
|
|
|
|
int? ackId = null;
|
|
if (cursor < raw.Length && char.IsDigit(raw[cursor]))
|
|
{
|
|
var start = cursor;
|
|
while (cursor < raw.Length && char.IsDigit(raw[cursor])) cursor++;
|
|
ackId = int.Parse(raw.AsSpan(start, cursor - start));
|
|
}
|
|
|
|
var argsJson = cursor < raw.Length ? raw.Substring(cursor) : string.Empty;
|
|
JsonElement[] allElements;
|
|
if (string.IsNullOrEmpty(argsJson))
|
|
{
|
|
allElements = Array.Empty<JsonElement>();
|
|
}
|
|
else
|
|
{
|
|
using var doc = JsonDocument.Parse(argsJson);
|
|
allElements = doc.RootElement.EnumerateArray().Select(el => el.Clone()).ToArray();
|
|
}
|
|
|
|
string? eventName = null;
|
|
JsonElement[] rawArgs;
|
|
if (type is SocketIoPacketType.Event or SocketIoPacketType.BinaryEvent && allElements.Length > 0)
|
|
{
|
|
eventName = allElements[0].GetString();
|
|
// RawArgs excludes the leading event-name element so callers index args from 0.
|
|
rawArgs = allElements.Length > 1 ? allElements[1..] : Array.Empty<JsonElement>();
|
|
}
|
|
else
|
|
{
|
|
rawArgs = allElements;
|
|
}
|
|
|
|
return new SocketIoFrame(type, ackId, attachmentCount, eventName, rawArgs, Array.Empty<byte[]>());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Return a new frame with the given binary attachments attached. Throws if the count doesn't
|
|
/// match the header's declared attachment count.
|
|
/// </summary>
|
|
public SocketIoFrame WithAttachments(IReadOnlyList<byte[]> attachments)
|
|
{
|
|
if (attachments.Count != AttachmentCount)
|
|
throw new ArgumentException(
|
|
$"Attachment count mismatch: header says {AttachmentCount}, got {attachments.Count}");
|
|
return new SocketIoFrame(Type, AckId, AttachmentCount, EventName, RawArgs, attachments);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Build a binary event frame for the given event name + binary attachments.
|
|
/// The JSON args become <c>[eventName, {_placeholder:true,num:0}, {_placeholder:true,num:1}, ...]</c>.
|
|
/// </summary>
|
|
public static SocketIoFrame BinaryEventWithAttachments(string eventName, IReadOnlyList<byte[]> attachments)
|
|
{
|
|
// Build the placeholder-only portion (without the event name) — event name is stored separately.
|
|
var sb = new StringBuilder();
|
|
sb.Append('[');
|
|
for (var i = 0; i < attachments.Count; i++)
|
|
{
|
|
if (i > 0) sb.Append(',');
|
|
sb.Append("{\"_placeholder\":true,\"num\":").Append(i).Append('}');
|
|
}
|
|
sb.Append(']');
|
|
JsonElement[] args;
|
|
using (var doc = JsonDocument.Parse(sb.ToString()))
|
|
{
|
|
args = doc.RootElement.EnumerateArray().Select(el => el.Clone()).ToArray();
|
|
}
|
|
|
|
return new SocketIoFrame(
|
|
SocketIoPacketType.BinaryEvent,
|
|
ackId: null,
|
|
attachmentCount: attachments.Count,
|
|
eventName: eventName,
|
|
rawArgs: args,
|
|
binaryAttachments: attachments);
|
|
}
|
|
|
|
/// <summary>Build an ack response with a single int argument (the spec's pubSeq echo).</summary>
|
|
public static SocketIoFrame AckResponse(int ackId, int arg)
|
|
{
|
|
JsonElement[] args;
|
|
using (var doc = JsonDocument.Parse($"[{arg}]"))
|
|
{
|
|
args = doc.RootElement.EnumerateArray().Select(el => el.Clone()).ToArray();
|
|
}
|
|
return new SocketIoFrame(
|
|
SocketIoPacketType.Ack, ackId, 0, null, args, Array.Empty<byte[]>());
|
|
}
|
|
|
|
/// <summary>
|
|
/// Encode to the wire form: (text payload, ordered list of binary attachments).
|
|
/// The caller is responsible for sending the text frame first then each binary attachment frame.
|
|
/// </summary>
|
|
public (string Text, IReadOnlyList<byte[]> Binaries) Encode()
|
|
{
|
|
var sb = new StringBuilder();
|
|
sb.Append((int)Type);
|
|
if (Type is SocketIoPacketType.BinaryEvent or SocketIoPacketType.BinaryAck)
|
|
{
|
|
sb.Append(AttachmentCount).Append('-');
|
|
}
|
|
if (AckId.HasValue) sb.Append(AckId.Value);
|
|
// Re-serialize args — for event/binary-event types, re-prepend the event name.
|
|
bool hasJsonPayload = EventName is not null || RawArgs.Length > 0;
|
|
if (hasJsonPayload)
|
|
{
|
|
sb.Append('[');
|
|
if (EventName is not null)
|
|
{
|
|
sb.Append(JsonSerializer.Serialize(EventName, SocketIoJsonOptions.EventNameOptions));
|
|
if (RawArgs.Length > 0) sb.Append(',');
|
|
}
|
|
for (var i = 0; i < RawArgs.Length; i++)
|
|
{
|
|
if (i > 0) sb.Append(',');
|
|
sb.Append(RawArgs[i].GetRawText());
|
|
}
|
|
sb.Append(']');
|
|
}
|
|
return (sb.ToString(), BinaryAttachments);
|
|
}
|
|
}
|