LLUDPServer.cs 45 KB

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