LLUDPServer.cs 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.IO;
  31. using System.Net;
  32. using System.Net.Sockets;
  33. using System.Reflection;
  34. using System.Threading;
  35. using log4net;
  36. using Nini.Config;
  37. using OpenMetaverse.Packets;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Statistics;
  40. using OpenSim.Region.Framework.Scenes;
  41. using OpenMetaverse;
  42. using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket;
  43. namespace OpenSim.Region.ClientStack.LindenUDP
  44. {
  45. /// <summary>
  46. /// A shim around LLUDPServer that implements the IClientNetworkServer interface
  47. /// </summary>
  48. public sealed class LLUDPServerShim : IClientNetworkServer
  49. {
  50. LLUDPServer m_udpServer;
  51. public LLUDPServerShim()
  52. {
  53. }
  54. public void Initialise(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
  55. {
  56. m_udpServer = new LLUDPServer(listenIP, ref port, proxyPortOffsetParm, allow_alternate_port, configSource, circuitManager);
  57. }
  58. public void NetworkStop()
  59. {
  60. m_udpServer.Stop();
  61. }
  62. public void AddScene(IScene scene)
  63. {
  64. m_udpServer.AddScene(scene);
  65. }
  66. public bool HandlesRegion(Location x)
  67. {
  68. return m_udpServer.HandlesRegion(x);
  69. }
  70. public void Start()
  71. {
  72. m_udpServer.Start();
  73. }
  74. public void Stop()
  75. {
  76. m_udpServer.Stop();
  77. }
  78. }
  79. /// <summary>
  80. /// The LLUDP server for a region. This handles incoming and outgoing
  81. /// packets for all UDP connections to the region
  82. /// </summary>
  83. public class LLUDPServer : OpenSimUDPBase
  84. {
  85. /// <summary>Maximum transmission unit, or UDP packet size, for the LLUDP protocol</summary>
  86. public const int MTU = 1400;
  87. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  88. /// <summary>The measured resolution of Environment.TickCount</summary>
  89. public readonly float TickCountResolution;
  90. /// <summary>Number of prim updates to put on the queue each time the
  91. /// OnQueueEmpty event is triggered for updates</summary>
  92. public readonly int PrimUpdatesPerCallback;
  93. /// <summary>Number of texture packets to put on the queue each time the
  94. /// OnQueueEmpty event is triggered for textures</summary>
  95. public readonly int TextureSendLimit;
  96. /// <summary>Handlers for incoming packets</summary>
  97. //PacketEventDictionary packetEvents = new PacketEventDictionary();
  98. /// <summary>Incoming packets that are awaiting handling</summary>
  99. private OpenMetaverse.BlockingQueue<IncomingPacket> packetInbox = new OpenMetaverse.BlockingQueue<IncomingPacket>();
  100. /// <summary></summary>
  101. //private UDPClientCollection m_clients = new UDPClientCollection();
  102. /// <summary>Bandwidth throttle for this UDP server</summary>
  103. protected TokenBucket m_throttle;
  104. /// <summary>Bandwidth throttle rates for this UDP server</summary>
  105. public ThrottleRates ThrottleRates { get; private set; }
  106. /// <summary>Manages authentication for agent circuits</summary>
  107. private AgentCircuitManager m_circuitManager;
  108. /// <summary>Reference to the scene this UDP server is attached to</summary>
  109. protected Scene m_scene;
  110. /// <summary>The X/Y coordinates of the scene this UDP server is attached to</summary>
  111. private Location m_location;
  112. /// <summary>The size of the receive buffer for the UDP socket. This value
  113. /// is passed up to the operating system and used in the system networking
  114. /// stack. Use zero to leave this value as the default</summary>
  115. private int m_recvBufferSize;
  116. /// <summary>Flag to process packets asynchronously or synchronously</summary>
  117. private bool m_asyncPacketHandling;
  118. /// <summary>Tracks whether or not a packet was sent each round so we know
  119. /// whether or not to sleep</summary>
  120. private bool m_packetSent;
  121. /// <summary>Environment.TickCount of the last time that packet stats were reported to the scene</summary>
  122. private int m_elapsedMSSinceLastStatReport = 0;
  123. /// <summary>Environment.TickCount of the last time the outgoing packet handler executed</summary>
  124. private int m_tickLastOutgoingPacketHandler;
  125. /// <summary>Keeps track of the number of elapsed milliseconds since the last time the outgoing packet handler looped</summary>
  126. private int m_elapsedMSOutgoingPacketHandler;
  127. /// <summary>Keeps track of the number of 100 millisecond periods elapsed in the outgoing packet handler executed</summary>
  128. private int m_elapsed100MSOutgoingPacketHandler;
  129. /// <summary>Keeps track of the number of 500 millisecond periods elapsed in the outgoing packet handler executed</summary>
  130. private int m_elapsed500MSOutgoingPacketHandler;
  131. /// <summary>Flag to signal when clients should check for resends</summary>
  132. private bool m_resendUnacked;
  133. /// <summary>Flag to signal when clients should send ACKs</summary>
  134. private bool m_sendAcks;
  135. /// <summary>Flag to signal when clients should send pings</summary>
  136. private bool m_sendPing;
  137. private int m_defaultRTO = 0;
  138. private int m_maxRTO = 0;
  139. private bool m_disableFacelights = false;
  140. public Socket Server { get { return null; } }
  141. public LLUDPServer(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
  142. : base(listenIP, (int)port)
  143. {
  144. #region Environment.TickCount Measurement
  145. // Measure the resolution of Environment.TickCount
  146. TickCountResolution = 0f;
  147. for (int i = 0; i < 5; i++)
  148. {
  149. int start = Environment.TickCount;
  150. int now = start;
  151. while (now == start)
  152. now = Environment.TickCount;
  153. TickCountResolution += (float)(now - start) * 0.2f;
  154. }
  155. m_log.Info("[LLUDPSERVER]: Average Environment.TickCount resolution: " + TickCountResolution + "ms");
  156. TickCountResolution = (float)Math.Ceiling(TickCountResolution);
  157. #endregion Environment.TickCount Measurement
  158. m_circuitManager = circuitManager;
  159. int sceneThrottleBps = 0;
  160. IConfig config = configSource.Configs["ClientStack.LindenUDP"];
  161. if (config != null)
  162. {
  163. m_asyncPacketHandling = config.GetBoolean("async_packet_handling", true);
  164. m_recvBufferSize = config.GetInt("client_socket_rcvbuf_size", 0);
  165. sceneThrottleBps = config.GetInt("scene_throttle_max_bps", 0);
  166. PrimUpdatesPerCallback = config.GetInt("PrimUpdatesPerCallback", 100);
  167. TextureSendLimit = config.GetInt("TextureSendLimit", 20);
  168. m_defaultRTO = config.GetInt("DefaultRTO", 0);
  169. m_maxRTO = config.GetInt("MaxRTO", 0);
  170. m_disableFacelights = config.GetBoolean("DisableFacelights", false);
  171. }
  172. else
  173. {
  174. PrimUpdatesPerCallback = 100;
  175. TextureSendLimit = 20;
  176. }
  177. #region BinaryStats
  178. config = configSource.Configs["Statistics.Binary"];
  179. m_shouldCollectStats = false;
  180. if (config != null)
  181. {
  182. if (config.Contains("enabled") && config.GetBoolean("enabled"))
  183. {
  184. if (config.Contains("collect_packet_headers"))
  185. m_shouldCollectStats = config.GetBoolean("collect_packet_headers");
  186. if (config.Contains("packet_headers_period_seconds"))
  187. {
  188. binStatsMaxFilesize = TimeSpan.FromSeconds(config.GetInt("region_stats_period_seconds"));
  189. }
  190. if (config.Contains("stats_dir"))
  191. {
  192. binStatsDir = config.GetString("stats_dir");
  193. }
  194. }
  195. else
  196. {
  197. m_shouldCollectStats = false;
  198. }
  199. }
  200. #endregion BinaryStats
  201. m_throttle = new TokenBucket(null, sceneThrottleBps);
  202. ThrottleRates = new ThrottleRates(configSource);
  203. }
  204. public void Start()
  205. {
  206. if (m_scene == null)
  207. throw new InvalidOperationException("[LLUDPSERVER]: Cannot LLUDPServer.Start() without an IScene reference");
  208. m_log.Info("[LLUDPSERVER]: Starting the LLUDP server in " + (m_asyncPacketHandling ? "asynchronous" : "synchronous") + " mode");
  209. base.Start(m_recvBufferSize, m_asyncPacketHandling);
  210. // Start the packet processing threads
  211. Watchdog.StartThread(IncomingPacketHandler, "Incoming Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
  212. Watchdog.StartThread(OutgoingPacketHandler, "Outgoing Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
  213. m_elapsedMSSinceLastStatReport = Environment.TickCount;
  214. }
  215. public new void Stop()
  216. {
  217. m_log.Info("[LLUDPSERVER]: Shutting down the LLUDP server for " + m_scene.RegionInfo.RegionName);
  218. base.Stop();
  219. }
  220. public void AddScene(IScene scene)
  221. {
  222. if (m_scene != null)
  223. {
  224. m_log.Error("[LLUDPSERVER]: AddScene() called on an LLUDPServer that already has a scene");
  225. return;
  226. }
  227. if (!(scene is Scene))
  228. {
  229. m_log.Error("[LLUDPSERVER]: AddScene() called with an unrecognized scene type " + scene.GetType());
  230. return;
  231. }
  232. m_scene = (Scene)scene;
  233. m_location = new Location(m_scene.RegionInfo.RegionHandle);
  234. }
  235. public bool HandlesRegion(Location x)
  236. {
  237. return x == m_location;
  238. }
  239. public void BroadcastPacket(Packet packet, ThrottleOutPacketType category, bool sendToPausedAgents, bool allowSplitting)
  240. {
  241. // CoarseLocationUpdate and AvatarGroupsReply packets cannot be split in an automated way
  242. if ((packet.Type == PacketType.CoarseLocationUpdate || packet.Type == PacketType.AvatarGroupsReply) && allowSplitting)
  243. allowSplitting = false;
  244. if (allowSplitting && packet.HasVariableBlocks)
  245. {
  246. byte[][] datas = packet.ToBytesMultiple();
  247. int packetCount = datas.Length;
  248. if (packetCount < 1)
  249. m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
  250. for (int i = 0; i < packetCount; i++)
  251. {
  252. byte[] data = datas[i];
  253. m_scene.ForEachClient(
  254. delegate(IClientAPI client)
  255. {
  256. if (client is LLClientView)
  257. SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category, null);
  258. }
  259. );
  260. }
  261. }
  262. else
  263. {
  264. byte[] data = packet.ToBytes();
  265. m_scene.ForEachClient(
  266. delegate(IClientAPI client)
  267. {
  268. if (client is LLClientView)
  269. SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category, null);
  270. }
  271. );
  272. }
  273. }
  274. /// <summary>
  275. /// Start the process of sending a packet to the client.
  276. /// </summary>
  277. /// <param name="udpClient"></param>
  278. /// <param name="packet"></param>
  279. /// <param name="category"></param>
  280. /// <param name="allowSplitting"></param>
  281. public void SendPacket(LLUDPClient udpClient, Packet packet, ThrottleOutPacketType category, bool allowSplitting, UnackedPacketMethod method)
  282. {
  283. // CoarseLocationUpdate packets cannot be split in an automated way
  284. if (packet.Type == PacketType.CoarseLocationUpdate && allowSplitting)
  285. allowSplitting = false;
  286. if (allowSplitting && packet.HasVariableBlocks)
  287. {
  288. byte[][] datas = packet.ToBytesMultiple();
  289. int packetCount = datas.Length;
  290. if (packetCount < 1)
  291. m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
  292. for (int i = 0; i < packetCount; i++)
  293. {
  294. byte[] data = datas[i];
  295. SendPacketData(udpClient, data, packet.Type, category, method);
  296. }
  297. }
  298. else
  299. {
  300. byte[] data = packet.ToBytes();
  301. SendPacketData(udpClient, data, packet.Type, category, method);
  302. }
  303. }
  304. /// <summary>
  305. /// Start the process of sending a packet to the client.
  306. /// </summary>
  307. /// <param name="udpClient"></param>
  308. /// <param name="data"></param>
  309. /// <param name="type"></param>
  310. /// <param name="category"></param>
  311. public void SendPacketData(LLUDPClient udpClient, byte[] data, PacketType type, ThrottleOutPacketType category, UnackedPacketMethod method)
  312. {
  313. int dataLength = data.Length;
  314. bool doZerocode = (data[0] & Helpers.MSG_ZEROCODED) != 0;
  315. bool doCopy = true;
  316. // Frequency analysis of outgoing packet sizes shows a large clump of packets at each end of the spectrum.
  317. // The vast majority of packets are less than 200 bytes, although due to asset transfers and packet splitting
  318. // there are a decent number of packets in the 1000-1140 byte range. We allocate one of two sizes of data here
  319. // to accomodate for both common scenarios and provide ample room for ACK appending in both
  320. int bufferSize = (dataLength > 180) ? LLUDPServer.MTU : 200;
  321. UDPPacketBuffer buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
  322. // Zerocode if needed
  323. if (doZerocode)
  324. {
  325. try
  326. {
  327. dataLength = Helpers.ZeroEncode(data, dataLength, buffer.Data);
  328. doCopy = false;
  329. }
  330. catch (IndexOutOfRangeException)
  331. {
  332. // The packet grew larger than the bufferSize while zerocoding.
  333. // Remove the MSG_ZEROCODED flag and send the unencoded data
  334. // instead
  335. m_log.Debug("[LLUDPSERVER]: Packet exceeded buffer size during zerocoding for " + type + ". DataLength=" + dataLength +
  336. " and BufferLength=" + buffer.Data.Length + ". Removing MSG_ZEROCODED flag");
  337. data[0] = (byte)(data[0] & ~Helpers.MSG_ZEROCODED);
  338. }
  339. }
  340. // If the packet data wasn't already copied during zerocoding, copy it now
  341. if (doCopy)
  342. {
  343. if (dataLength <= buffer.Data.Length)
  344. {
  345. Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
  346. }
  347. else
  348. {
  349. bufferSize = dataLength;
  350. buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
  351. // m_log.Error("[LLUDPSERVER]: Packet exceeded buffer size! This could be an indication of packet assembly not obeying the MTU. Type=" +
  352. // type + ", DataLength=" + dataLength + ", BufferLength=" + buffer.Data.Length + ". Dropping packet");
  353. Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
  354. }
  355. }
  356. buffer.DataLength = dataLength;
  357. #region Queue or Send
  358. OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category, null);
  359. // If we were not provided a method for handling unacked, use the UDPServer default method
  360. outgoingPacket.UnackedMethod = ((method == null) ? delegate(OutgoingPacket oPacket) { ResendUnacked(oPacket); } : method);
  361. // If a Linden Lab 1.23.5 client receives an update packet after a kill packet for an object, it will
  362. // continue to display the deleted object until relog. Therefore, we need to always queue a kill object
  363. // packet so that it isn't sent before a queued update packet.
  364. bool requestQueue = type == PacketType.KillObject;
  365. if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, requestQueue))
  366. SendPacketFinal(outgoingPacket);
  367. #endregion Queue or Send
  368. }
  369. public void SendAcks(LLUDPClient udpClient)
  370. {
  371. uint ack;
  372. if (udpClient.PendingAcks.Dequeue(out ack))
  373. {
  374. List<PacketAckPacket.PacketsBlock> blocks = new List<PacketAckPacket.PacketsBlock>();
  375. PacketAckPacket.PacketsBlock block = new PacketAckPacket.PacketsBlock();
  376. block.ID = ack;
  377. blocks.Add(block);
  378. while (udpClient.PendingAcks.Dequeue(out ack))
  379. {
  380. block = new PacketAckPacket.PacketsBlock();
  381. block.ID = ack;
  382. blocks.Add(block);
  383. }
  384. PacketAckPacket packet = new PacketAckPacket();
  385. packet.Header.Reliable = false;
  386. packet.Packets = blocks.ToArray();
  387. SendPacket(udpClient, packet, ThrottleOutPacketType.Unknown, true, null);
  388. }
  389. }
  390. public void SendPing(LLUDPClient udpClient)
  391. {
  392. StartPingCheckPacket pc = (StartPingCheckPacket)PacketPool.Instance.GetPacket(PacketType.StartPingCheck);
  393. pc.Header.Reliable = false;
  394. pc.PingID.PingID = (byte)udpClient.CurrentPingSequence++;
  395. // We *could* get OldestUnacked, but it would hurt performance and not provide any benefit
  396. pc.PingID.OldestUnacked = 0;
  397. SendPacket(udpClient, pc, ThrottleOutPacketType.Unknown, false, null);
  398. }
  399. public void CompletePing(LLUDPClient udpClient, byte pingID)
  400. {
  401. CompletePingCheckPacket completePing = new CompletePingCheckPacket();
  402. completePing.PingID.PingID = pingID;
  403. SendPacket(udpClient, completePing, ThrottleOutPacketType.Unknown, false, null);
  404. }
  405. public void HandleUnacked(LLUDPClient udpClient)
  406. {
  407. if (!udpClient.IsConnected)
  408. return;
  409. // Disconnect an agent if no packets are received for some time
  410. //FIXME: Make 60 an .ini setting
  411. if ((Environment.TickCount & Int32.MaxValue) - udpClient.TickLastPacketReceived > 1000 * 60)
  412. {
  413. m_log.Warn("[LLUDPSERVER]: Ack timeout, disconnecting " + udpClient.AgentID);
  414. RemoveClient(udpClient);
  415. return;
  416. }
  417. // Get a list of all of the packets that have been sitting unacked longer than udpClient.RTO
  418. List<OutgoingPacket> expiredPackets = udpClient.NeedAcks.GetExpiredPackets(udpClient.RTO);
  419. if (expiredPackets != null)
  420. {
  421. //m_log.Debug("[LLUDPSERVER]: Handling " + expiredPackets.Count + " packets to " + udpClient.AgentID + ", RTO=" + udpClient.RTO);
  422. // Exponential backoff of the retransmission timeout
  423. udpClient.BackoffRTO();
  424. for (int i = 0; i < expiredPackets.Count; ++i)
  425. expiredPackets[i].UnackedMethod(expiredPackets[i]);
  426. }
  427. }
  428. public void ResendUnacked(OutgoingPacket outgoingPacket)
  429. {
  430. //m_log.DebugFormat("[LLUDPSERVER]: Resending packet #{0} (attempt {1}), {2}ms have passed",
  431. // outgoingPacket.SequenceNumber, outgoingPacket.ResendCount, Environment.TickCount - outgoingPacket.TickCount);
  432. // Set the resent flag
  433. outgoingPacket.Buffer.Data[0] = (byte)(outgoingPacket.Buffer.Data[0] | Helpers.MSG_RESENT);
  434. outgoingPacket.Category = ThrottleOutPacketType.Resend;
  435. // Bump up the resend count on this packet
  436. Interlocked.Increment(ref outgoingPacket.ResendCount);
  437. // Requeue or resend the packet
  438. if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, false))
  439. SendPacketFinal(outgoingPacket);
  440. }
  441. public void Flush(LLUDPClient udpClient)
  442. {
  443. // FIXME: Implement?
  444. }
  445. /// <summary>
  446. /// Actually send a packet to a client.
  447. /// </summary>
  448. /// <param name="outgoingPacket"></param>
  449. internal void SendPacketFinal(OutgoingPacket outgoingPacket)
  450. {
  451. UDPPacketBuffer buffer = outgoingPacket.Buffer;
  452. byte flags = buffer.Data[0];
  453. bool isResend = (flags & Helpers.MSG_RESENT) != 0;
  454. bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
  455. bool isZerocoded = (flags & Helpers.MSG_ZEROCODED) != 0;
  456. LLUDPClient udpClient = outgoingPacket.Client;
  457. if (!udpClient.IsConnected)
  458. return;
  459. #region ACK Appending
  460. int dataLength = buffer.DataLength;
  461. // NOTE: I'm seeing problems with some viewers when ACKs are appended to zerocoded packets so I've disabled that here
  462. if (!isZerocoded)
  463. {
  464. // Keep appending ACKs until there is no room left in the buffer or there are
  465. // no more ACKs to append
  466. uint ackCount = 0;
  467. uint ack;
  468. while (dataLength + 5 < buffer.Data.Length && udpClient.PendingAcks.Dequeue(out ack))
  469. {
  470. Utils.UIntToBytesBig(ack, buffer.Data, dataLength);
  471. dataLength += 4;
  472. ++ackCount;
  473. }
  474. if (ackCount > 0)
  475. {
  476. // Set the last byte of the packet equal to the number of appended ACKs
  477. buffer.Data[dataLength++] = (byte)ackCount;
  478. // Set the appended ACKs flag on this packet
  479. buffer.Data[0] = (byte)(buffer.Data[0] | Helpers.MSG_APPENDED_ACKS);
  480. }
  481. }
  482. buffer.DataLength = dataLength;
  483. #endregion ACK Appending
  484. #region Sequence Number Assignment
  485. if (!isResend)
  486. {
  487. // Not a resend, assign a new sequence number
  488. uint sequenceNumber = (uint)Interlocked.Increment(ref udpClient.CurrentSequence);
  489. Utils.UIntToBytesBig(sequenceNumber, buffer.Data, 1);
  490. outgoingPacket.SequenceNumber = sequenceNumber;
  491. if (isReliable)
  492. {
  493. // Add this packet to the list of ACK responses we are waiting on from the server
  494. udpClient.NeedAcks.Add(outgoingPacket);
  495. }
  496. }
  497. else
  498. {
  499. Interlocked.Increment(ref udpClient.PacketsResent);
  500. }
  501. #endregion Sequence Number Assignment
  502. // Stats tracking
  503. Interlocked.Increment(ref udpClient.PacketsSent);
  504. // Put the UDP payload on the wire
  505. AsyncBeginSend(buffer);
  506. // Keep track of when this packet was sent out (right now)
  507. outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
  508. }
  509. protected override void PacketReceived(UDPPacketBuffer buffer)
  510. {
  511. // Debugging/Profiling
  512. //try { Thread.CurrentThread.Name = "PacketReceived (" + m_scene.RegionInfo.RegionName + ")"; }
  513. //catch (Exception) { }
  514. LLUDPClient udpClient = null;
  515. Packet packet = null;
  516. int packetEnd = buffer.DataLength - 1;
  517. IPEndPoint address = (IPEndPoint)buffer.RemoteEndPoint;
  518. #region Decoding
  519. try
  520. {
  521. packet = Packet.BuildPacket(buffer.Data, ref packetEnd,
  522. // Only allocate a buffer for zerodecoding if the packet is zerocoded
  523. ((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0) ? new byte[4096] : null);
  524. }
  525. catch (MalformedDataException)
  526. {
  527. }
  528. // Fail-safe check
  529. if (packet == null)
  530. {
  531. m_log.ErrorFormat("[LLUDPSERVER]: Malformed data, cannot parse {0} byte packet from {1}:",
  532. buffer.DataLength, buffer.RemoteEndPoint);
  533. m_log.Error(Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
  534. return;
  535. }
  536. #endregion Decoding
  537. #region Packet to Client Mapping
  538. // UseCircuitCode handling
  539. if (packet.Type == PacketType.UseCircuitCode)
  540. {
  541. object[] array = new object[] { buffer, packet };
  542. Util.FireAndForget(HandleUseCircuitCode, array);
  543. return;
  544. }
  545. // Determine which agent this packet came from
  546. IClientAPI client;
  547. if (!m_scene.TryGetClient(address, out client) || !(client is LLClientView))
  548. {
  549. //m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet from an unrecognized source: " + address + " in " + m_scene.RegionInfo.RegionName);
  550. return;
  551. }
  552. udpClient = ((LLClientView)client).UDPClient;
  553. if (!udpClient.IsConnected)
  554. return;
  555. #endregion Packet to Client Mapping
  556. // Stats tracking
  557. Interlocked.Increment(ref udpClient.PacketsReceived);
  558. int now = Environment.TickCount & Int32.MaxValue;
  559. udpClient.TickLastPacketReceived = now;
  560. #region ACK Receiving
  561. // Handle appended ACKs
  562. if (packet.Header.AppendedAcks && packet.Header.AckList != null)
  563. {
  564. for (int i = 0; i < packet.Header.AckList.Length; i++)
  565. udpClient.NeedAcks.Acknowledge(packet.Header.AckList[i], now, packet.Header.Resent);
  566. }
  567. // Handle PacketAck packets
  568. if (packet.Type == PacketType.PacketAck)
  569. {
  570. PacketAckPacket ackPacket = (PacketAckPacket)packet;
  571. for (int i = 0; i < ackPacket.Packets.Length; i++)
  572. udpClient.NeedAcks.Acknowledge(ackPacket.Packets[i].ID, now, packet.Header.Resent);
  573. // We don't need to do anything else with PacketAck packets
  574. return;
  575. }
  576. #endregion ACK Receiving
  577. #region ACK Sending
  578. if (packet.Header.Reliable)
  579. {
  580. udpClient.PendingAcks.Enqueue(packet.Header.Sequence);
  581. // This is a somewhat odd sequence of steps to pull the client.BytesSinceLastACK value out,
  582. // add the current received bytes to it, test if 2*MTU bytes have been sent, if so remove
  583. // 2*MTU bytes from the value and send ACKs, and finally add the local value back to
  584. // client.BytesSinceLastACK. Lockless thread safety
  585. int bytesSinceLastACK = Interlocked.Exchange(ref udpClient.BytesSinceLastACK, 0);
  586. bytesSinceLastACK += buffer.DataLength;
  587. if (bytesSinceLastACK > LLUDPServer.MTU * 2)
  588. {
  589. bytesSinceLastACK -= LLUDPServer.MTU * 2;
  590. SendAcks(udpClient);
  591. }
  592. Interlocked.Add(ref udpClient.BytesSinceLastACK, bytesSinceLastACK);
  593. }
  594. #endregion ACK Sending
  595. #region Incoming Packet Accounting
  596. // Check the archive of received reliable packet IDs to see whether we already received this packet
  597. if (packet.Header.Reliable && !udpClient.PacketArchive.TryEnqueue(packet.Header.Sequence))
  598. {
  599. if (packet.Header.Resent)
  600. m_log.DebugFormat(
  601. "[LLUDPSERVER]: Received a resend of already processed packet #{0}, type {1} from {2}",
  602. packet.Header.Sequence, packet.Type, client.Name);
  603. else
  604. m_log.WarnFormat(
  605. "[LLUDPSERVER]: Received a duplicate (not marked as resend) of packet #{0}, type {1} from {2}",
  606. packet.Header.Sequence, packet.Type, client.Name);
  607. // Avoid firing a callback twice for the same packet
  608. return;
  609. }
  610. #endregion Incoming Packet Accounting
  611. #region BinaryStats
  612. LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
  613. #endregion BinaryStats
  614. #region Ping Check Handling
  615. if (packet.Type == PacketType.StartPingCheck)
  616. {
  617. // We don't need to do anything else with ping checks
  618. StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
  619. CompletePing(udpClient, startPing.PingID.PingID);
  620. if ((Environment.TickCount - m_elapsedMSSinceLastStatReport) >= 3000)
  621. {
  622. udpClient.SendPacketStats();
  623. m_elapsedMSSinceLastStatReport = Environment.TickCount;
  624. }
  625. return;
  626. }
  627. else if (packet.Type == PacketType.CompletePingCheck)
  628. {
  629. // We don't currently track client ping times
  630. return;
  631. }
  632. #endregion Ping Check Handling
  633. // Inbox insertion
  634. packetInbox.Enqueue(new IncomingPacket(udpClient, packet));
  635. }
  636. #region BinaryStats
  637. public class PacketLogger
  638. {
  639. public DateTime StartTime;
  640. public string Path = null;
  641. public System.IO.BinaryWriter Log = null;
  642. }
  643. public static PacketLogger PacketLog;
  644. protected static bool m_shouldCollectStats = false;
  645. // Number of seconds to log for
  646. static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
  647. static object binStatsLogLock = new object();
  648. static string binStatsDir = "";
  649. public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
  650. {
  651. if (!m_shouldCollectStats) return;
  652. // Binary logging format is TTTTTTTTCCCCFPPPSS, T=Time, C=Circuit, F=Flags, P=PacketType, S=size
  653. // Put the incoming bit into the least significant bit of the flags byte
  654. if (incoming)
  655. flags |= 0x01;
  656. else
  657. flags &= 0xFE;
  658. // Put the flags byte into the most significant bits of the type integer
  659. uint type = (uint)packetType;
  660. type |= (uint)flags << 24;
  661. // m_log.Debug("1 LogPacketHeader(): Outside lock");
  662. lock (binStatsLogLock)
  663. {
  664. DateTime now = DateTime.Now;
  665. // m_log.Debug("2 LogPacketHeader(): Inside lock. now is " + now.Ticks);
  666. try
  667. {
  668. if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
  669. {
  670. if (PacketLog != null && PacketLog.Log != null)
  671. {
  672. PacketLog.Log.Close();
  673. }
  674. // First log file or time has expired, start writing to a new log file
  675. PacketLog = new PacketLogger();
  676. PacketLog.StartTime = now;
  677. PacketLog.Path = (binStatsDir.Length > 0 ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
  678. + String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
  679. PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
  680. }
  681. // Serialize the data
  682. byte[] output = new byte[18];
  683. Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
  684. Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
  685. Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
  686. Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);
  687. // Write the serialized data to disk
  688. if (PacketLog != null && PacketLog.Log != null)
  689. PacketLog.Log.Write(output);
  690. }
  691. catch (Exception ex)
  692. {
  693. m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
  694. if (PacketLog.Log != null)
  695. {
  696. PacketLog.Log.Close();
  697. }
  698. PacketLog = null;
  699. }
  700. }
  701. }
  702. #endregion BinaryStats
  703. private void HandleUseCircuitCode(object o)
  704. {
  705. // DateTime startTime = DateTime.Now;
  706. object[] array = (object[])o;
  707. UDPPacketBuffer buffer = (UDPPacketBuffer)array[0];
  708. UseCircuitCodePacket packet = (UseCircuitCodePacket)array[1];
  709. m_log.DebugFormat("[LLUDPSERVER]: Handling UseCircuitCode request from {0}", buffer.RemoteEndPoint);
  710. IPEndPoint remoteEndPoint = (IPEndPoint)buffer.RemoteEndPoint;
  711. // Begin the process of adding the client to the simulator
  712. AddNewClient((UseCircuitCodePacket)packet, remoteEndPoint);
  713. // Send ack
  714. SendAckImmediate(remoteEndPoint, packet.Header.Sequence);
  715. // m_log.DebugFormat(
  716. // "[LLUDPSERVER]: Handling UseCircuitCode request from {0} took {1}ms",
  717. // buffer.RemoteEndPoint, (DateTime.Now - startTime).Milliseconds);
  718. }
  719. private void SendAckImmediate(IPEndPoint remoteEndpoint, uint sequenceNumber)
  720. {
  721. PacketAckPacket ack = new PacketAckPacket();
  722. ack.Header.Reliable = false;
  723. ack.Packets = new PacketAckPacket.PacketsBlock[1];
  724. ack.Packets[0] = new PacketAckPacket.PacketsBlock();
  725. ack.Packets[0].ID = sequenceNumber;
  726. byte[] packetData = ack.ToBytes();
  727. int length = packetData.Length;
  728. UDPPacketBuffer buffer = new UDPPacketBuffer(remoteEndpoint, length);
  729. buffer.DataLength = length;
  730. Buffer.BlockCopy(packetData, 0, buffer.Data, 0, length);
  731. AsyncBeginSend(buffer);
  732. }
  733. private bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, out AuthenticateResponse sessionInfo)
  734. {
  735. UUID agentID = useCircuitCode.CircuitCode.ID;
  736. UUID sessionID = useCircuitCode.CircuitCode.SessionID;
  737. uint circuitCode = useCircuitCode.CircuitCode.Code;
  738. sessionInfo = m_circuitManager.AuthenticateSession(sessionID, agentID, circuitCode);
  739. return sessionInfo.Authorised;
  740. }
  741. private void AddNewClient(UseCircuitCodePacket useCircuitCode, IPEndPoint remoteEndPoint)
  742. {
  743. UUID agentID = useCircuitCode.CircuitCode.ID;
  744. UUID sessionID = useCircuitCode.CircuitCode.SessionID;
  745. uint circuitCode = useCircuitCode.CircuitCode.Code;
  746. if (m_scene.RegionStatus != RegionStatus.SlaveScene)
  747. {
  748. AuthenticateResponse sessionInfo;
  749. if (IsClientAuthorized(useCircuitCode, out sessionInfo))
  750. {
  751. AddClient(circuitCode, agentID, sessionID, remoteEndPoint, sessionInfo);
  752. }
  753. else
  754. {
  755. // Don't create circuits for unauthorized clients
  756. m_log.WarnFormat(
  757. "[LLUDPSERVER]: Connection request for client {0} connecting with unnotified circuit code {1} from {2}",
  758. useCircuitCode.CircuitCode.ID, useCircuitCode.CircuitCode.Code, remoteEndPoint);
  759. }
  760. }
  761. else
  762. {
  763. // Slave regions don't accept new clients
  764. m_log.Debug("[LLUDPSERVER]: Slave region " + m_scene.RegionInfo.RegionName + " ignoring UseCircuitCode packet");
  765. }
  766. }
  767. protected virtual void AddClient(uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
  768. {
  769. // In priciple there shouldn't be more than one thread here, ever.
  770. // But in case that happens, we need to synchronize this piece of code
  771. // because it's too important
  772. lock (this)
  773. {
  774. IClientAPI existingClient;
  775. if (!m_scene.TryGetClient(agentID, out existingClient))
  776. {
  777. // Create the LLUDPClient
  778. LLUDPClient udpClient = new LLUDPClient(this, ThrottleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
  779. // Create the LLClientView
  780. LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);
  781. client.OnLogout += LogoutHandler;
  782. client.DisableFacelights = m_disableFacelights;
  783. // Start the IClientAPI
  784. client.Start();
  785. }
  786. else
  787. {
  788. m_log.WarnFormat("[LLUDPSERVER]: Ignoring a repeated UseCircuitCode from {0} at {1} for circuit {2}",
  789. existingClient.AgentId, remoteEndPoint, circuitCode);
  790. }
  791. }
  792. }
  793. private void RemoveClient(LLUDPClient udpClient)
  794. {
  795. // Remove this client from the scene
  796. IClientAPI client;
  797. if (m_scene.TryGetClient(udpClient.AgentID, out client))
  798. {
  799. client.IsLoggingOut = true;
  800. client.Close();
  801. }
  802. }
  803. private void IncomingPacketHandler()
  804. {
  805. // Set this culture for the thread that incoming packets are received
  806. // on to en-US to avoid number parsing issues
  807. Culture.SetCurrentCulture();
  808. while (base.IsRunning)
  809. {
  810. try
  811. {
  812. IncomingPacket incomingPacket = null;
  813. // HACK: This is a test to try and rate limit packet handling on Mono.
  814. // If it works, a more elegant solution can be devised
  815. if (Util.FireAndForgetCount() < 2)
  816. {
  817. //m_log.Debug("[LLUDPSERVER]: Incoming packet handler is sleeping");
  818. Thread.Sleep(30);
  819. }
  820. if (packetInbox.Dequeue(100, ref incomingPacket))
  821. ProcessInPacket(incomingPacket);//, incomingPacket); Util.FireAndForget(ProcessInPacket, incomingPacket);
  822. }
  823. catch (Exception ex)
  824. {
  825. m_log.Error("[LLUDPSERVER]: Error in the incoming packet handler loop: " + ex.Message, ex);
  826. }
  827. Watchdog.UpdateThread();
  828. }
  829. if (packetInbox.Count > 0)
  830. m_log.Warn("[LLUDPSERVER]: IncomingPacketHandler is shutting down, dropping " + packetInbox.Count + " packets");
  831. packetInbox.Clear();
  832. Watchdog.RemoveThread();
  833. }
  834. private void OutgoingPacketHandler()
  835. {
  836. // Set this culture for the thread that outgoing packets are sent
  837. // on to en-US to avoid number parsing issues
  838. Culture.SetCurrentCulture();
  839. // Typecast the function to an Action<IClientAPI> once here to avoid allocating a new
  840. // Action generic every round
  841. Action<IClientAPI> clientPacketHandler = ClientOutgoingPacketHandler;
  842. while (base.IsRunning)
  843. {
  844. try
  845. {
  846. m_packetSent = false;
  847. #region Update Timers
  848. m_resendUnacked = false;
  849. m_sendAcks = false;
  850. m_sendPing = false;
  851. // Update elapsed time
  852. int thisTick = Environment.TickCount & Int32.MaxValue;
  853. if (m_tickLastOutgoingPacketHandler > thisTick)
  854. m_elapsedMSOutgoingPacketHandler += ((Int32.MaxValue - m_tickLastOutgoingPacketHandler) + thisTick);
  855. else
  856. m_elapsedMSOutgoingPacketHandler += (thisTick - m_tickLastOutgoingPacketHandler);
  857. m_tickLastOutgoingPacketHandler = thisTick;
  858. // Check for pending outgoing resends every 100ms
  859. if (m_elapsedMSOutgoingPacketHandler >= 100)
  860. {
  861. m_resendUnacked = true;
  862. m_elapsedMSOutgoingPacketHandler = 0;
  863. m_elapsed100MSOutgoingPacketHandler += 1;
  864. }
  865. // Check for pending outgoing ACKs every 500ms
  866. if (m_elapsed100MSOutgoingPacketHandler >= 5)
  867. {
  868. m_sendAcks = true;
  869. m_elapsed100MSOutgoingPacketHandler = 0;
  870. m_elapsed500MSOutgoingPacketHandler += 1;
  871. }
  872. // Send pings to clients every 5000ms
  873. if (m_elapsed500MSOutgoingPacketHandler >= 10)
  874. {
  875. m_sendPing = true;
  876. m_elapsed500MSOutgoingPacketHandler = 0;
  877. }
  878. #endregion Update Timers
  879. // Use this for emergency monitoring -- bug hunting
  880. //if (m_scene.EmergencyMonitoring)
  881. // clientPacketHandler = MonitoredClientOutgoingPacketHandler;
  882. //else
  883. // clientPacketHandler = ClientOutgoingPacketHandler;
  884. // Handle outgoing packets, resends, acknowledgements, and pings for each
  885. // client. m_packetSent will be set to true if a packet is sent
  886. m_scene.ForEachClient(clientPacketHandler);
  887. // If nothing was sent, sleep for the minimum amount of time before a
  888. // token bucket could get more tokens
  889. if (!m_packetSent)
  890. Thread.Sleep((int)TickCountResolution);
  891. Watchdog.UpdateThread();
  892. }
  893. catch (Exception ex)
  894. {
  895. m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler loop threw an exception: " + ex.Message, ex);
  896. }
  897. }
  898. Watchdog.RemoveThread();
  899. }
  900. private void ClientOutgoingPacketHandler(IClientAPI client)
  901. {
  902. try
  903. {
  904. if (client is LLClientView)
  905. {
  906. LLUDPClient udpClient = ((LLClientView)client).UDPClient;
  907. if (udpClient.IsConnected)
  908. {
  909. if (m_resendUnacked)
  910. HandleUnacked(udpClient);
  911. if (m_sendAcks)
  912. SendAcks(udpClient);
  913. if (m_sendPing)
  914. SendPing(udpClient);
  915. // Dequeue any outgoing packets that are within the throttle limits
  916. if (udpClient.DequeueOutgoing())
  917. m_packetSent = true;
  918. }
  919. }
  920. }
  921. catch (Exception ex)
  922. {
  923. m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler iteration for " + client.Name +
  924. " threw an exception: " + ex.Message, ex);
  925. }
  926. }
  927. #region Emergency Monitoring
  928. // Alternative packet handler fuull of instrumentation
  929. // Handy for hunting bugs
  930. private Stopwatch watch1 = new Stopwatch();
  931. private Stopwatch watch2 = new Stopwatch();
  932. private float avgProcessingTicks = 0;
  933. private float avgResendUnackedTicks = 0;
  934. private float avgSendAcksTicks = 0;
  935. private float avgSendPingTicks = 0;
  936. private float avgDequeueTicks = 0;
  937. private long nticks = 0;
  938. private long nticksUnack = 0;
  939. private long nticksAck = 0;
  940. private long nticksPing = 0;
  941. private int npacksSent = 0;
  942. private int npackNotSent = 0;
  943. private void MonitoredClientOutgoingPacketHandler(IClientAPI client)
  944. {
  945. nticks++;
  946. watch1.Start();
  947. try
  948. {
  949. if (client is LLClientView)
  950. {
  951. LLUDPClient udpClient = ((LLClientView)client).UDPClient;
  952. if (udpClient.IsConnected)
  953. {
  954. if (m_resendUnacked)
  955. {
  956. nticksUnack++;
  957. watch2.Start();
  958. HandleUnacked(udpClient);
  959. watch2.Stop();
  960. avgResendUnackedTicks = (nticksUnack - 1)/(float)nticksUnack * avgResendUnackedTicks + (watch2.ElapsedTicks / (float)nticksUnack);
  961. watch2.Reset();
  962. }
  963. if (m_sendAcks)
  964. {
  965. nticksAck++;
  966. watch2.Start();
  967. SendAcks(udpClient);
  968. watch2.Stop();
  969. avgSendAcksTicks = (nticksAck - 1) / (float)nticksAck * avgSendAcksTicks + (watch2.ElapsedTicks / (float)nticksAck);
  970. watch2.Reset();
  971. }
  972. if (m_sendPing)
  973. {
  974. nticksPing++;
  975. watch2.Start();
  976. SendPing(udpClient);
  977. watch2.Stop();
  978. avgSendPingTicks = (nticksPing - 1) / (float)nticksPing * avgSendPingTicks + (watch2.ElapsedTicks / (float)nticksPing);
  979. watch2.Reset();
  980. }
  981. watch2.Start();
  982. // Dequeue any outgoing packets that are within the throttle limits
  983. if (udpClient.DequeueOutgoing())
  984. {
  985. m_packetSent = true;
  986. npacksSent++;
  987. }
  988. else
  989. npackNotSent++;
  990. watch2.Stop();
  991. avgDequeueTicks = (nticks - 1) / (float)nticks * avgDequeueTicks + (watch2.ElapsedTicks / (float)nticks);
  992. watch2.Reset();
  993. }
  994. else
  995. m_log.WarnFormat("[LLUDPSERVER]: Client is not connected");
  996. }
  997. }
  998. catch (Exception ex)
  999. {
  1000. m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler iteration for " + client.Name +
  1001. " threw an exception: " + ex.Message, ex);
  1002. }
  1003. watch1.Stop();
  1004. avgProcessingTicks = (nticks - 1) / (float)nticks * avgProcessingTicks + (watch1.ElapsedTicks / (float)nticks);
  1005. watch1.Reset();
  1006. // reuse this -- it's every ~100ms
  1007. if (m_scene.EmergencyMonitoring && nticks % 100 == 0)
  1008. {
  1009. m_log.InfoFormat("[LLUDPSERVER]: avg processing ticks: {0} avg unacked: {1} avg acks: {2} avg ping: {3} avg dequeue: {4} (TickCountRes: {5} sent: {6} notsent: {7})",
  1010. avgProcessingTicks, avgResendUnackedTicks, avgSendAcksTicks, avgSendPingTicks, avgDequeueTicks, TickCountResolution, npacksSent, npackNotSent);
  1011. npackNotSent = npacksSent = 0;
  1012. }
  1013. }
  1014. #endregion
  1015. private void ProcessInPacket(object state)
  1016. {
  1017. IncomingPacket incomingPacket = (IncomingPacket)state;
  1018. Packet packet = incomingPacket.Packet;
  1019. LLUDPClient udpClient = incomingPacket.Client;
  1020. IClientAPI client;
  1021. // Sanity check
  1022. if (packet == null || udpClient == null)
  1023. {
  1024. m_log.WarnFormat("[LLUDPSERVER]: Processing a packet with incomplete state. Packet=\"{0}\", UDPClient=\"{1}\"",
  1025. packet, udpClient);
  1026. }
  1027. // Make sure this client is still alive
  1028. if (m_scene.TryGetClient(udpClient.AgentID, out client))
  1029. {
  1030. try
  1031. {
  1032. // Process this packet
  1033. client.ProcessInPacket(packet);
  1034. }
  1035. catch (ThreadAbortException)
  1036. {
  1037. // If something is trying to abort the packet processing thread, take that as a hint that it's time to shut down
  1038. m_log.Info("[LLUDPSERVER]: Caught a thread abort, shutting down the LLUDP server");
  1039. Stop();
  1040. }
  1041. catch (Exception e)
  1042. {
  1043. // Don't let a failure in an individual client thread crash the whole sim.
  1044. m_log.ErrorFormat("[LLUDPSERVER]: Client packet handler for {0} for packet {1} threw an exception", udpClient.AgentID, packet.Type);
  1045. m_log.Error(e.Message, e);
  1046. }
  1047. }
  1048. else
  1049. {
  1050. m_log.DebugFormat("[LLUDPSERVER]: Dropping incoming {0} packet for dead client {1}", packet.Type, udpClient.AgentID);
  1051. }
  1052. }
  1053. protected void LogoutHandler(IClientAPI client)
  1054. {
  1055. client.SendLogoutPacket();
  1056. if (client.IsActive)
  1057. RemoveClient(((LLClientView)client).UDPClient);
  1058. }
  1059. }
  1060. }