* Adding generic HttpServer to OpenMetaverse.Capabilites

* LoginResponseData can now serialize to XmlRpc
* Adding new Simian project, ultra-lightweight simulator for testing and development
* Shuffling OpenMetaverse.Capabilities around a bit in preparation for CAPS server implementation

git-svn-id: http://libopenmetaverse.googlecode.com/svn/trunk@2094 52acb1d6-8a22-11de-b505-999d5b087335
This commit is contained in:
John Hurliman
2008-08-16 02:04:20 +00:00
parent c07826e29a
commit 0bd77baba2
15 changed files with 1643 additions and 61 deletions

273
Programs/Simian/Agent.cs Normal file
View File

@@ -0,0 +1,273 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace Simian
{
public class Agent
{
public UUID AgentID;
public UUID SessionID;
public UUID SecureSessionID;
public uint CircuitCode;
/// <summary>Sequence numbers of packets we've received (for duplicate checking)</summary>
internal Queue<uint> packetArchive = new Queue<uint>();
/// <summary>Packets we have sent that need to be ACKed by the client</summary>
internal Dictionary<uint, Packet> needAcks = new Dictionary<uint, Packet>();
UDPServer udpServer;
IPEndPoint address;
/// <summary>ACKs that are queued up, waiting to be sent to the client</summary>
SortedList<uint, uint> pendingAcks = new SortedList<uint, uint>();
int currentSequence = 0;
Timer ackTimer;
public IPEndPoint Address
{
get { return address; }
set { address = value; }
}
public Agent(UDPServer udpServer, UUID agentID, UUID sessionID, UUID secureSessionID, uint circuitCode)
{
AgentID = agentID;
SessionID = sessionID;
SecureSessionID = secureSessionID;
CircuitCode = circuitCode;
this.udpServer = udpServer;
}
public void Initialize(IPEndPoint address)
{
this.address = address;
ackTimer = new Timer(new TimerCallback(AckTimer_Elapsed), null, Settings.NETWORK_TICK_INTERVAL,
Settings.NETWORK_TICK_INTERVAL);
}
public void SendPacket(Packet packet)
{
SendPacket(packet, true);
}
public void SendPacket(Packet packet, bool setSequence)
{
byte[] buffer;
int bytes;
// Keep track of when this packet was sent out
packet.TickCount = Environment.TickCount;
if (setSequence)
{
// Reset to zero if we've hit the upper sequence number limit
Interlocked.CompareExchange(ref currentSequence, 0, 0xFFFFFF);
// Increment and fetch the current sequence number
uint sequence = (uint)Interlocked.Increment(ref currentSequence);
packet.Header.Sequence = sequence;
if (packet.Header.Reliable)
{
// Add this packet to the list of ACK responses we are waiting on from the client
lock (needAcks)
needAcks[sequence] = packet;
if (packet.Header.Resent)
{
// This packet has already been sent out once, strip any appended ACKs
// off it and reinsert them into the outgoing ACK queue under the
// assumption that this packet will continually be rejected from the
// client or that the appended ACKs are possibly making the delivery fail
if (packet.Header.AckList.Length > 0)
{
Logger.DebugLog(String.Format("Purging ACKs from packet #{0} ({1}) which will be resent.",
packet.Header.Sequence, packet.GetType()));
lock (pendingAcks)
{
foreach (uint ack in packet.Header.AckList)
{
if (!pendingAcks.ContainsKey(ack))
pendingAcks[ack] = ack;
}
}
packet.Header.AppendedAcks = false;
packet.Header.AckList = new uint[0];
}
}
else
{
// This packet is not a resend, check if the conditions are favorable
// to ACK appending
if (packet.Type != PacketType.PacketAck)
{
lock (pendingAcks)
{
if (pendingAcks.Count > 0 &&
pendingAcks.Count < 10)
{
// Append all of the queued up outgoing ACKs to this packet
packet.Header.AckList = new uint[pendingAcks.Count];
for (int i = 0; i < pendingAcks.Count; i++)
packet.Header.AckList[i] = pendingAcks.Values[i];
pendingAcks.Clear();
packet.Header.AppendedAcks = true;
}
}
}
}
}
else if (packet.Header.AckList.Length > 0)
{
// Sanity check for ACKS appended on an unreliable packet, this is bad form
Logger.Log("Sending appended ACKs on an unreliable packet", Helpers.LogLevel.Warning);
}
}
// Serialize the packet
buffer = packet.ToBytes();
bytes = buffer.Length;
//Stats.SentBytes += (ulong)bytes;
//++Stats.SentPackets;
UDPPacketBuffer buf;
// Zerocode if needed
if (packet.Header.Zerocoded)
{
buf = new UDPPacketBuffer(address, true, false);
bytes = Helpers.ZeroEncode(buffer, bytes, buf.Data);
buf.DataLength = bytes;
}
else
{
buf = new UDPPacketBuffer(address, false, false);
buf.Data = buffer;
buf.DataLength = bytes;
}
udpServer.AsyncBeginSend(buf);
}
public void QueueAck(uint ack)
{
// Add this packet to the list of ACKs that need to be sent out
lock (pendingAcks)
pendingAcks[ack] = ack;
// Send out ACKs if we have a lot of them
if (pendingAcks.Count >= 10)
SendAcks();
}
public void ProcessAcks(List<uint> acks)
{
lock (needAcks)
{
foreach (uint ack in acks)
needAcks.Remove(ack);
}
}
public void SendAck(uint ack)
{
PacketAckPacket acks = new PacketAckPacket();
acks.Header.Reliable = false;
acks.Packets = new PacketAckPacket.PacketsBlock[1];
acks.Packets[0] = new PacketAckPacket.PacketsBlock();
acks.Packets[0].ID = ack;
SendPacket(acks, true);
}
void SendAcks()
{
PacketAckPacket acks = null;
lock (pendingAcks)
{
if (pendingAcks.Count > 0)
{
if (pendingAcks.Count > 250)
{
Logger.Log("Too many ACKs queued up!", Helpers.LogLevel.Error);
return;
}
acks = new PacketAckPacket();
acks.Header.Reliable = false;
acks.Packets = new PacketAckPacket.PacketsBlock[pendingAcks.Count];
for (int i = 0; i < pendingAcks.Count; i++)
{
acks.Packets[i] = new PacketAckPacket.PacketsBlock();
acks.Packets[i].ID = pendingAcks.Values[i];
}
pendingAcks.Clear();
}
}
if (acks != null)
SendPacket(acks, true);
}
void ResendUnacked()
{
lock (needAcks)
{
List<uint> dropAck = new List<uint>();
int now = Environment.TickCount;
// Resend packets
foreach (Packet packet in needAcks.Values)
{
if (packet.TickCount != 0 && now - packet.TickCount > 4000)
{
if (packet.ResendCount < 3)
{
Logger.DebugLog(String.Format("Resending packet #{0} ({1}), {2}ms have passed",
packet.Header.Sequence, packet.GetType(), now - packet.TickCount));
packet.TickCount = 0;
packet.Header.Resent = true;
//++Stats.ResentPackets;
++packet.ResendCount;
SendPacket(packet, false);
}
else
{
Logger.Log(String.Format("Dropping packet #{0} ({1}) after {2} failed attempts",
packet.Header.Sequence, packet.GetType(), packet.ResendCount), Helpers.LogLevel.Warning);
dropAck.Add(packet.Header.Sequence);
}
}
}
if (dropAck.Count != 0)
{
foreach (uint seq in dropAck)
needAcks.Remove(seq);
}
}
}
private void AckTimer_Elapsed(object obj)
{
SendAcks();
ResendUnacked();
}
}
}

View File

@@ -0,0 +1,127 @@
using System;
using System.Collections.Generic;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace Simian
{
/// <summary>
/// Registers, unregisters, and fires events generated by incoming packets
/// </summary>
public class PacketEventDictionary
{
/// <summary>
/// Object that is passed to worker threads in the ThreadPool for
/// firing packet callbacks
/// </summary>
private struct PacketCallbackWrapper
{
/// <summary>Callback to fire for this packet</summary>
public UDPServer.PacketCallback Callback;
/// <summary>Reference to the agent that this packet came from</summary>
public Agent Agent;
/// <summary>The packet that needs to be processed</summary>
public Packet Packet;
}
private Dictionary<PacketType, UDPServer.PacketCallback> _EventTable = new Dictionary<PacketType, UDPServer.PacketCallback>();
private WaitCallback _ThreadPoolCallback;
/// <summary>
/// Default constructor
/// </summary>
public PacketEventDictionary()
{
_ThreadPoolCallback = new WaitCallback(ThreadPoolDelegate);
}
/// <summary>
/// Register an event handler
/// </summary>
/// <remarks>Use PacketType.Default to fire this event on every
/// incoming packet</remarks>
/// <param name="packetType">Packet type to register the handler for</param>
/// <param name="eventHandler">Callback to be fired</param>
public void RegisterEvent(PacketType packetType, UDPServer.PacketCallback eventHandler)
{
lock (_EventTable)
{
if (_EventTable.ContainsKey(packetType))
_EventTable[packetType] += eventHandler;
else
_EventTable[packetType] = eventHandler;
}
}
/// <summary>
/// Unregister an event handler
/// </summary>
/// <param name="packetType">Packet type to unregister the handler for</param>
/// <param name="eventHandler">Callback to be unregistered</param>
public void UnregisterEvent(PacketType packetType, UDPServer.PacketCallback eventHandler)
{
lock (_EventTable)
{
if (_EventTable.ContainsKey(packetType) && _EventTable[packetType] != null)
_EventTable[packetType] -= eventHandler;
}
}
/// <summary>
/// Fire the events registered for this packet type asynchronously
/// </summary>
/// <param name="packetType">Incoming packet type</param>
/// <param name="packet">Incoming packet</param>
/// <param name="agent">Agent this packet was received from</param>
internal void BeginRaiseEvent(PacketType packetType, Packet packet, Agent agent)
{
UDPServer.PacketCallback callback;
PacketCallbackWrapper wrapper;
// Default handler first, if one exists
if (_EventTable.TryGetValue(PacketType.Default, out callback))
{
if (callback != null)
{
wrapper.Callback = callback;
wrapper.Packet = packet;
wrapper.Agent = agent;
ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper);
}
}
if (_EventTable.TryGetValue(packetType, out callback))
{
if (callback != null)
{
wrapper.Callback = callback;
wrapper.Packet = packet;
wrapper.Agent = agent;
ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper);
return;
}
}
if (packetType != PacketType.Default && packetType != PacketType.PacketAck)
{
Logger.DebugLog("No handler registered for packet event " + packetType);
}
}
private void ThreadPoolDelegate(Object state)
{
PacketCallbackWrapper wrapper = (PacketCallbackWrapper)state;
try
{
wrapper.Callback(wrapper.Packet, wrapper.Agent);
}
catch (Exception ex)
{
Logger.Log("Async Packet Event Handler: " + ex.ToString(), Helpers.LogLevel.Error);
}
}
}
}

21
Programs/Simian/Main.cs Normal file
View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Simian
{
class MainEntry
{
static void Main(string[] args)
{
Simian simulator = new Simian();
simulator.Start(9000, false);
Console.WriteLine("Simulator is running. Press ENTER to quit");
Console.ReadLine();
simulator.Stop();
}
}
}

View File

@@ -0,0 +1,75 @@
using System;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace Simian
{
public partial class Simian
{
void UseCircuitCodeHandler(Packet packet, Agent agent)
{
RegionHandshakePacket handshake = new RegionHandshakePacket();
handshake.RegionInfo.BillableFactor = 0f;
handshake.RegionInfo.CacheID = UUID.Random();
handshake.RegionInfo.IsEstateManager = false;
handshake.RegionInfo.RegionFlags = 1;
handshake.RegionInfo.SimOwner = UUID.Random();
handshake.RegionInfo.SimAccess = 1;
handshake.RegionInfo.SimName = Utils.StringToBytes("Simian");
handshake.RegionInfo.WaterHeight = 20.0f;
handshake.RegionInfo.TerrainBase0 = UUID.Zero;
handshake.RegionInfo.TerrainBase1 = UUID.Zero;
handshake.RegionInfo.TerrainBase2 = UUID.Zero;
handshake.RegionInfo.TerrainBase3 = UUID.Zero;
handshake.RegionInfo.TerrainDetail0 = UUID.Zero;
handshake.RegionInfo.TerrainDetail1 = UUID.Zero;
handshake.RegionInfo.TerrainDetail2 = UUID.Zero;
handshake.RegionInfo.TerrainDetail3 = UUID.Zero;
handshake.RegionInfo.TerrainHeightRange00 = 0f;
handshake.RegionInfo.TerrainHeightRange01 = 20f;
handshake.RegionInfo.TerrainHeightRange10 = 0f;
handshake.RegionInfo.TerrainHeightRange11 = 20f;
handshake.RegionInfo.TerrainStartHeight00 = 0f;
handshake.RegionInfo.TerrainStartHeight01 = 40f;
handshake.RegionInfo.TerrainStartHeight10 = 0f;
handshake.RegionInfo.TerrainStartHeight11 = 40f;
handshake.RegionInfo2.RegionID = UUID.Random();
agent.SendPacket(handshake);
}
void StartPingCheckHandler(Packet packet, Agent agent)
{
StartPingCheckPacket start = (StartPingCheckPacket)packet;
CompletePingCheckPacket complete = new CompletePingCheckPacket();
complete.Header.Reliable = false;
complete.PingID.PingID = start.PingID.PingID;
agent.SendPacket(complete);
}
void CompleteAgentMovementHandler(Packet packet, Agent agent)
{
uint regionX = 256000;
uint regionY = 256000;
CompleteAgentMovementPacket request = (CompleteAgentMovementPacket)packet;
AgentMovementCompletePacket complete = new AgentMovementCompletePacket();
complete.AgentData.AgentID = agent.AgentID;
complete.AgentData.SessionID = agent.SessionID;
complete.Data.LookAt = Vector3.UnitX;
complete.Data.Position = new Vector3(128f, 128f, 25f);
complete.Data.RegionHandle = Helpers.UIntsToLong(regionX, regionY);
complete.Data.Timestamp = Utils.DateTimeToUnixTime(DateTime.Now);
complete.SimData.ChannelVersion = Utils.StringToBytes("Simian");
agent.SendPacket(complete);
}
void AgentUpdateHandler(Packet packet, Agent agent)
{
}
}
}

281
Programs/Simian/Simian.cs Normal file
View File

@@ -0,0 +1,281 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System.Text;
using System.Xml;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Capabilities;
using OpenMetaverse.Packets;
namespace Simian
{
public partial class Simian
{
HttpServer httpServer;
UDPServer udpServer;
Dictionary<uint, Agent> unassociatedAgents;
int currentCircuitCode;
int tcpPort;
int udpPort;
public Simian()
{
unassociatedAgents = new Dictionary<uint, Agent>();
currentCircuitCode = 0;
}
public void Start(int port, bool ssl)
{
// Put UDP listening on the same port number as the HTTP server for simplicity
tcpPort = port;
udpPort = port;
InitUDPServer(udpPort);
InitHttpServer(tcpPort, ssl);
}
public void Stop()
{
udpServer.Stop();
httpServer.Stop();
}
public bool TryGetUnassociatedAgent(uint circuitCode, out Agent agent)
{
if (unassociatedAgents.TryGetValue(circuitCode, out agent))
{
lock (unassociatedAgents)
unassociatedAgents.Remove(circuitCode);
return true;
}
else
{
return false;
}
}
void InitUDPServer(int port)
{
udpServer = new UDPServer(port, this);
udpServer.RegisterPacketCallback(PacketType.UseCircuitCode, new UDPServer.PacketCallback(UseCircuitCodeHandler));
udpServer.RegisterPacketCallback(PacketType.StartPingCheck, new UDPServer.PacketCallback(StartPingCheckHandler));
udpServer.RegisterPacketCallback(PacketType.CompleteAgentMovement, new UDPServer.PacketCallback(CompleteAgentMovementHandler));
udpServer.RegisterPacketCallback(PacketType.AgentUpdate, new UDPServer.PacketCallback(AgentUpdateHandler));
}
void InitHttpServer(int port, bool ssl)
{
httpServer = new HttpServer(tcpPort, ssl);
// Login webpage HEAD request, used to check if the login webpage is alive
HttpRequestSignature signature = new HttpRequestSignature();
signature.Method = "head";
signature.ContentType = String.Empty;
signature.Path = "/loginpage";
HttpServer.HttpRequestCallback callback = new HttpServer.HttpRequestCallback(LoginWebpageHeadHandler);
HttpServer.HttpRequestHandler handler = new HttpServer.HttpRequestHandler(signature, callback);
httpServer.AddHandler(handler);
// Login webpage GET request, gets the login webpage data (purely aesthetic)
signature.Method = "get";
signature.ContentType = String.Empty;
signature.Path = "/loginpage";
callback = new HttpServer.HttpRequestCallback(LoginWebpageGetHandler);
handler.Signature = signature;
handler.Callback = callback;
httpServer.AddHandler(handler);
// Client XML-RPC login
signature.Method = "post";
signature.ContentType = "text/xml";
signature.Path = "/login";
callback = new HttpServer.HttpRequestCallback(LoginXmlRpcPostHandler);
handler.Signature = signature;
handler.Callback = callback;
httpServer.AddHandler(handler);
// Client LLSD login
signature.Method = "post";
signature.ContentType = "application/xml";
signature.Path = "/login";
callback = new HttpServer.HttpRequestCallback(LoginLLSDPostHandler);
handler.Signature = signature;
handler.Callback = callback;
httpServer.AddHandler(handler);
httpServer.Start();
}
void LoginWebpageHeadHandler(ref HttpListenerContext context)
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.StatusDescription = "OK";
}
void LoginWebpageGetHandler(ref HttpListenerContext context)
{
string pageContent = "<html><head><title>Simian</title></head><body><br/><h1>Welcome to Simian</h1></body></html>";
byte[] pageData = Encoding.UTF8.GetBytes(pageContent);
context.Response.OutputStream.Write(pageData, 0, pageData.Length);
context.Response.Close();
}
void LoginXmlRpcPostHandler(ref HttpListenerContext context)
{
string
firstName = String.Empty,
lastName = String.Empty,
password = String.Empty,
start = String.Empty,
version = String.Empty,
channel = String.Empty;
try
{
// Parse the incoming XML
XmlReader reader = XmlReader.Create(context.Request.InputStream);
reader.ReadStartElement("methodCall");
{
string methodName = reader.ReadElementContentAsString("methodName", String.Empty);
if (methodName == "login_to_simulator")
{
reader.ReadStartElement("params");
reader.ReadStartElement("param");
reader.ReadStartElement("value");
reader.ReadStartElement("struct");
{
while (reader.Name == "member")
{
reader.ReadStartElement("member");
{
string name = reader.ReadElementContentAsString("name", String.Empty);
reader.ReadStartElement("value");
{
switch (name)
{
case "first":
firstName = reader.ReadElementContentAsString("string", String.Empty);
break;
case "last":
lastName = reader.ReadElementContentAsString("string", String.Empty);
break;
case "passwd":
password = reader.ReadElementContentAsString("string", String.Empty);
break;
case "start":
start = reader.ReadElementContentAsString("string", String.Empty);
break;
case "version":
version = reader.ReadElementContentAsString("string", String.Empty);
break;
case "channel":
channel = reader.ReadElementContentAsString("string", String.Empty);
break;
default:
if (reader.Name == "string")
Console.WriteLine(String.Format("Ignore login xml value: name={0}, value={1}", name, reader.ReadInnerXml()));
else
Console.WriteLine(String.Format("Unknown login xml: name={0}, value={1}", name, reader.ReadInnerXml()));
break;
}
}
reader.ReadEndElement();
}
reader.ReadEndElement();
}
}
reader.ReadEndElement();
reader.ReadEndElement();
reader.ReadEndElement();
reader.ReadEndElement();
}
}
reader.ReadEndElement();
reader.Close();
LoginResponseData responseData = HandleLogin(firstName, lastName, password, start, version, channel);
XmlWriter writer = XmlWriter.Create(context.Response.OutputStream);
responseData.ToXmlRpc(writer);
writer.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
void LoginLLSDPostHandler(ref HttpListenerContext context)
{
string body = String.Empty;
using (StreamReader reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding))
{
body = reader.ReadToEnd();
}
Console.WriteLine(body);
}
LoginResponseData HandleLogin(string firstName, string lastName, string password, string start, string version, string channel)
{
uint regionX = 256000;
uint regionY = 256000;
// Setup default login response values
LoginResponseData response;
response.AgentID = UUID.Random();
response.SecureSessionID = UUID.Random();
response.SessionID = UUID.Random();
response.CircuitCode = CreateAgentCircuit(response.AgentID, response.SessionID, response.SecureSessionID);
response.AgentAccess = "M";
response.BuddyList = null;
response.FirstName = firstName;
response.HomeLookAt = Vector3.UnitX;
response.HomePosition = new Vector3(128f, 128f, 25f);
response.HomeRegion = Helpers.UIntsToLong(regionX, regionY);
response.InventoryFolders = null;
response.InventoryRoot = UUID.Random();
response.LastName = lastName;
response.LibraryFolders = null;
response.LibraryOwner = response.AgentID;
response.LibraryRoot = UUID.Random();
response.LookAt = Vector3.UnitX;
response.Message = "Welcome to Simian";
response.Reason = String.Empty;
response.RegionX = regionX;
response.RegionY = regionY;
response.SecondsSinceEpoch = DateTime.Now;
// FIXME: Actually generate a seed capability
response.SeedCapability = String.Format("http://{0}:{1}/seed_caps", IPAddress.Loopback, tcpPort);
response.SimIP = IPAddress.Loopback;
response.SimPort = (ushort)udpPort;
response.StartLocation = "last";
response.Success = true;
return response;
}
uint CreateAgentCircuit(UUID agentID, UUID sessionID, UUID secureSessionID)
{
uint circuitCode = (uint)Interlocked.Increment(ref currentCircuitCode);
Agent agent = new Agent(udpServer, agentID, sessionID, secureSessionID, circuitCode);
// Put this client in the list of clients that have not been associated with an IPEndPoint yet
lock (unassociatedAgents)
unassociatedAgents[circuitCode] = agent;
Logger.Log("Created a circuit for agent " + agentID.ToString(), Helpers.LogLevel.Info);
return circuitCode;
}
}
}

View File

@@ -0,0 +1,220 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Threading;
using OpenMetaverse;
using OpenMetaverse.Packets;
namespace Simian
{
public struct IncomingPacket
{
public Agent Agent;
public Packet Packet;
}
public class UDPServer : UDPBase
{
/// <summary>
/// Coupled with RegisterCallback(), this is triggered whenever a packet
/// of a registered type is received
/// </summary>
public delegate void PacketCallback(Packet packet, Agent agent);
/// <summary>This is only used to fetch unassociated agents, which will
/// be exposed through a login interface at some point</summary>
Simian server;
/// <summary>Handlers for incoming packets</summary>
PacketEventDictionary packetEvents = new PacketEventDictionary();
/// <summary>All of the agents currently connected to this UDP server</summary>
Dictionary<IPEndPoint, Agent> agents = new Dictionary<IPEndPoint, Agent>();
/// <summary>Incoming packets that are awaiting handling</summary>
BlockingQueue<IncomingPacket> packetInbox = new BlockingQueue<IncomingPacket>(Settings.PACKET_INBOX_SIZE);
public UDPServer(int port, Simian server)
: base(port)
{
this.server = server;
Start();
// Start the incoming packet processing thread
Thread incomingThread = new Thread(new ThreadStart(IncomingPacketHandler));
incomingThread.Start();
}
public void RegisterPacketCallback(PacketType type, PacketCallback callback)
{
packetEvents.RegisterEvent(type, callback);
}
protected override void PacketReceived(UDPPacketBuffer buffer)
{
Agent agent = null;
Packet packet = null;
int packetEnd = buffer.DataLength - 1;
// Decoding
try
{
packet = Packet.BuildPacket(buffer.Data, ref packetEnd, buffer.ZeroData);
}
catch (MalformedDataException)
{
Logger.Log(String.Format("Malformed data, cannot parse packet:\n{0}",
Utils.BytesToHexString(buffer.Data, buffer.DataLength, null)), Helpers.LogLevel.Error);
}
// Fail-safe check
if (packet == null)
{
Logger.Log("Couldn't build a message from the incoming data", Helpers.LogLevel.Warning);
return;
}
//Stats.RecvBytes += (ulong)buffer.DataLength;
//++Stats.RecvPackets;
if (packet.Type == PacketType.UseCircuitCode)
{
UseCircuitCodePacket useCircuitCode = (UseCircuitCodePacket)packet;
if (server.TryGetUnassociatedAgent(useCircuitCode.CircuitCode.Code, out agent))
{
agent.Initialize((IPEndPoint)buffer.RemoteEndPoint);
lock (agents)
agents[(IPEndPoint)buffer.RemoteEndPoint] = agent;
Logger.Log("Activated UDP circuit " + useCircuitCode.CircuitCode.Code, Helpers.LogLevel.Info);
//agent.SendAck(useCircuitCode.Header.Sequence);
}
else
{
Logger.Log("Received a UseCircuitCode packet for an unrecognized circuit: " + useCircuitCode.CircuitCode.Code.ToString(),
Helpers.LogLevel.Warning);
return;
}
}
else
{
// Determine which agent this packet came from
if (!agents.TryGetValue((IPEndPoint)buffer.RemoteEndPoint, out agent))
{
Logger.Log("Received UDP packet from an unrecognized source: " + ((IPEndPoint)buffer.RemoteEndPoint).ToString(),
Helpers.LogLevel.Warning);
return;
}
}
// Reliable handling
if (packet.Header.Reliable)
{
// Queue up this sequence number for acknowledgement
agent.QueueAck((uint)packet.Header.Sequence);
//if (packet.Header.Resent) ++Stats.ReceivedResends;
}
// Inbox insertion
IncomingPacket incomingPacket;
incomingPacket.Agent = agent;
incomingPacket.Packet = packet;
// TODO: Prioritize the queue
packetInbox.Enqueue(incomingPacket);
}
protected override void PacketSent(UDPPacketBuffer buffer, int bytesSent)
{
Logger.DebugLog("Sent " + buffer.DataLength + " byte packet");
}
private void IncomingPacketHandler()
{
IncomingPacket incomingPacket = new IncomingPacket();
Packet packet = null;
Agent agent = null;
while (IsRunning)
{
// Reset packet to null for the check below
packet = null;
if (packetInbox.Dequeue(100, ref incomingPacket))
{
packet = incomingPacket.Packet;
agent = incomingPacket.Agent;
if (packet != null)
{
#region ACK accounting
// Check the archives to see whether we already received this packet
lock (agent.packetArchive)
{
if (agent.packetArchive.Contains(packet.Header.Sequence))
{
if (packet.Header.Resent)
{
Logger.DebugLog("Received resent packet #" + packet.Header.Sequence);
}
else
{
Logger.Log(String.Format("Received a duplicate of packet #{0}, current type: {1}",
packet.Header.Sequence, packet.Type), Helpers.LogLevel.Warning);
}
// Avoid firing a callback twice for the same packet
continue;
}
else
{
// Keep the PacketArchive size within a certain capacity
while (agent.packetArchive.Count >= Settings.PACKET_ARCHIVE_SIZE)
{
agent.packetArchive.Dequeue(); agent.packetArchive.Dequeue();
agent.packetArchive.Dequeue(); agent.packetArchive.Dequeue();
}
agent.packetArchive.Enqueue(packet.Header.Sequence);
}
}
#endregion ACK accounting
#region ACK handling
// Handle appended ACKs
if (packet.Header.AppendedAcks)
{
lock (agent.needAcks)
{
for (int i = 0; i < packet.Header.AckList.Length; i++)
agent.needAcks.Remove(packet.Header.AckList[i]);
}
}
// Handle PacketAck packets
if (packet.Type == PacketType.PacketAck)
{
PacketAckPacket ackPacket = (PacketAckPacket)packet;
lock (agent.needAcks)
{
for (int i = 0; i < ackPacket.Packets.Length; i++)
agent.needAcks.Remove(ackPacket.Packets[i].ID);
}
}
#endregion ACK handling
packetEvents.BeginRaiseEvent(packet.Type, packet, agent);
}
}
}
}
}
}