perf(net): borrow inbound packet storage
Decode headers, optional fields, fragments, and single-fragment messages directly over pooled datagrams. Copy only fragment state that crosses a datagram lifetime, preserve synchronous dispatch and ACK ordering, and lock the path to the owned decoder with differential and zero-allocation tests.
This commit is contained in:
parent
7211bb1bf7
commit
e928c5dd02
18 changed files with 1329 additions and 66 deletions
|
|
@ -35,16 +35,16 @@ public static class EmoteText
|
|||
string SenderName,
|
||||
string Text);
|
||||
|
||||
public static Parsed? TryParse(byte[] body)
|
||||
public static Parsed? TryParse(ReadOnlySpan<byte> body)
|
||||
{
|
||||
if (body is null || body.Length < 8) return null;
|
||||
if (body.Length < 8) return null;
|
||||
uint opcode = BinaryPrimitives.ReadUInt32LittleEndian(body);
|
||||
if (opcode != Opcode) return null;
|
||||
|
||||
try
|
||||
{
|
||||
int pos = 4;
|
||||
uint senderGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos));
|
||||
uint senderGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.Slice(pos));
|
||||
pos += 4;
|
||||
string senderName = StringReader.ReadString16L(body, ref pos);
|
||||
string text = StringReader.ReadString16L(body, ref pos);
|
||||
|
|
|
|||
|
|
@ -17,7 +17,10 @@ namespace AcDream.Core.Net.Messages;
|
|||
/// Handlers are invoked synchronously on the thread that called
|
||||
/// <see cref="Dispatch"/> — normally the render thread since
|
||||
/// <see cref="WorldSession"/>'s decode path runs there in the current
|
||||
/// architecture. Handlers must not block.
|
||||
/// architecture. Handlers must not block or retain the envelope/payload:
|
||||
/// production payload memory borrows a pooled inbound datagram and expires
|
||||
/// when the synchronous dispatch call returns. Handlers must parse or copy
|
||||
/// any state they need to keep.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed class GameEventDispatcher
|
||||
|
|
@ -86,7 +89,8 @@ public sealed class GameEventDispatcher
|
|||
/// <summary>
|
||||
/// Route an envelope to its handler, or log as unhandled. Exceptions
|
||||
/// inside handlers are swallowed to keep the decode loop alive — a
|
||||
/// malformed event from the server should not crash the client.
|
||||
/// malformed event from the server should not crash the client. The
|
||||
/// handler must not retain <paramref name="envelope"/> or its payload.
|
||||
/// </summary>
|
||||
public void Dispatch(GameEventEnvelope envelope)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -42,16 +42,28 @@ public readonly record struct GameEventEnvelope(
|
|||
/// </summary>
|
||||
public static GameEventEnvelope? TryParse(byte[] body)
|
||||
{
|
||||
if (body is null || body.Length < HeaderSize) return null;
|
||||
ArgumentNullException.ThrowIfNull(body);
|
||||
return TryParseBorrowed(body);
|
||||
}
|
||||
|
||||
uint outer = BinaryPrimitives.ReadUInt32LittleEndian(body);
|
||||
/// <summary>
|
||||
/// Internal receive-path parser. The returned payload borrows
|
||||
/// <paramref name="body"/> and must not escape synchronous dispatch.
|
||||
/// </summary>
|
||||
internal static GameEventEnvelope? TryParseBorrowed(
|
||||
ReadOnlyMemory<byte> body)
|
||||
{
|
||||
if (body.Length < HeaderSize) return null;
|
||||
|
||||
ReadOnlySpan<byte> span = body.Span;
|
||||
uint outer = BinaryPrimitives.ReadUInt32LittleEndian(span);
|
||||
if (outer != Opcode) return null;
|
||||
|
||||
uint guid = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(4));
|
||||
uint sequence = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(8));
|
||||
uint eventType = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(12));
|
||||
uint guid = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(4));
|
||||
uint sequence = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(8));
|
||||
uint eventType = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(12));
|
||||
|
||||
var payload = body.AsMemory(HeaderSize);
|
||||
ReadOnlyMemory<byte> payload = body.Slice(HeaderSize);
|
||||
return new GameEventEnvelope(guid, sequence, (GameEventType)eventType, payload);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,9 +46,9 @@ public static class HearSpeech
|
|||
uint ChatType,
|
||||
bool IsRanged);
|
||||
|
||||
public static Parsed? TryParse(byte[] body)
|
||||
public static Parsed? TryParse(ReadOnlySpan<byte> body)
|
||||
{
|
||||
if (body is null || body.Length < 16) return null;
|
||||
if (body.Length < 16) return null;
|
||||
|
||||
uint opcode = BinaryPrimitives.ReadUInt32LittleEndian(body);
|
||||
bool isRanged;
|
||||
|
|
@ -62,8 +62,8 @@ public static class HearSpeech
|
|||
string text = ReadString16L(body, ref pos);
|
||||
string sender = ReadString16L(body, ref pos);
|
||||
if (body.Length - pos < 8) return null;
|
||||
uint senderGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos)); pos += 4;
|
||||
uint chatType = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos)); pos += 4;
|
||||
uint senderGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.Slice(pos)); pos += 4;
|
||||
uint chatType = BinaryPrimitives.ReadUInt32LittleEndian(body.Slice(pos)); pos += 4;
|
||||
return new Parsed(text, sender, senderGuid, chatType, isRanged);
|
||||
}
|
||||
catch { return null; }
|
||||
|
|
|
|||
|
|
@ -30,9 +30,9 @@ public static class PlayerKilled
|
|||
uint VictimGuid,
|
||||
uint KillerGuid);
|
||||
|
||||
public static Parsed? TryParse(byte[] body)
|
||||
public static Parsed? TryParse(ReadOnlySpan<byte> body)
|
||||
{
|
||||
if (body is null || body.Length < 4) return null;
|
||||
if (body.Length < 4) return null;
|
||||
uint opcode = BinaryPrimitives.ReadUInt32LittleEndian(body);
|
||||
if (opcode != Opcode) return null;
|
||||
|
||||
|
|
@ -41,9 +41,9 @@ public static class PlayerKilled
|
|||
int pos = 4;
|
||||
string deathMessage = StringReader.ReadString16L(body, ref pos);
|
||||
if (body.Length - pos < 8) return null;
|
||||
uint victimGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos));
|
||||
uint victimGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.Slice(pos));
|
||||
pos += 4;
|
||||
uint killerGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos));
|
||||
uint killerGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.Slice(pos));
|
||||
return new Parsed(deathMessage, victimGuid, killerGuid);
|
||||
}
|
||||
catch { return null; }
|
||||
|
|
|
|||
|
|
@ -32,9 +32,9 @@ public static class ServerMessage
|
|||
|
||||
public readonly record struct Parsed(string Message, uint ChatType);
|
||||
|
||||
public static Parsed? TryParse(byte[] body)
|
||||
public static Parsed? TryParse(ReadOnlySpan<byte> body)
|
||||
{
|
||||
if (body is null || body.Length < 8) return null;
|
||||
if (body.Length < 8) return null;
|
||||
uint opcode = BinaryPrimitives.ReadUInt32LittleEndian(body);
|
||||
if (opcode != Opcode) return null;
|
||||
|
||||
|
|
@ -43,7 +43,7 @@ public static class ServerMessage
|
|||
int pos = 4;
|
||||
string message = StringReader.ReadString16L(body, ref pos);
|
||||
if (body.Length - pos < 4) return null;
|
||||
uint chatType = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos));
|
||||
uint chatType = BinaryPrimitives.ReadUInt32LittleEndian(body.Slice(pos));
|
||||
return new Parsed(message, chatType);
|
||||
}
|
||||
catch { return null; }
|
||||
|
|
|
|||
|
|
@ -31,16 +31,16 @@ public static class SoulEmote
|
|||
string SenderName,
|
||||
string Text);
|
||||
|
||||
public static Parsed? TryParse(byte[] body)
|
||||
public static Parsed? TryParse(ReadOnlySpan<byte> body)
|
||||
{
|
||||
if (body is null || body.Length < 8) return null;
|
||||
if (body.Length < 8) return null;
|
||||
uint opcode = BinaryPrimitives.ReadUInt32LittleEndian(body);
|
||||
if (opcode != Opcode) return null;
|
||||
|
||||
try
|
||||
{
|
||||
int pos = 4;
|
||||
uint senderGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.AsSpan(pos));
|
||||
uint senderGuid = BinaryPrimitives.ReadUInt32LittleEndian(body.Slice(pos));
|
||||
pos += 4;
|
||||
string senderName = StringReader.ReadString16L(body, ref pos);
|
||||
string text = StringReader.ReadString16L(body, ref pos);
|
||||
|
|
|
|||
|
|
@ -143,9 +143,9 @@ public static class TurbineChat
|
|||
/// for any structural error (truncation, unknown blob_type, ACE
|
||||
/// id-mismatch in RequestSendToRoomById, malformed UTF-16 string).
|
||||
/// </summary>
|
||||
public static Parsed? TryParse(byte[] body)
|
||||
public static Parsed? TryParse(ReadOnlySpan<byte> body)
|
||||
{
|
||||
if (body is null || body.Length < 4 + HeaderSize) return null;
|
||||
if (body.Length < 4 + HeaderSize) return null;
|
||||
uint opcode = BinaryPrimitives.ReadUInt32LittleEndian(body);
|
||||
if (opcode != Opcode) return null;
|
||||
|
||||
|
|
@ -259,7 +259,7 @@ public static class TurbineChat
|
|||
int remaining = expectedPayload;
|
||||
if (body.Length - pos < remaining) return null;
|
||||
var bytes = new byte[remaining];
|
||||
Array.Copy(body, pos, bytes, 0, remaining);
|
||||
body.Slice(pos, remaining).CopyTo(bytes);
|
||||
pos += remaining;
|
||||
payload = new Payload.Unknown(bytes);
|
||||
break;
|
||||
|
|
@ -403,7 +403,9 @@ public static class TurbineChat
|
|||
/// the high bit of the first byte is set the prefix is two bytes
|
||||
/// (high 7 bits of byte 0 + all 8 bits of byte 1).
|
||||
/// </summary>
|
||||
public static string ReadTurbineString(byte[] data, ref int pos)
|
||||
public static string ReadTurbineString(
|
||||
ReadOnlySpan<byte> data,
|
||||
ref int pos)
|
||||
{
|
||||
if (data.Length - pos < 1) throw new FormatException("turbine str: truncated len");
|
||||
int chars = data[pos];
|
||||
|
|
@ -422,7 +424,8 @@ public static class TurbineChat
|
|||
|
||||
// String.from_utf16 in Rust validates surrogate pairs; .NET's
|
||||
// Encoding.Unicode.GetString matches that semantics.
|
||||
string s = Encoding.Unicode.GetString(data, pos, (int)bytesLen);
|
||||
string s = Encoding.Unicode.GetString(
|
||||
data.Slice(pos, (int)bytesLen));
|
||||
pos += (int)bytesLen;
|
||||
return s;
|
||||
}
|
||||
|
|
@ -463,9 +466,12 @@ public static class TurbineChat
|
|||
// Helpers
|
||||
// ──────────────────────────────────────────────────────────────
|
||||
|
||||
private static uint ReadU32(byte[] data, ref int pos)
|
||||
private static uint ReadU32(
|
||||
ReadOnlySpan<byte> data,
|
||||
ref int pos)
|
||||
{
|
||||
uint v = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(pos, 4));
|
||||
uint v = BinaryPrimitives.ReadUInt32LittleEndian(
|
||||
data.Slice(pos, 4));
|
||||
pos += 4;
|
||||
return v;
|
||||
}
|
||||
|
|
|
|||
74
src/AcDream.Core.Net/Packets/BorrowedPacket.cs
Normal file
74
src/AcDream.Core.Net/Packets/BorrowedPacket.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
namespace AcDream.Core.Net.Packets;
|
||||
|
||||
/// <summary>
|
||||
/// Allocation-free decoded packet view. Every memory member borrows the
|
||||
/// caller's datagram and is valid only while that owner retains the buffer.
|
||||
/// </summary>
|
||||
internal readonly record struct BorrowedPacket(
|
||||
PacketHeader Header,
|
||||
BorrowedOptionalHeader Optional,
|
||||
ReadOnlyMemory<byte> Body,
|
||||
ReadOnlyMemory<byte> FragmentBytes,
|
||||
int FragmentCount)
|
||||
{
|
||||
public BorrowedFragmentEnumerable Fragments =>
|
||||
new(FragmentBytes);
|
||||
}
|
||||
|
||||
internal readonly record struct BorrowedOptionalHeader(
|
||||
uint AckSequence,
|
||||
double TimeSync,
|
||||
float EchoRequestClientTime,
|
||||
uint FlowBytes,
|
||||
ushort FlowInterval,
|
||||
double ConnectRequestServerTime,
|
||||
ulong ConnectRequestCookie,
|
||||
uint ConnectRequestClientId,
|
||||
uint ConnectRequestServerSeed,
|
||||
uint ConnectRequestClientSeed,
|
||||
ReadOnlyMemory<byte> RawBytes,
|
||||
ReadOnlyMemory<byte> RetransmitRequestBytes,
|
||||
int RetransmitRequestCount);
|
||||
|
||||
internal readonly record struct BorrowedPacketDecodeResult(
|
||||
BorrowedPacket Packet,
|
||||
PacketCodec.DecodeError Error)
|
||||
{
|
||||
public bool IsOk => Error == PacketCodec.DecodeError.None;
|
||||
}
|
||||
|
||||
internal readonly record struct BorrowedMessageFragment(
|
||||
MessageFragmentHeader Header,
|
||||
ReadOnlyMemory<byte> Payload);
|
||||
|
||||
internal readonly struct BorrowedFragmentEnumerable(
|
||||
ReadOnlyMemory<byte> encoded)
|
||||
{
|
||||
public Enumerator GetEnumerator() => new(encoded);
|
||||
|
||||
internal struct Enumerator(ReadOnlyMemory<byte> remaining)
|
||||
{
|
||||
private ReadOnlyMemory<byte> _remaining = remaining;
|
||||
|
||||
public BorrowedMessageFragment Current { get; private set; }
|
||||
|
||||
public bool MoveNext()
|
||||
{
|
||||
if (_remaining.IsEmpty)
|
||||
return false;
|
||||
|
||||
if (!MessageFragment.TryParseBorrowed(
|
||||
_remaining,
|
||||
out BorrowedMessageFragment fragment,
|
||||
out int consumed))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"validated packet contained an invalid fragment");
|
||||
}
|
||||
|
||||
Current = fragment;
|
||||
_remaining = _remaining.Slice(consumed);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -95,6 +95,80 @@ public sealed class FragmentAssembler
|
|||
return combined;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Production borrowed-memory path. A complete single-fragment message
|
||||
/// is returned as a view into the current datagram. Multi-fragment
|
||||
/// payloads are copied only because they must survive that datagram's
|
||||
/// pooled lifetime.
|
||||
/// </summary>
|
||||
internal bool TryIngest(
|
||||
in BorrowedMessageFragment fragment,
|
||||
out ReadOnlyMemory<byte> message,
|
||||
out ushort messageQueue)
|
||||
{
|
||||
MessageFragmentHeader header = fragment.Header;
|
||||
message = ReadOnlyMemory<byte>.Empty;
|
||||
messageQueue = 0;
|
||||
|
||||
if (header.Count == 1 && header.Index == 0)
|
||||
{
|
||||
message = fragment.Payload;
|
||||
messageQueue = header.Queue;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!_inFlight.TryGetValue(
|
||||
header.Sequence,
|
||||
out PartialMessage? partial))
|
||||
{
|
||||
partial = new PartialMessage(
|
||||
header.Count,
|
||||
header.Queue);
|
||||
_inFlight[header.Sequence] = partial;
|
||||
}
|
||||
else if (partial.TotalFragments != header.Count
|
||||
|| partial.Queue != header.Queue)
|
||||
{
|
||||
// Same sequence with conflicting identity is malformed. Preserve
|
||||
// the first accepted partial instead of corrupting its layout.
|
||||
return false;
|
||||
}
|
||||
|
||||
if (partial.Fragments[header.Index] is null)
|
||||
{
|
||||
partial.Fragments[header.Index] =
|
||||
fragment.Payload.ToArray();
|
||||
partial.ReceivedCount++;
|
||||
}
|
||||
|
||||
if (partial.ReceivedCount < partial.TotalFragments)
|
||||
return false;
|
||||
|
||||
int totalBytes = 0;
|
||||
for (int index = 0;
|
||||
index < partial.TotalFragments;
|
||||
index++)
|
||||
{
|
||||
totalBytes += partial.Fragments[index]!.Length;
|
||||
}
|
||||
|
||||
var combined = new byte[totalBytes];
|
||||
int offset = 0;
|
||||
for (int index = 0;
|
||||
index < partial.TotalFragments;
|
||||
index++)
|
||||
{
|
||||
byte[] payload = partial.Fragments[index]!;
|
||||
payload.CopyTo(combined, offset);
|
||||
offset += payload.Length;
|
||||
}
|
||||
|
||||
_inFlight.Remove(header.Sequence);
|
||||
message = combined;
|
||||
messageQueue = partial.Queue;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Discard all in-flight partial messages.</summary>
|
||||
public void DropAll() => _inFlight.Clear();
|
||||
|
||||
|
|
|
|||
|
|
@ -20,25 +20,75 @@ public readonly record struct MessageFragment(MessageFragmentHeader Header, byte
|
|||
/// </summary>
|
||||
public static (MessageFragment? fragment, int consumed) TryParse(ReadOnlySpan<byte> source)
|
||||
{
|
||||
if (source.Length < MessageFragmentHeader.Size)
|
||||
if (!TryParseLayout(
|
||||
source,
|
||||
out MessageFragmentHeader header,
|
||||
out int payloadLength,
|
||||
out int consumed))
|
||||
{
|
||||
return (null, 0);
|
||||
}
|
||||
|
||||
var header = MessageFragmentHeader.Unpack(source);
|
||||
byte[] payload = source
|
||||
.Slice(MessageFragmentHeader.Size, payloadLength)
|
||||
.ToArray();
|
||||
return (new MessageFragment(header, payload), consumed);
|
||||
}
|
||||
|
||||
internal static bool TryParseBorrowed(
|
||||
ReadOnlyMemory<byte> source,
|
||||
out BorrowedMessageFragment fragment,
|
||||
out int consumed)
|
||||
{
|
||||
if (!TryParseLayout(
|
||||
source.Span,
|
||||
out MessageFragmentHeader header,
|
||||
out int payloadLength,
|
||||
out consumed))
|
||||
{
|
||||
fragment = default;
|
||||
return false;
|
||||
}
|
||||
|
||||
fragment = new BorrowedMessageFragment(
|
||||
header,
|
||||
source.Slice(
|
||||
MessageFragmentHeader.Size,
|
||||
payloadLength));
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static bool TryParseLayout(
|
||||
ReadOnlySpan<byte> source,
|
||||
out MessageFragmentHeader header,
|
||||
out int payloadLength,
|
||||
out int consumed)
|
||||
{
|
||||
header = default;
|
||||
payloadLength = 0;
|
||||
consumed = 0;
|
||||
if (source.Length < MessageFragmentHeader.Size)
|
||||
return false;
|
||||
|
||||
header = MessageFragmentHeader.Unpack(source);
|
||||
|
||||
// TotalSize is the fragment's own size including its header. Anything
|
||||
// smaller than the header or larger than the max fragment size is
|
||||
// wire corruption and we refuse to parse.
|
||||
if (header.TotalSize < MessageFragmentHeader.Size
|
||||
|| header.TotalSize > MessageFragmentHeader.MaxFragmentSize)
|
||||
|| header.TotalSize > MessageFragmentHeader.MaxFragmentSize
|
||||
|| header.Count == 0
|
||||
|| header.Index >= header.Count)
|
||||
{
|
||||
return (null, 0);
|
||||
return false;
|
||||
}
|
||||
|
||||
int payloadLength = header.TotalSize - MessageFragmentHeader.Size;
|
||||
payloadLength =
|
||||
header.TotalSize - MessageFragmentHeader.Size;
|
||||
if (source.Length < header.TotalSize)
|
||||
return (null, 0);
|
||||
return false;
|
||||
|
||||
var payload = source.Slice(MessageFragmentHeader.Size, payloadLength).ToArray();
|
||||
return (new MessageFragment(header, payload), header.TotalSize);
|
||||
consumed = header.TotalSize;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -115,6 +115,373 @@ public static class PacketCodec
|
|||
return new PacketDecodeResult(packet, DecodeError.None);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decode and verify one packet without materializing packet, optional-
|
||||
/// header, fragment-list, body, or fragment-payload objects. Returned
|
||||
/// memory borrows <paramref name="datagram"/> and must not outlive it.
|
||||
/// </summary>
|
||||
internal static BorrowedPacketDecodeResult TryDecodeBorrowed(
|
||||
ReadOnlyMemory<byte> datagram,
|
||||
IsaacRandom? inboundIsaac)
|
||||
{
|
||||
ReadOnlySpan<byte> wire = datagram.Span;
|
||||
if (wire.Length < PacketHeader.Size)
|
||||
{
|
||||
return new BorrowedPacketDecodeResult(
|
||||
default,
|
||||
DecodeError.TooShort);
|
||||
}
|
||||
|
||||
PacketHeader header = PacketHeader.Unpack(wire);
|
||||
int bodyLength = header.DataSize;
|
||||
if (wire.Length - PacketHeader.Size < bodyLength)
|
||||
{
|
||||
return new BorrowedPacketDecodeResult(
|
||||
default,
|
||||
DecodeError.HeaderSizeExceedsBuffer);
|
||||
}
|
||||
|
||||
ReadOnlyMemory<byte> body = datagram.Slice(
|
||||
PacketHeader.Size,
|
||||
bodyLength);
|
||||
if (!TryParseBorrowedOptional(
|
||||
body,
|
||||
header.Flags,
|
||||
out BorrowedOptionalHeader optional,
|
||||
out int optionalConsumed))
|
||||
{
|
||||
return new BorrowedPacketDecodeResult(
|
||||
default,
|
||||
DecodeError.InvalidOptionalHeader);
|
||||
}
|
||||
|
||||
ReadOnlyMemory<byte> fragmentBytes =
|
||||
ReadOnlyMemory<byte>.Empty;
|
||||
int fragmentCount = 0;
|
||||
uint fragmentHash = 0;
|
||||
if (header.HasFlag(PacketHeaderFlags.BlobFragments))
|
||||
{
|
||||
fragmentBytes = body.Slice(optionalConsumed);
|
||||
ReadOnlySpan<byte> remaining = fragmentBytes.Span;
|
||||
while (!remaining.IsEmpty)
|
||||
{
|
||||
if (!MessageFragment.TryParseLayout(
|
||||
remaining,
|
||||
out _,
|
||||
out int payloadLength,
|
||||
out int consumed))
|
||||
{
|
||||
return new BorrowedPacketDecodeResult(
|
||||
default,
|
||||
DecodeError.InvalidFragment);
|
||||
}
|
||||
|
||||
fragmentHash +=
|
||||
Hash32.Calculate(
|
||||
remaining.Slice(
|
||||
0,
|
||||
MessageFragmentHeader.Size))
|
||||
+ Hash32.Calculate(
|
||||
remaining.Slice(
|
||||
MessageFragmentHeader.Size,
|
||||
payloadLength));
|
||||
fragmentCount++;
|
||||
remaining = remaining.Slice(consumed);
|
||||
}
|
||||
}
|
||||
|
||||
uint headerHash = header.CalculateHeaderHash32();
|
||||
uint optionalHash = Hash32.Calculate(
|
||||
optional.RawBytes.Span);
|
||||
uint payloadHash = optionalHash + fragmentHash;
|
||||
if (header.HasFlag(
|
||||
PacketHeaderFlags.EncryptedChecksum))
|
||||
{
|
||||
if (inboundIsaac is null)
|
||||
{
|
||||
return new BorrowedPacketDecodeResult(
|
||||
default,
|
||||
DecodeError.ChecksumMismatch);
|
||||
}
|
||||
|
||||
uint expectedKey =
|
||||
(header.Checksum - headerHash) ^ payloadHash;
|
||||
uint isaacKey = inboundIsaac.Next();
|
||||
if (expectedKey != isaacKey)
|
||||
{
|
||||
return new BorrowedPacketDecodeResult(
|
||||
default,
|
||||
DecodeError.ChecksumMismatch);
|
||||
}
|
||||
}
|
||||
else if (header.Checksum != headerHash + payloadHash)
|
||||
{
|
||||
return new BorrowedPacketDecodeResult(
|
||||
default,
|
||||
DecodeError.ChecksumMismatch);
|
||||
}
|
||||
|
||||
return new BorrowedPacketDecodeResult(
|
||||
new BorrowedPacket(
|
||||
header,
|
||||
optional,
|
||||
body,
|
||||
fragmentBytes,
|
||||
fragmentCount),
|
||||
DecodeError.None);
|
||||
}
|
||||
|
||||
private static bool TryParseBorrowedOptional(
|
||||
ReadOnlyMemory<byte> bodyMemory,
|
||||
PacketHeaderFlags flags,
|
||||
out BorrowedOptionalHeader optional,
|
||||
out int consumed)
|
||||
{
|
||||
ReadOnlySpan<byte> body = bodyMemory.Span;
|
||||
int position = 0;
|
||||
uint ackSequence = 0;
|
||||
double timeSync = 0;
|
||||
float echoRequestClientTime = 0;
|
||||
uint flowBytes = 0;
|
||||
ushort flowInterval = 0;
|
||||
double connectRequestServerTime = 0;
|
||||
ulong connectRequestCookie = 0;
|
||||
uint connectRequestClientId = 0;
|
||||
uint connectRequestServerSeed = 0;
|
||||
uint connectRequestClientSeed = 0;
|
||||
int retransmitOffset = 0;
|
||||
int retransmitCount = 0;
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.ServerSwitch)
|
||||
&& !Take(body, ref position, 8))
|
||||
{
|
||||
return Invalid(out optional, out consumed);
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.RequestRetransmit))
|
||||
{
|
||||
if (!Take(body, ref position, 4))
|
||||
return Invalid(out optional, out consumed);
|
||||
uint count = System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadUInt32LittleEndian(
|
||||
body.Slice(position - 4));
|
||||
if (count > 1024
|
||||
|| body.Length - position < (int)count * 4)
|
||||
{
|
||||
return Invalid(out optional, out consumed);
|
||||
}
|
||||
|
||||
retransmitOffset = position;
|
||||
retransmitCount = checked((int)count);
|
||||
position += retransmitCount * 4;
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.RejectRetransmit))
|
||||
{
|
||||
if (!Take(body, ref position, 4))
|
||||
return Invalid(out optional, out consumed);
|
||||
uint count = System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadUInt32LittleEndian(
|
||||
body.Slice(position - 4));
|
||||
if (count > 1024
|
||||
|| body.Length - position < (int)count * 4)
|
||||
{
|
||||
return Invalid(out optional, out consumed);
|
||||
}
|
||||
position += checked((int)count * 4);
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.AckSequence))
|
||||
{
|
||||
if (!Take(body, ref position, 4))
|
||||
return Invalid(out optional, out consumed);
|
||||
ackSequence =
|
||||
System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadUInt32LittleEndian(
|
||||
body.Slice(position - 4));
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.LoginRequest))
|
||||
{
|
||||
position = body.Length;
|
||||
optional = BuildOptional(
|
||||
bodyMemory,
|
||||
position,
|
||||
ackSequence,
|
||||
timeSync,
|
||||
echoRequestClientTime,
|
||||
flowBytes,
|
||||
flowInterval,
|
||||
connectRequestServerTime,
|
||||
connectRequestCookie,
|
||||
connectRequestClientId,
|
||||
connectRequestServerSeed,
|
||||
connectRequestClientSeed,
|
||||
retransmitOffset,
|
||||
retransmitCount);
|
||||
consumed = position;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.WorldLoginRequest)
|
||||
&& !Take(body, ref position, 8))
|
||||
{
|
||||
return Invalid(out optional, out consumed);
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.ConnectRequest))
|
||||
{
|
||||
if (body.Length - position < 32)
|
||||
return Invalid(out optional, out consumed);
|
||||
|
||||
connectRequestServerTime =
|
||||
BitConverter.Int64BitsToDouble(
|
||||
System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadInt64LittleEndian(
|
||||
body.Slice(position)));
|
||||
connectRequestCookie =
|
||||
System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadUInt64LittleEndian(
|
||||
body.Slice(position + 8));
|
||||
connectRequestClientId =
|
||||
System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadUInt32LittleEndian(
|
||||
body.Slice(position + 16));
|
||||
connectRequestServerSeed =
|
||||
System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadUInt32LittleEndian(
|
||||
body.Slice(position + 20));
|
||||
connectRequestClientSeed =
|
||||
System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadUInt32LittleEndian(
|
||||
body.Slice(position + 24));
|
||||
position += 32;
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.ConnectResponse)
|
||||
&& !Take(body, ref position, 8))
|
||||
{
|
||||
return Invalid(out optional, out consumed);
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.CICMDCommand)
|
||||
&& !Take(body, ref position, 8))
|
||||
{
|
||||
return Invalid(out optional, out consumed);
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.TimeSync))
|
||||
{
|
||||
if (!Take(body, ref position, 8))
|
||||
return Invalid(out optional, out consumed);
|
||||
timeSync = BitConverter.Int64BitsToDouble(
|
||||
System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadInt64LittleEndian(
|
||||
body.Slice(position - 8)));
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.EchoRequest))
|
||||
{
|
||||
if (!Take(body, ref position, 4))
|
||||
return Invalid(out optional, out consumed);
|
||||
echoRequestClientTime =
|
||||
System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadSingleLittleEndian(
|
||||
body.Slice(position - 4));
|
||||
}
|
||||
|
||||
if (HasFlag(flags, PacketHeaderFlags.Flow))
|
||||
{
|
||||
if (!Take(body, ref position, 6))
|
||||
return Invalid(out optional, out consumed);
|
||||
flowBytes =
|
||||
System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadUInt32LittleEndian(
|
||||
body.Slice(position - 6));
|
||||
flowInterval =
|
||||
System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadUInt16LittleEndian(
|
||||
body.Slice(position - 2));
|
||||
}
|
||||
|
||||
optional = BuildOptional(
|
||||
bodyMemory,
|
||||
position,
|
||||
ackSequence,
|
||||
timeSync,
|
||||
echoRequestClientTime,
|
||||
flowBytes,
|
||||
flowInterval,
|
||||
connectRequestServerTime,
|
||||
connectRequestCookie,
|
||||
connectRequestClientId,
|
||||
connectRequestServerSeed,
|
||||
connectRequestClientSeed,
|
||||
retransmitOffset,
|
||||
retransmitCount);
|
||||
consumed = position;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static BorrowedOptionalHeader BuildOptional(
|
||||
ReadOnlyMemory<byte> body,
|
||||
int consumed,
|
||||
uint ackSequence,
|
||||
double timeSync,
|
||||
float echoRequestClientTime,
|
||||
uint flowBytes,
|
||||
ushort flowInterval,
|
||||
double connectRequestServerTime,
|
||||
ulong connectRequestCookie,
|
||||
uint connectRequestClientId,
|
||||
uint connectRequestServerSeed,
|
||||
uint connectRequestClientSeed,
|
||||
int retransmitOffset,
|
||||
int retransmitCount) =>
|
||||
new(
|
||||
ackSequence,
|
||||
timeSync,
|
||||
echoRequestClientTime,
|
||||
flowBytes,
|
||||
flowInterval,
|
||||
connectRequestServerTime,
|
||||
connectRequestCookie,
|
||||
connectRequestClientId,
|
||||
connectRequestServerSeed,
|
||||
connectRequestClientSeed,
|
||||
body.Slice(0, consumed),
|
||||
retransmitCount == 0
|
||||
? ReadOnlyMemory<byte>.Empty
|
||||
: body.Slice(
|
||||
retransmitOffset,
|
||||
retransmitCount * 4),
|
||||
retransmitCount);
|
||||
|
||||
private static bool Invalid(
|
||||
out BorrowedOptionalHeader optional,
|
||||
out int consumed)
|
||||
{
|
||||
optional = default;
|
||||
consumed = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool HasFlag(
|
||||
PacketHeaderFlags all,
|
||||
PacketHeaderFlags bit) =>
|
||||
(all & bit) != 0;
|
||||
|
||||
private static bool Take(
|
||||
ReadOnlySpan<byte> body,
|
||||
ref int position,
|
||||
int count)
|
||||
{
|
||||
if (body.Length - position < count)
|
||||
return false;
|
||||
position += count;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Assemble a datagram from a header and an optional-section body.
|
||||
/// Computes the checksum (both unencrypted and ISAAC-encrypted forms)
|
||||
|
|
|
|||
|
|
@ -801,8 +801,11 @@ public sealed class WorldSession : IDisposable
|
|||
_net.Send(PacketCodec.Encode(loginHeader, loginPayload, null));
|
||||
|
||||
// Step 2: wait for ConnectRequest
|
||||
Packet? cr = null;
|
||||
while (DateTime.UtcNow < deadline && cr is null)
|
||||
bool connectRequestReceived = false;
|
||||
BorrowedOptionalHeader connectRequest = default;
|
||||
ushort connectRequestIteration = 0;
|
||||
while (DateTime.UtcNow < deadline
|
||||
&& !connectRequestReceived)
|
||||
{
|
||||
PooledInboundDatagram? received =
|
||||
ReceiveBlocking(deadline - DateTime.UtcNow);
|
||||
|
|
@ -812,14 +815,23 @@ public sealed class WorldSession : IDisposable
|
|||
PooledInboundDatagram datagram = received.Value;
|
||||
try
|
||||
{
|
||||
var dec = PacketCodec.TryDecode(
|
||||
datagram.Memory.Span,
|
||||
BorrowedPacketDecodeResult dec =
|
||||
PacketCodec.TryDecodeBorrowed(
|
||||
datagram.Memory,
|
||||
inboundIsaac: null);
|
||||
if (dec.IsOk
|
||||
&& dec.Packet!.Header.HasFlag(
|
||||
&& dec.Packet.Header.HasFlag(
|
||||
PacketHeaderFlags.ConnectRequest))
|
||||
{
|
||||
cr = dec.Packet;
|
||||
connectRequest = dec.Packet.Optional with
|
||||
{
|
||||
RawBytes = ReadOnlyMemory<byte>.Empty,
|
||||
RetransmitRequestBytes =
|
||||
ReadOnlyMemory<byte>.Empty,
|
||||
};
|
||||
connectRequestIteration =
|
||||
dec.Packet.Header.Iteration;
|
||||
connectRequestReceived = true;
|
||||
}
|
||||
}
|
||||
finally
|
||||
|
|
@ -827,10 +839,15 @@ public sealed class WorldSession : IDisposable
|
|||
ReturnInboundDatagram(datagram);
|
||||
}
|
||||
}
|
||||
if (cr is null) { Transition(State.Failed); throw new TimeoutException("ConnectRequest not received"); }
|
||||
if (!connectRequestReceived)
|
||||
{
|
||||
Transition(State.Failed);
|
||||
throw new TimeoutException(
|
||||
"ConnectRequest not received");
|
||||
}
|
||||
|
||||
// Step 3: seed ISAAC, send ConnectResponse to port+1, with 200ms race delay
|
||||
var opt = cr.Optional;
|
||||
BorrowedOptionalHeader opt = connectRequest;
|
||||
|
||||
// Phase G.1: server's initial PortalYearTicks (r12 §1.3) lives
|
||||
// in the ConnectRequest optional section. Publish it to
|
||||
|
|
@ -846,7 +863,7 @@ public sealed class WorldSession : IDisposable
|
|||
// SharedNet::SendOptionalHeader @ 0x00543160 copies this ReceiverData
|
||||
// generation into connection-level control packets, including the
|
||||
// final disconnect. ACE currently emits iteration 1.
|
||||
_sessionIteration = cr.Header.Iteration;
|
||||
_sessionIteration = connectRequestIteration;
|
||||
_transportNegotiated = true;
|
||||
_clientPacketSequence = 2;
|
||||
|
||||
|
|
@ -979,7 +996,7 @@ public sealed class WorldSession : IDisposable
|
|||
{
|
||||
try
|
||||
{
|
||||
ProcessDatagram(datagram.Memory.Span);
|
||||
ProcessDatagram(datagram.Memory);
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -1142,7 +1159,7 @@ public sealed class WorldSession : IDisposable
|
|||
try
|
||||
{
|
||||
ProcessDatagram(
|
||||
datagram.Memory.Span,
|
||||
datagram.Memory,
|
||||
opcodesThisCall);
|
||||
return true;
|
||||
}
|
||||
|
|
@ -1153,11 +1170,14 @@ public sealed class WorldSession : IDisposable
|
|||
}
|
||||
|
||||
private void ProcessDatagram(
|
||||
ReadOnlySpan<byte> bytes,
|
||||
ReadOnlyMemory<byte> bytes,
|
||||
List<uint>? opcodesOut = null,
|
||||
bool dispatchWorldEvents = true)
|
||||
{
|
||||
var dec = PacketCodec.TryDecode(bytes, _inboundIsaac);
|
||||
BorrowedPacketDecodeResult dec =
|
||||
PacketCodec.TryDecodeBorrowed(
|
||||
bytes,
|
||||
_inboundIsaac);
|
||||
if (!dec.IsOk) return;
|
||||
|
||||
// Retail LinkStatusHolder::OnHeartbeat @ 0x004113D0 updates its
|
||||
|
|
@ -1172,7 +1192,7 @@ public sealed class WorldSession : IDisposable
|
|||
// with "Network Timeout" because it sees no acks coming back —
|
||||
// which surfaces in other clients' views as the player rendering
|
||||
// as a stationary purple haze (loading state).
|
||||
var serverHeader = dec.Packet!.Header;
|
||||
PacketHeader serverHeader = dec.Packet.Header;
|
||||
if (serverHeader.Sequence > 0
|
||||
&& (serverHeader.Flags & PacketHeaderFlags.AckSequence) == 0)
|
||||
{
|
||||
|
|
@ -1184,7 +1204,7 @@ public sealed class WorldSession : IDisposable
|
|||
// periodically — no explicit opcode, just the header flag.
|
||||
if ((serverHeader.Flags & PacketHeaderFlags.TimeSync) != 0)
|
||||
{
|
||||
double t = dec.Packet!.Optional.TimeSync;
|
||||
double t = dec.Packet.Optional.TimeSync;
|
||||
if (t > 0)
|
||||
{
|
||||
LastServerTimeTicks = t;
|
||||
|
|
@ -1192,11 +1212,21 @@ public sealed class WorldSession : IDisposable
|
|||
}
|
||||
}
|
||||
|
||||
foreach (var frag in dec.Packet!.Fragments)
|
||||
foreach (BorrowedMessageFragment frag
|
||||
in dec.Packet.Fragments)
|
||||
{
|
||||
var body = _assembler.Ingest(frag, out _);
|
||||
if (body is null || body.Length < 4) continue;
|
||||
uint op = BinaryPrimitives.ReadUInt32LittleEndian(body);
|
||||
if (!_assembler.TryIngest(
|
||||
frag,
|
||||
out ReadOnlyMemory<byte> bodyMemory,
|
||||
out _)
|
||||
|| bodyMemory.Length < 4)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
ReadOnlySpan<byte> body = bodyMemory.Span;
|
||||
uint op = BinaryPrimitives.ReadUInt32LittleEndian(
|
||||
body);
|
||||
opcodesOut?.Add(op);
|
||||
|
||||
// Retail waits for the server's opcode-only CharacterLogOff echo
|
||||
|
|
@ -1335,7 +1365,9 @@ public sealed class WorldSession : IDisposable
|
|||
&& !_setStateHexDumped)
|
||||
{
|
||||
_setStateHexDumped = true;
|
||||
var hex = string.Join(" ", body.Take(Math.Min(body.Length, 32))
|
||||
var hex = string.Join(" ", body
|
||||
.Slice(0, Math.Min(body.Length, 32))
|
||||
.ToArray()
|
||||
.Select(b => b.ToString("X2")));
|
||||
Console.WriteLine($"[setstate-hex] body.len={body.Length} first-{Math.Min(body.Length, 32)}-bytes: {hex}");
|
||||
}
|
||||
|
|
@ -1460,7 +1492,8 @@ public sealed class WorldSession : IDisposable
|
|||
// header (guid + sequence + eventType) and dispatch to the
|
||||
// registered handler for that sub-opcode. Unregistered
|
||||
// types get counted for diagnostic overlays.
|
||||
var env = GameEventEnvelope.TryParse(body);
|
||||
var env = GameEventEnvelope.TryParseBorrowed(
|
||||
bodyMemory);
|
||||
if (env is not null) GameEvents.Dispatch(env.Value);
|
||||
}
|
||||
else if (op == 0xEA60u) // AdminEnvirons — server pushes a fog preset or sound cue
|
||||
|
|
@ -1472,7 +1505,7 @@ public sealed class WorldSession : IDisposable
|
|||
if (body.Length >= 8)
|
||||
{
|
||||
uint envType = System.Buffers.Binary.BinaryPrimitives
|
||||
.ReadUInt32LittleEndian(body.AsSpan(4, 4));
|
||||
.ReadUInt32LittleEndian(body.Slice(4, 4));
|
||||
EnvironChanged?.Invoke(envType);
|
||||
}
|
||||
}
|
||||
|
|
@ -1502,7 +1535,7 @@ public sealed class WorldSession : IDisposable
|
|||
if (body.Length >= 6)
|
||||
{
|
||||
ushort sequence = System.Buffers.Binary.BinaryPrimitives.ReadUInt16LittleEndian(
|
||||
body.AsSpan(4, 2));
|
||||
body.Slice(4, 2));
|
||||
TeleportStarted?.Invoke(sequence);
|
||||
}
|
||||
}
|
||||
|
|
@ -2344,7 +2377,7 @@ public sealed class WorldSession : IDisposable
|
|||
datagram =>
|
||||
{
|
||||
ProcessDatagram(
|
||||
datagram.Memory.Span,
|
||||
datagram.Memory,
|
||||
dispatchWorldEvents: false);
|
||||
return Volatile.Read(ref _characterLogOffConfirmed) != 0;
|
||||
},
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue