1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Reflection;
- using System.Threading;
- using log4net;
- using Nini.Config;
- using OpenMetaverse.Packets;
- using OpenSim.Framework;
- using OpenSim.Framework.Statistics;
- using OpenSim.Region.Framework.Scenes;
- using OpenMetaverse;
- using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket;
- namespace OpenSim.Region.ClientStack.LindenUDP
- {
-
-
-
- public sealed class LLUDPServerShim : IClientNetworkServer
- {
- LLUDPServer m_udpServer;
- public LLUDPServerShim()
- {
- }
- public void Initialise(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
- {
- m_udpServer = new LLUDPServer(listenIP, ref port, proxyPortOffsetParm, allow_alternate_port, configSource, circuitManager);
- }
- public void NetworkStop()
- {
- m_udpServer.Stop();
- }
- public void AddScene(IScene scene)
- {
- m_udpServer.AddScene(scene);
- }
- public bool HandlesRegion(Location x)
- {
- return m_udpServer.HandlesRegion(x);
- }
- public void Start()
- {
- m_udpServer.Start();
- }
- public void Stop()
- {
- m_udpServer.Stop();
- }
- }
-
-
-
-
- public class LLUDPServer : OpenSimUDPBase
- {
-
- public const int MTU = 1400;
- private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-
- public readonly float TickCountResolution;
-
-
- public readonly int PrimUpdatesPerCallback;
-
-
- public readonly int TextureSendLimit;
-
-
-
- private OpenMetaverse.BlockingQueue<IncomingPacket> packetInbox = new OpenMetaverse.BlockingQueue<IncomingPacket>();
-
-
-
- protected TokenBucket m_throttle;
-
-
- public ThrottleRates ThrottleRates { get; private set; }
-
-
- private AgentCircuitManager m_circuitManager;
-
- protected Scene m_scene;
-
- private Location m_location;
-
-
-
- private int m_recvBufferSize;
-
- private bool m_asyncPacketHandling;
-
-
- private bool m_packetSent;
-
- private int m_elapsedMSSinceLastStatReport = 0;
-
- private int m_tickLastOutgoingPacketHandler;
-
- private int m_elapsedMSOutgoingPacketHandler;
-
- private int m_elapsed100MSOutgoingPacketHandler;
-
- private int m_elapsed500MSOutgoingPacketHandler;
-
- private bool m_resendUnacked;
-
- private bool m_sendAcks;
-
- private bool m_sendPing;
- private int m_defaultRTO = 0;
- private int m_maxRTO = 0;
- private bool m_disableFacelights = false;
- public Socket Server { get { return null; } }
- public LLUDPServer(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
- : base(listenIP, (int)port)
- {
- #region Environment.TickCount Measurement
-
- TickCountResolution = 0f;
- for (int i = 0; i < 5; i++)
- {
- int start = Environment.TickCount;
- int now = start;
- while (now == start)
- now = Environment.TickCount;
- TickCountResolution += (float)(now - start) * 0.2f;
- }
- m_log.Info("[LLUDPSERVER]: Average Environment.TickCount resolution: " + TickCountResolution + "ms");
- TickCountResolution = (float)Math.Ceiling(TickCountResolution);
- #endregion Environment.TickCount Measurement
- m_circuitManager = circuitManager;
- int sceneThrottleBps = 0;
- IConfig config = configSource.Configs["ClientStack.LindenUDP"];
- if (config != null)
- {
- m_asyncPacketHandling = config.GetBoolean("async_packet_handling", true);
- m_recvBufferSize = config.GetInt("client_socket_rcvbuf_size", 0);
- sceneThrottleBps = config.GetInt("scene_throttle_max_bps", 0);
- PrimUpdatesPerCallback = config.GetInt("PrimUpdatesPerCallback", 100);
- TextureSendLimit = config.GetInt("TextureSendLimit", 20);
- m_defaultRTO = config.GetInt("DefaultRTO", 0);
- m_maxRTO = config.GetInt("MaxRTO", 0);
- m_disableFacelights = config.GetBoolean("DisableFacelights", false);
- }
- else
- {
- PrimUpdatesPerCallback = 100;
- TextureSendLimit = 20;
- }
- #region BinaryStats
- config = configSource.Configs["Statistics.Binary"];
- m_shouldCollectStats = false;
- if (config != null)
- {
- if (config.Contains("enabled") && config.GetBoolean("enabled"))
- {
- if (config.Contains("collect_packet_headers"))
- m_shouldCollectStats = config.GetBoolean("collect_packet_headers");
- if (config.Contains("packet_headers_period_seconds"))
- {
- binStatsMaxFilesize = TimeSpan.FromSeconds(config.GetInt("region_stats_period_seconds"));
- }
- if (config.Contains("stats_dir"))
- {
- binStatsDir = config.GetString("stats_dir");
- }
- }
- else
- {
- m_shouldCollectStats = false;
- }
- }
- #endregion BinaryStats
- m_throttle = new TokenBucket(null, sceneThrottleBps, sceneThrottleBps);
- ThrottleRates = new ThrottleRates(configSource);
- }
- public void Start()
- {
- if (m_scene == null)
- throw new InvalidOperationException("[LLUDPSERVER]: Cannot LLUDPServer.Start() without an IScene reference");
- m_log.Info("[LLUDPSERVER]: Starting the LLUDP server in " + (m_asyncPacketHandling ? "asynchronous" : "synchronous") + " mode");
- base.Start(m_recvBufferSize, m_asyncPacketHandling);
-
- Watchdog.StartThread(IncomingPacketHandler, "Incoming Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
- Watchdog.StartThread(OutgoingPacketHandler, "Outgoing Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
- m_elapsedMSSinceLastStatReport = Environment.TickCount;
- }
- public new void Stop()
- {
- m_log.Info("[LLUDPSERVER]: Shutting down the LLUDP server for " + m_scene.RegionInfo.RegionName);
- base.Stop();
- }
- public void AddScene(IScene scene)
- {
- if (m_scene != null)
- {
- m_log.Error("[LLUDPSERVER]: AddScene() called on an LLUDPServer that already has a scene");
- return;
- }
- if (!(scene is Scene))
- {
- m_log.Error("[LLUDPSERVER]: AddScene() called with an unrecognized scene type " + scene.GetType());
- return;
- }
- m_scene = (Scene)scene;
- m_location = new Location(m_scene.RegionInfo.RegionHandle);
- }
- public bool HandlesRegion(Location x)
- {
- return x == m_location;
- }
- public void BroadcastPacket(Packet packet, ThrottleOutPacketType category, bool sendToPausedAgents, bool allowSplitting)
- {
-
- if ((packet.Type == PacketType.CoarseLocationUpdate || packet.Type == PacketType.AvatarGroupsReply) && allowSplitting)
- allowSplitting = false;
- if (allowSplitting && packet.HasVariableBlocks)
- {
- byte[][] datas = packet.ToBytesMultiple();
- int packetCount = datas.Length;
- if (packetCount < 1)
- m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
- for (int i = 0; i < packetCount; i++)
- {
- byte[] data = datas[i];
- m_scene.ForEachClient(
- delegate(IClientAPI client)
- {
- if (client is LLClientView)
- SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category);
- }
- );
- }
- }
- else
- {
- byte[] data = packet.ToBytes();
- m_scene.ForEachClient(
- delegate(IClientAPI client)
- {
- if (client is LLClientView)
- SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category);
- }
- );
- }
- }
-
-
-
-
-
-
-
- public void SendPacket(LLUDPClient udpClient, Packet packet, ThrottleOutPacketType category, bool allowSplitting)
- {
-
- if (packet.Type == PacketType.CoarseLocationUpdate && allowSplitting)
- allowSplitting = false;
- if (allowSplitting && packet.HasVariableBlocks)
- {
- byte[][] datas = packet.ToBytesMultiple();
- int packetCount = datas.Length;
- if (packetCount < 1)
- m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
- for (int i = 0; i < packetCount; i++)
- {
- byte[] data = datas[i];
- SendPacketData(udpClient, data, packet.Type, category);
- }
- }
- else
- {
- byte[] data = packet.ToBytes();
- SendPacketData(udpClient, data, packet.Type, category);
- }
- }
-
-
-
-
-
-
-
- public void SendPacketData(LLUDPClient udpClient, byte[] data, PacketType type, ThrottleOutPacketType category)
- {
- int dataLength = data.Length;
- bool doZerocode = (data[0] & Helpers.MSG_ZEROCODED) != 0;
- bool doCopy = true;
-
-
-
-
- int bufferSize = (dataLength > 180) ? LLUDPServer.MTU : 200;
- UDPPacketBuffer buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
-
- if (doZerocode)
- {
- try
- {
- dataLength = Helpers.ZeroEncode(data, dataLength, buffer.Data);
- doCopy = false;
- }
- catch (IndexOutOfRangeException)
- {
-
-
-
- m_log.Debug("[LLUDPSERVER]: Packet exceeded buffer size during zerocoding for " + type + ". DataLength=" + dataLength +
- " and BufferLength=" + buffer.Data.Length + ". Removing MSG_ZEROCODED flag");
- data[0] = (byte)(data[0] & ~Helpers.MSG_ZEROCODED);
- }
- }
-
- if (doCopy)
- {
- if (dataLength <= buffer.Data.Length)
- {
- Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
- }
- else
- {
- bufferSize = dataLength;
- buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
-
-
- Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
- }
- }
- buffer.DataLength = dataLength;
- #region Queue or Send
- OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category);
-
-
-
- bool requestQueue = type == PacketType.KillObject;
- if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, requestQueue))
- SendPacketFinal(outgoingPacket);
- #endregion Queue or Send
- }
- public void SendAcks(LLUDPClient udpClient)
- {
- uint ack;
- if (udpClient.PendingAcks.Dequeue(out ack))
- {
- List<PacketAckPacket.PacketsBlock> blocks = new List<PacketAckPacket.PacketsBlock>();
- PacketAckPacket.PacketsBlock block = new PacketAckPacket.PacketsBlock();
- block.ID = ack;
- blocks.Add(block);
- while (udpClient.PendingAcks.Dequeue(out ack))
- {
- block = new PacketAckPacket.PacketsBlock();
- block.ID = ack;
- blocks.Add(block);
- }
- PacketAckPacket packet = new PacketAckPacket();
- packet.Header.Reliable = false;
- packet.Packets = blocks.ToArray();
- SendPacket(udpClient, packet, ThrottleOutPacketType.Unknown, true);
- }
- }
- public void SendPing(LLUDPClient udpClient)
- {
- StartPingCheckPacket pc = (StartPingCheckPacket)PacketPool.Instance.GetPacket(PacketType.StartPingCheck);
- pc.Header.Reliable = false;
- pc.PingID.PingID = (byte)udpClient.CurrentPingSequence++;
-
- pc.PingID.OldestUnacked = 0;
- SendPacket(udpClient, pc, ThrottleOutPacketType.Unknown, false);
- }
- public void CompletePing(LLUDPClient udpClient, byte pingID)
- {
- CompletePingCheckPacket completePing = new CompletePingCheckPacket();
- completePing.PingID.PingID = pingID;
- SendPacket(udpClient, completePing, ThrottleOutPacketType.Unknown, false);
- }
- public void ResendUnacked(LLUDPClient udpClient)
- {
- if (!udpClient.IsConnected)
- return;
-
-
- if ((Environment.TickCount & Int32.MaxValue) - udpClient.TickLastPacketReceived > 1000 * 60)
- {
- m_log.Warn("[LLUDPSERVER]: Ack timeout, disconnecting " + udpClient.AgentID);
- RemoveClient(udpClient);
- return;
- }
-
- List<OutgoingPacket> expiredPackets = udpClient.NeedAcks.GetExpiredPackets(udpClient.RTO);
- if (expiredPackets != null)
- {
-
-
- udpClient.BackoffRTO();
-
- for (int i = 0; i < expiredPackets.Count; i++)
- {
- OutgoingPacket outgoingPacket = expiredPackets[i];
-
-
-
- outgoingPacket.Buffer.Data[0] = (byte)(outgoingPacket.Buffer.Data[0] | Helpers.MSG_RESENT);
- outgoingPacket.Category = ThrottleOutPacketType.Resend;
-
- Interlocked.Increment(ref outgoingPacket.ResendCount);
-
-
- if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, false))
- SendPacketFinal(outgoingPacket);
- }
- }
- }
- public void Flush(LLUDPClient udpClient)
- {
-
- }
-
-
-
-
- internal void SendPacketFinal(OutgoingPacket outgoingPacket)
- {
- UDPPacketBuffer buffer = outgoingPacket.Buffer;
- byte flags = buffer.Data[0];
- bool isResend = (flags & Helpers.MSG_RESENT) != 0;
- bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
- bool isZerocoded = (flags & Helpers.MSG_ZEROCODED) != 0;
- LLUDPClient udpClient = outgoingPacket.Client;
- if (!udpClient.IsConnected)
- return;
- #region ACK Appending
- int dataLength = buffer.DataLength;
-
- if (!isZerocoded)
- {
-
-
- uint ackCount = 0;
- uint ack;
- while (dataLength + 5 < buffer.Data.Length && udpClient.PendingAcks.Dequeue(out ack))
- {
- Utils.UIntToBytesBig(ack, buffer.Data, dataLength);
- dataLength += 4;
- ++ackCount;
- }
- if (ackCount > 0)
- {
-
- buffer.Data[dataLength++] = (byte)ackCount;
-
- buffer.Data[0] = (byte)(buffer.Data[0] | Helpers.MSG_APPENDED_ACKS);
- }
- }
- buffer.DataLength = dataLength;
- #endregion ACK Appending
- #region Sequence Number Assignment
- if (!isResend)
- {
-
- uint sequenceNumber = (uint)Interlocked.Increment(ref udpClient.CurrentSequence);
- Utils.UIntToBytesBig(sequenceNumber, buffer.Data, 1);
- outgoingPacket.SequenceNumber = sequenceNumber;
- if (isReliable)
- {
-
- udpClient.NeedAcks.Add(outgoingPacket);
- }
- }
- #endregion Sequence Number Assignment
-
- Interlocked.Increment(ref udpClient.PacketsSent);
-
- AsyncBeginSend(buffer);
-
- outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
- }
- protected override void PacketReceived(UDPPacketBuffer buffer)
- {
-
-
-
- LLUDPClient udpClient = null;
- Packet packet = null;
- int packetEnd = buffer.DataLength - 1;
- IPEndPoint address = (IPEndPoint)buffer.RemoteEndPoint;
- #region Decoding
- try
- {
- packet = Packet.BuildPacket(buffer.Data, ref packetEnd,
-
- ((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0) ? new byte[4096] : null);
- }
- catch (MalformedDataException)
- {
- }
-
- if (packet == null)
- {
- m_log.ErrorFormat("[LLUDPSERVER]: Malformed data, cannot parse {0} byte packet from {1}:",
- buffer.DataLength, buffer.RemoteEndPoint);
- m_log.Error(Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
- return;
- }
- #endregion Decoding
- #region Packet to Client Mapping
-
- if (packet.Type == PacketType.UseCircuitCode)
- {
- object[] array = new object[] { buffer, packet };
- if (m_asyncPacketHandling)
- Util.FireAndForget(HandleUseCircuitCode, array);
- else
- HandleUseCircuitCode(array);
- return;
- }
-
- IClientAPI client;
- if (!m_scene.TryGetClient(address, out client) || !(client is LLClientView))
- {
-
- return;
- }
- udpClient = ((LLClientView)client).UDPClient;
- if (!udpClient.IsConnected)
- return;
- #endregion Packet to Client Mapping
-
- Interlocked.Increment(ref udpClient.PacketsReceived);
- int now = Environment.TickCount & Int32.MaxValue;
- udpClient.TickLastPacketReceived = now;
- #region ACK Receiving
-
- if (packet.Header.AppendedAcks && packet.Header.AckList != null)
- {
- for (int i = 0; i < packet.Header.AckList.Length; i++)
- udpClient.NeedAcks.Remove(packet.Header.AckList[i], now, packet.Header.Resent);
- }
-
- if (packet.Type == PacketType.PacketAck)
- {
- PacketAckPacket ackPacket = (PacketAckPacket)packet;
- for (int i = 0; i < ackPacket.Packets.Length; i++)
- udpClient.NeedAcks.Remove(ackPacket.Packets[i].ID, now, packet.Header.Resent);
-
- return;
- }
- #endregion ACK Receiving
- #region ACK Sending
- if (packet.Header.Reliable)
- {
- udpClient.PendingAcks.Enqueue(packet.Header.Sequence);
-
-
-
-
- int bytesSinceLastACK = Interlocked.Exchange(ref udpClient.BytesSinceLastACK, 0);
- bytesSinceLastACK += buffer.DataLength;
- if (bytesSinceLastACK > LLUDPServer.MTU * 2)
- {
- bytesSinceLastACK -= LLUDPServer.MTU * 2;
- SendAcks(udpClient);
- }
- Interlocked.Add(ref udpClient.BytesSinceLastACK, bytesSinceLastACK);
- }
- #endregion ACK Sending
- #region Incoming Packet Accounting
-
- if (packet.Header.Reliable && !udpClient.PacketArchive.TryEnqueue(packet.Header.Sequence))
- {
- if (packet.Header.Resent)
- m_log.DebugFormat(
- "[LLUDPSERVER]: Received a resend of already processed packet #{0}, type {1} from {2}",
- packet.Header.Sequence, packet.Type, client.Name);
- else
- m_log.WarnFormat(
- "[LLUDPSERVER]: Received a duplicate (not marked as resend) of packet #{0}, type {1} from {2}",
- packet.Header.Sequence, packet.Type, client.Name);
-
- return;
- }
- #endregion Incoming Packet Accounting
- #region BinaryStats
- LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
- #endregion BinaryStats
- #region Ping Check Handling
- if (packet.Type == PacketType.StartPingCheck)
- {
-
- StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
- CompletePing(udpClient, startPing.PingID.PingID);
- if ((Environment.TickCount - m_elapsedMSSinceLastStatReport) >= 3000)
- {
- udpClient.SendPacketStats();
- m_elapsedMSSinceLastStatReport = Environment.TickCount;
- }
- return;
- }
- else if (packet.Type == PacketType.CompletePingCheck)
- {
-
- return;
- }
- #endregion Ping Check Handling
-
- packetInbox.Enqueue(new IncomingPacket(udpClient, packet));
- }
- #region BinaryStats
- public class PacketLogger
- {
- public DateTime StartTime;
- public string Path = null;
- public System.IO.BinaryWriter Log = null;
- }
- public static PacketLogger PacketLog;
- protected static bool m_shouldCollectStats = false;
-
- static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
- static object binStatsLogLock = new object();
- static string binStatsDir = "";
- public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
- {
- if (!m_shouldCollectStats) return;
-
-
- if (incoming)
- flags |= 0x01;
- else
- flags &= 0xFE;
-
- uint type = (uint)packetType;
- type |= (uint)flags << 24;
-
- lock (binStatsLogLock)
- {
- DateTime now = DateTime.Now;
-
- try
- {
- if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
- {
- if (PacketLog != null && PacketLog.Log != null)
- {
- PacketLog.Log.Close();
- }
-
- PacketLog = new PacketLogger();
- PacketLog.StartTime = now;
- PacketLog.Path = (binStatsDir.Length > 0 ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
- + String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
- PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
- }
-
- byte[] output = new byte[18];
- Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
- Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
- Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
- Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);
-
- if (PacketLog != null && PacketLog.Log != null)
- PacketLog.Log.Write(output);
- }
- catch (Exception ex)
- {
- m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
- if (PacketLog.Log != null)
- {
- PacketLog.Log.Close();
- }
- PacketLog = null;
- }
- }
- }
- #endregion BinaryStats
- private void HandleUseCircuitCode(object o)
- {
- DateTime startTime = DateTime.Now;
- object[] array = (object[])o;
- UDPPacketBuffer buffer = (UDPPacketBuffer)array[0];
- UseCircuitCodePacket packet = (UseCircuitCodePacket)array[1];
-
- m_log.DebugFormat("[LLUDPSERVER]: Handling UseCircuitCode request from {0}", buffer.RemoteEndPoint);
- IPEndPoint remoteEndPoint = (IPEndPoint)buffer.RemoteEndPoint;
-
- AddNewClient((UseCircuitCodePacket)packet, remoteEndPoint);
-
- SendAckImmediate(remoteEndPoint, packet.Header.Sequence);
-
- }
- private void SendAckImmediate(IPEndPoint remoteEndpoint, uint sequenceNumber)
- {
- PacketAckPacket ack = new PacketAckPacket();
- ack.Header.Reliable = false;
- ack.Packets = new PacketAckPacket.PacketsBlock[1];
- ack.Packets[0] = new PacketAckPacket.PacketsBlock();
- ack.Packets[0].ID = sequenceNumber;
- byte[] packetData = ack.ToBytes();
- int length = packetData.Length;
- UDPPacketBuffer buffer = new UDPPacketBuffer(remoteEndpoint, length);
- buffer.DataLength = length;
- Buffer.BlockCopy(packetData, 0, buffer.Data, 0, length);
- AsyncBeginSend(buffer);
- }
- private bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, out AuthenticateResponse sessionInfo)
- {
- UUID agentID = useCircuitCode.CircuitCode.ID;
- UUID sessionID = useCircuitCode.CircuitCode.SessionID;
- uint circuitCode = useCircuitCode.CircuitCode.Code;
- sessionInfo = m_circuitManager.AuthenticateSession(sessionID, agentID, circuitCode);
- return sessionInfo.Authorised;
- }
- private void AddNewClient(UseCircuitCodePacket useCircuitCode, IPEndPoint remoteEndPoint)
- {
- UUID agentID = useCircuitCode.CircuitCode.ID;
- UUID sessionID = useCircuitCode.CircuitCode.SessionID;
- uint circuitCode = useCircuitCode.CircuitCode.Code;
- if (m_scene.RegionStatus != RegionStatus.SlaveScene)
- {
- AuthenticateResponse sessionInfo;
- if (IsClientAuthorized(useCircuitCode, out sessionInfo))
- {
- AddClient(circuitCode, agentID, sessionID, remoteEndPoint, sessionInfo);
- }
- else
- {
-
- m_log.WarnFormat(
- "[LLUDPSERVER]: Connection request for client {0} connecting with unnotified circuit code {1} from {2}",
- useCircuitCode.CircuitCode.ID, useCircuitCode.CircuitCode.Code, remoteEndPoint);
- }
- }
- else
- {
-
- m_log.Debug("[LLUDPSERVER]: Slave region " + m_scene.RegionInfo.RegionName + " ignoring UseCircuitCode packet");
- }
- }
- protected virtual void AddClient(uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
- {
-
- LLUDPClient udpClient = new LLUDPClient(this, ThrottleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
- IClientAPI existingClient;
- if (!m_scene.TryGetClient(agentID, out existingClient))
- {
-
- LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);
- client.OnLogout += LogoutHandler;
- client.DisableFacelights = m_disableFacelights;
-
- client.Start();
- }
- else
- {
- m_log.WarnFormat("[LLUDPSERVER]: Ignoring a repeated UseCircuitCode from {0} at {1} for circuit {2}",
- udpClient.AgentID, remoteEndPoint, circuitCode);
- }
- }
- private void RemoveClient(LLUDPClient udpClient)
- {
-
- IClientAPI client;
- if (m_scene.TryGetClient(udpClient.AgentID, out client))
- {
- client.IsLoggingOut = true;
- client.Close();
- }
- }
- private void IncomingPacketHandler()
- {
-
-
- Culture.SetCurrentCulture();
- while (base.IsRunning)
- {
- try
- {
- IncomingPacket incomingPacket = null;
-
-
- if (Util.FireAndForgetCount() < 2)
- {
-
- Thread.Sleep(30);
- }
- if (packetInbox.Dequeue(100, ref incomingPacket))
- ProcessInPacket(incomingPacket);
- }
- catch (Exception ex)
- {
- m_log.Error("[LLUDPSERVER]: Error in the incoming packet handler loop: " + ex.Message, ex);
- }
- Watchdog.UpdateThread();
- }
- if (packetInbox.Count > 0)
- m_log.Warn("[LLUDPSERVER]: IncomingPacketHandler is shutting down, dropping " + packetInbox.Count + " packets");
- packetInbox.Clear();
- Watchdog.RemoveThread();
- }
- private void OutgoingPacketHandler()
- {
-
-
- Culture.SetCurrentCulture();
-
-
- Action<IClientAPI> clientPacketHandler = ClientOutgoingPacketHandler;
- while (base.IsRunning)
- {
- try
- {
- m_packetSent = false;
- #region Update Timers
- m_resendUnacked = false;
- m_sendAcks = false;
- m_sendPing = false;
-
- int thisTick = Environment.TickCount & Int32.MaxValue;
- if (m_tickLastOutgoingPacketHandler > thisTick)
- m_elapsedMSOutgoingPacketHandler += ((Int32.MaxValue - m_tickLastOutgoingPacketHandler) + thisTick);
- else
- m_elapsedMSOutgoingPacketHandler += (thisTick - m_tickLastOutgoingPacketHandler);
- m_tickLastOutgoingPacketHandler = thisTick;
-
- if (m_elapsedMSOutgoingPacketHandler >= 100)
- {
- m_resendUnacked = true;
- m_elapsedMSOutgoingPacketHandler = 0;
- m_elapsed100MSOutgoingPacketHandler += 1;
- }
-
- if (m_elapsed100MSOutgoingPacketHandler >= 5)
- {
- m_sendAcks = true;
- m_elapsed100MSOutgoingPacketHandler = 0;
- m_elapsed500MSOutgoingPacketHandler += 1;
- }
-
- if (m_elapsed500MSOutgoingPacketHandler >= 10)
- {
- m_sendPing = true;
- m_elapsed500MSOutgoingPacketHandler = 0;
- }
- #endregion Update Timers
-
-
- m_scene.ForEachClient(clientPacketHandler);
-
-
- if (!m_packetSent)
- Thread.Sleep((int)TickCountResolution);
- Watchdog.UpdateThread();
- }
- catch (Exception ex)
- {
- m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler loop threw an exception: " + ex.Message, ex);
- }
- }
- Watchdog.RemoveThread();
- }
- private void ClientOutgoingPacketHandler(IClientAPI client)
- {
- try
- {
- if (client is LLClientView)
- {
- LLUDPClient udpClient = ((LLClientView)client).UDPClient;
- if (udpClient.IsConnected)
- {
- if (m_resendUnacked)
- ResendUnacked(udpClient);
- if (m_sendAcks)
- SendAcks(udpClient);
- if (m_sendPing)
- SendPing(udpClient);
-
- if (udpClient.DequeueOutgoing())
- m_packetSent = true;
- }
- }
- }
- catch (Exception ex)
- {
- m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler iteration for " + client.Name +
- " threw an exception: " + ex.Message, ex);
- }
- }
- private void ProcessInPacket(object state)
- {
- IncomingPacket incomingPacket = (IncomingPacket)state;
- Packet packet = incomingPacket.Packet;
- LLUDPClient udpClient = incomingPacket.Client;
- IClientAPI client;
-
- if (packet == null || udpClient == null)
- {
- m_log.WarnFormat("[LLUDPSERVER]: Processing a packet with incomplete state. Packet=\"{0}\", UDPClient=\"{1}\"",
- packet, udpClient);
- }
-
- if (m_scene.TryGetClient(udpClient.AgentID, out client))
- {
- try
- {
-
- client.ProcessInPacket(packet);
- }
- catch (ThreadAbortException)
- {
-
- m_log.Info("[LLUDPSERVER]: Caught a thread abort, shutting down the LLUDP server");
- Stop();
- }
- catch (Exception e)
- {
-
- m_log.ErrorFormat("[LLUDPSERVER]: Client packet handler for {0} for packet {1} threw an exception", udpClient.AgentID, packet.Type);
- m_log.Error(e.Message, e);
- }
- }
- else
- {
- m_log.DebugFormat("[LLUDPSERVER]: Dropping incoming {0} packet for dead client {1}", packet.Type, udpClient.AgentID);
- }
- }
- protected void LogoutHandler(IClientAPI client)
- {
- client.SendLogoutPacket();
- if (client.IsActive)
- RemoveClient(((LLClientView)client).UDPClient);
- }
- }
- }
|