LLUDPServer.cs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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 terse prim updates to put on the queue each time the
  90. /// OnQueueEmpty event is triggered for updates</summary>
  91. public readonly int PrimTerseUpdatesPerPacket;
  92. /// <summary>Number of terse avatar updates to put on the queue each time the
  93. /// OnQueueEmpty event is triggered for updates</summary>
  94. public readonly int AvatarTerseUpdatesPerPacket;
  95. /// <summary>Number of full prim updates to put on the queue each time the
  96. /// OnQueueEmpty event is triggered for updates</summary>
  97. public readonly int PrimFullUpdatesPerPacket;
  98. /// <summary>Number of texture packets to put on the queue each time the
  99. /// OnQueueEmpty event is triggered for textures</summary>
  100. public readonly int TextureSendLimit;
  101. /// <summary>Handlers for incoming packets</summary>
  102. //PacketEventDictionary packetEvents = new PacketEventDictionary();
  103. /// <summary>Incoming packets that are awaiting handling</summary>
  104. private OpenMetaverse.BlockingQueue<IncomingPacket> packetInbox = new OpenMetaverse.BlockingQueue<IncomingPacket>();
  105. /// <summary></summary>
  106. //private UDPClientCollection m_clients = new UDPClientCollection();
  107. /// <summary>Bandwidth throttle for this UDP server</summary>
  108. protected TokenBucket m_throttle;
  109. /// <summary>Bandwidth throttle rates for this UDP server</summary>
  110. protected ThrottleRates m_throttleRates;
  111. /// <summary>Manages authentication for agent circuits</summary>
  112. private AgentCircuitManager m_circuitManager;
  113. /// <summary>Reference to the scene this UDP server is attached to</summary>
  114. protected Scene m_scene;
  115. /// <summary>The X/Y coordinates of the scene this UDP server is attached to</summary>
  116. private Location m_location;
  117. /// <summary>The size of the receive buffer for the UDP socket. This value
  118. /// is passed up to the operating system and used in the system networking
  119. /// stack. Use zero to leave this value as the default</summary>
  120. private int m_recvBufferSize;
  121. /// <summary>Flag to process packets asynchronously or synchronously</summary>
  122. private bool m_asyncPacketHandling;
  123. /// <summary>Tracks whether or not a packet was sent each round so we know
  124. /// whether or not to sleep</summary>
  125. private bool m_packetSent;
  126. /// <summary>Environment.TickCount of the last time that packet stats were reported to the scene</summary>
  127. private int m_elapsedMSSinceLastStatReport = 0;
  128. /// <summary>Environment.TickCount of the last time the outgoing packet handler executed</summary>
  129. private int m_tickLastOutgoingPacketHandler;
  130. /// <summary>Keeps track of the number of elapsed milliseconds since the last time the outgoing packet handler looped</summary>
  131. private int m_elapsedMSOutgoingPacketHandler;
  132. /// <summary>Keeps track of the number of 100 millisecond periods elapsed in the outgoing packet handler executed</summary>
  133. private int m_elapsed100MSOutgoingPacketHandler;
  134. /// <summary>Keeps track of the number of 500 millisecond periods elapsed in the outgoing packet handler executed</summary>
  135. private int m_elapsed500MSOutgoingPacketHandler;
  136. /// <summary>Flag to signal when clients should check for resends</summary>
  137. private bool m_resendUnacked;
  138. /// <summary>Flag to signal when clients should send ACKs</summary>
  139. private bool m_sendAcks;
  140. /// <summary>Flag to signal when clients should send pings</summary>
  141. private bool m_sendPing;
  142. private int m_defaultRTO = 0;
  143. private int m_maxRTO = 0;
  144. public Socket Server { get { return null; } }
  145. public LLUDPServer(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
  146. : base(listenIP, (int)port)
  147. {
  148. #region Environment.TickCount Measurement
  149. // Measure the resolution of Environment.TickCount
  150. TickCountResolution = 0f;
  151. for (int i = 0; i < 5; i++)
  152. {
  153. int start = Environment.TickCount;
  154. int now = start;
  155. while (now == start)
  156. now = Environment.TickCount;
  157. TickCountResolution += (float)(now - start) * 0.2f;
  158. }
  159. m_log.Info("[LLUDPSERVER]: Average Environment.TickCount resolution: " + TickCountResolution + "ms");
  160. TickCountResolution = (float)Math.Ceiling(TickCountResolution);
  161. #endregion Environment.TickCount Measurement
  162. m_circuitManager = circuitManager;
  163. int sceneThrottleBps = 0;
  164. IConfig config = configSource.Configs["ClientStack.LindenUDP"];
  165. if (config != null)
  166. {
  167. m_asyncPacketHandling = config.GetBoolean("async_packet_handling", false);
  168. m_recvBufferSize = config.GetInt("client_socket_rcvbuf_size", 0);
  169. sceneThrottleBps = config.GetInt("scene_throttle_max_bps", 0);
  170. PrimTerseUpdatesPerPacket = config.GetInt("PrimTerseUpdatesPerPacket", 25);
  171. AvatarTerseUpdatesPerPacket = config.GetInt("AvatarTerseUpdatesPerPacket", 10);
  172. PrimFullUpdatesPerPacket = config.GetInt("PrimFullUpdatesPerPacket", 100);
  173. TextureSendLimit = config.GetInt("TextureSendLimit", 20);
  174. m_defaultRTO = config.GetInt("DefaultRTO", 0);
  175. m_maxRTO = config.GetInt("MaxRTO", 0);
  176. }
  177. else
  178. {
  179. PrimTerseUpdatesPerPacket = 25;
  180. AvatarTerseUpdatesPerPacket = 10;
  181. PrimFullUpdatesPerPacket = 100;
  182. TextureSendLimit = 20;
  183. }
  184. #region BinaryStats
  185. config = configSource.Configs["Statistics.Binary"];
  186. m_shouldCollectStats = false;
  187. if (config != null)
  188. {
  189. if (config.Contains("enabled") && config.GetBoolean("enabled"))
  190. {
  191. if (config.Contains("collect_packet_headers"))
  192. m_shouldCollectStats = config.GetBoolean("collect_packet_headers");
  193. if (config.Contains("packet_headers_period_seconds"))
  194. {
  195. binStatsMaxFilesize = TimeSpan.FromSeconds(config.GetInt("region_stats_period_seconds"));
  196. }
  197. if (config.Contains("stats_dir"))
  198. {
  199. binStatsDir = config.GetString("stats_dir");
  200. }
  201. }
  202. else
  203. {
  204. m_shouldCollectStats = false;
  205. }
  206. }
  207. #endregion BinaryStats
  208. m_throttle = new TokenBucket(null, sceneThrottleBps, sceneThrottleBps);
  209. m_throttleRates = new ThrottleRates(configSource);
  210. }
  211. public void Start()
  212. {
  213. if (m_scene == null)
  214. throw new InvalidOperationException("[LLUDPSERVER]: Cannot LLUDPServer.Start() without an IScene reference");
  215. m_log.Info("[LLUDPSERVER]: Starting the LLUDP server in " + (m_asyncPacketHandling ? "asynchronous" : "synchronous") + " mode");
  216. base.Start(m_recvBufferSize, m_asyncPacketHandling);
  217. // Start the packet processing threads
  218. Watchdog.StartThread(IncomingPacketHandler, "Incoming Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
  219. Watchdog.StartThread(OutgoingPacketHandler, "Outgoing Packets (" + m_scene.RegionInfo.RegionName + ")", ThreadPriority.Normal, false);
  220. m_elapsedMSSinceLastStatReport = Environment.TickCount;
  221. }
  222. public new void Stop()
  223. {
  224. m_log.Info("[LLUDPSERVER]: Shutting down the LLUDP server for " + m_scene.RegionInfo.RegionName);
  225. base.Stop();
  226. }
  227. public void AddScene(IScene scene)
  228. {
  229. if (m_scene != null)
  230. {
  231. m_log.Error("[LLUDPSERVER]: AddScene() called on an LLUDPServer that already has a scene");
  232. return;
  233. }
  234. if (!(scene is Scene))
  235. {
  236. m_log.Error("[LLUDPSERVER]: AddScene() called with an unrecognized scene type " + scene.GetType());
  237. return;
  238. }
  239. m_scene = (Scene)scene;
  240. m_location = new Location(m_scene.RegionInfo.RegionHandle);
  241. }
  242. public bool HandlesRegion(Location x)
  243. {
  244. return x == m_location;
  245. }
  246. public void BroadcastPacket(Packet packet, ThrottleOutPacketType category, bool sendToPausedAgents, bool allowSplitting)
  247. {
  248. // CoarseLocationUpdate and AvatarGroupsReply packets cannot be split in an automated way
  249. if ((packet.Type == PacketType.CoarseLocationUpdate || packet.Type == PacketType.AvatarGroupsReply) && allowSplitting)
  250. allowSplitting = false;
  251. if (allowSplitting && packet.HasVariableBlocks)
  252. {
  253. byte[][] datas = packet.ToBytesMultiple();
  254. int packetCount = datas.Length;
  255. if (packetCount < 1)
  256. m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
  257. for (int i = 0; i < packetCount; i++)
  258. {
  259. byte[] data = datas[i];
  260. m_scene.ForEachClient(
  261. delegate(IClientAPI client)
  262. {
  263. if (client is LLClientView)
  264. SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category);
  265. }
  266. );
  267. }
  268. }
  269. else
  270. {
  271. byte[] data = packet.ToBytes();
  272. m_scene.ForEachClient(
  273. delegate(IClientAPI client)
  274. {
  275. if (client is LLClientView)
  276. SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category);
  277. }
  278. );
  279. }
  280. }
  281. public void SendPacket(LLUDPClient udpClient, Packet packet, ThrottleOutPacketType category, bool allowSplitting)
  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);
  296. }
  297. }
  298. else
  299. {
  300. byte[] data = packet.ToBytes();
  301. SendPacketData(udpClient, data, packet.Type, category);
  302. }
  303. }
  304. public void SendPacketData(LLUDPClient udpClient, byte[] data, PacketType type, ThrottleOutPacketType category)
  305. {
  306. int dataLength = data.Length;
  307. bool doZerocode = (data[0] & Helpers.MSG_ZEROCODED) != 0;
  308. bool doCopy = true;
  309. // Frequency analysis of outgoing packet sizes shows a large clump of packets at each end of the spectrum.
  310. // The vast majority of packets are less than 200 bytes, although due to asset transfers and packet splitting
  311. // there are a decent number of packets in the 1000-1140 byte range. We allocate one of two sizes of data here
  312. // to accomodate for both common scenarios and provide ample room for ACK appending in both
  313. int bufferSize = (dataLength > 180) ? LLUDPServer.MTU : 200;
  314. UDPPacketBuffer buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
  315. // Zerocode if needed
  316. if (doZerocode)
  317. {
  318. try
  319. {
  320. dataLength = Helpers.ZeroEncode(data, dataLength, buffer.Data);
  321. doCopy = false;
  322. }
  323. catch (IndexOutOfRangeException)
  324. {
  325. // The packet grew larger than the bufferSize while zerocoding.
  326. // Remove the MSG_ZEROCODED flag and send the unencoded data
  327. // instead
  328. m_log.Debug("[LLUDPSERVER]: Packet exceeded buffer size during zerocoding for " + type + ". DataLength=" + dataLength +
  329. " and BufferLength=" + buffer.Data.Length + ". Removing MSG_ZEROCODED flag");
  330. data[0] = (byte)(data[0] & ~Helpers.MSG_ZEROCODED);
  331. }
  332. }
  333. // If the packet data wasn't already copied during zerocoding, copy it now
  334. if (doCopy)
  335. {
  336. if (dataLength <= buffer.Data.Length)
  337. {
  338. Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
  339. }
  340. else
  341. {
  342. bufferSize = dataLength;
  343. buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
  344. // m_log.Error("[LLUDPSERVER]: Packet exceeded buffer size! This could be an indication of packet assembly not obeying the MTU. Type=" +
  345. // type + ", DataLength=" + dataLength + ", BufferLength=" + buffer.Data.Length + ". Dropping packet");
  346. Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
  347. }
  348. }
  349. buffer.DataLength = dataLength;
  350. #region Queue or Send
  351. OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category);
  352. if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket))
  353. SendPacketFinal(outgoingPacket);
  354. #endregion Queue or Send
  355. }
  356. public void SendAcks(LLUDPClient udpClient)
  357. {
  358. uint ack;
  359. if (udpClient.PendingAcks.Dequeue(out ack))
  360. {
  361. List<PacketAckPacket.PacketsBlock> blocks = new List<PacketAckPacket.PacketsBlock>();
  362. PacketAckPacket.PacketsBlock block = new PacketAckPacket.PacketsBlock();
  363. block.ID = ack;
  364. blocks.Add(block);
  365. while (udpClient.PendingAcks.Dequeue(out ack))
  366. {
  367. block = new PacketAckPacket.PacketsBlock();
  368. block.ID = ack;
  369. blocks.Add(block);
  370. }
  371. PacketAckPacket packet = new PacketAckPacket();
  372. packet.Header.Reliable = false;
  373. packet.Packets = blocks.ToArray();
  374. SendPacket(udpClient, packet, ThrottleOutPacketType.Unknown, true);
  375. }
  376. }
  377. public void SendPing(LLUDPClient udpClient)
  378. {
  379. StartPingCheckPacket pc = (StartPingCheckPacket)PacketPool.Instance.GetPacket(PacketType.StartPingCheck);
  380. pc.Header.Reliable = false;
  381. pc.PingID.PingID = (byte)udpClient.CurrentPingSequence++;
  382. // We *could* get OldestUnacked, but it would hurt performance and not provide any benefit
  383. pc.PingID.OldestUnacked = 0;
  384. SendPacket(udpClient, pc, ThrottleOutPacketType.Unknown, false);
  385. }
  386. public void CompletePing(LLUDPClient udpClient, byte pingID)
  387. {
  388. CompletePingCheckPacket completePing = new CompletePingCheckPacket();
  389. completePing.PingID.PingID = pingID;
  390. SendPacket(udpClient, completePing, ThrottleOutPacketType.Unknown, false);
  391. }
  392. public void ResendUnacked(LLUDPClient udpClient)
  393. {
  394. if (!udpClient.IsConnected)
  395. return;
  396. // Disconnect an agent if no packets are received for some time
  397. //FIXME: Make 60 an .ini setting
  398. if ((Environment.TickCount & Int32.MaxValue) - udpClient.TickLastPacketReceived > 1000 * 60)
  399. {
  400. m_log.Warn("[LLUDPSERVER]: Ack timeout, disconnecting " + udpClient.AgentID);
  401. RemoveClient(udpClient);
  402. return;
  403. }
  404. // Get a list of all of the packets that have been sitting unacked longer than udpClient.RTO
  405. List<OutgoingPacket> expiredPackets = udpClient.NeedAcks.GetExpiredPackets(udpClient.RTO);
  406. if (expiredPackets != null)
  407. {
  408. //m_log.Debug("[LLUDPSERVER]: Resending " + expiredPackets.Count + " packets to " + udpClient.AgentID + ", RTO=" + udpClient.RTO);
  409. // Exponential backoff of the retransmission timeout
  410. udpClient.BackoffRTO();
  411. // Resend packets
  412. for (int i = 0; i < expiredPackets.Count; i++)
  413. {
  414. OutgoingPacket outgoingPacket = expiredPackets[i];
  415. //m_log.DebugFormat("[LLUDPSERVER]: Resending packet #{0} (attempt {1}), {2}ms have passed",
  416. // outgoingPacket.SequenceNumber, outgoingPacket.ResendCount, Environment.TickCount - outgoingPacket.TickCount);
  417. // Set the resent flag
  418. outgoingPacket.Buffer.Data[0] = (byte)(outgoingPacket.Buffer.Data[0] | Helpers.MSG_RESENT);
  419. outgoingPacket.Category = ThrottleOutPacketType.Resend;
  420. // Bump up the resend count on this packet
  421. Interlocked.Increment(ref outgoingPacket.ResendCount);
  422. //Interlocked.Increment(ref Stats.ResentPackets);
  423. // Requeue or resend the packet
  424. if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket))
  425. SendPacketFinal(outgoingPacket);
  426. }
  427. }
  428. }
  429. public void Flush(LLUDPClient udpClient)
  430. {
  431. // FIXME: Implement?
  432. }
  433. internal void SendPacketFinal(OutgoingPacket outgoingPacket)
  434. {
  435. UDPPacketBuffer buffer = outgoingPacket.Buffer;
  436. byte flags = buffer.Data[0];
  437. bool isResend = (flags & Helpers.MSG_RESENT) != 0;
  438. bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
  439. LLUDPClient udpClient = outgoingPacket.Client;
  440. if (!udpClient.IsConnected)
  441. return;
  442. #region ACK Appending
  443. int dataLength = buffer.DataLength;
  444. // Keep appending ACKs until there is no room left in the buffer or there are
  445. // no more ACKs to append
  446. uint ackCount = 0;
  447. uint ack;
  448. while (dataLength + 5 < buffer.Data.Length && udpClient.PendingAcks.Dequeue(out ack))
  449. {
  450. Utils.UIntToBytesBig(ack, buffer.Data, dataLength);
  451. dataLength += 4;
  452. ++ackCount;
  453. }
  454. if (ackCount > 0)
  455. {
  456. // Set the last byte of the packet equal to the number of appended ACKs
  457. buffer.Data[dataLength++] = (byte)ackCount;
  458. // Set the appended ACKs flag on this packet
  459. buffer.Data[0] = (byte)(buffer.Data[0] | Helpers.MSG_APPENDED_ACKS);
  460. }
  461. buffer.DataLength = dataLength;
  462. #endregion ACK Appending
  463. #region Sequence Number Assignment
  464. if (!isResend)
  465. {
  466. // Not a resend, assign a new sequence number
  467. uint sequenceNumber = (uint)Interlocked.Increment(ref udpClient.CurrentSequence);
  468. Utils.UIntToBytesBig(sequenceNumber, buffer.Data, 1);
  469. outgoingPacket.SequenceNumber = sequenceNumber;
  470. if (isReliable)
  471. {
  472. // Add this packet to the list of ACK responses we are waiting on from the server
  473. udpClient.NeedAcks.Add(outgoingPacket);
  474. }
  475. }
  476. #endregion Sequence Number Assignment
  477. // Stats tracking
  478. Interlocked.Increment(ref udpClient.PacketsSent);
  479. if (isReliable)
  480. Interlocked.Add(ref udpClient.UnackedBytes, outgoingPacket.Buffer.DataLength);
  481. // Put the UDP payload on the wire
  482. AsyncBeginSend(buffer);
  483. // Keep track of when this packet was sent out (right now)
  484. outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
  485. }
  486. protected override void PacketReceived(UDPPacketBuffer buffer)
  487. {
  488. // Debugging/Profiling
  489. //try { Thread.CurrentThread.Name = "PacketReceived (" + m_scene.RegionInfo.RegionName + ")"; }
  490. //catch (Exception) { }
  491. LLUDPClient udpClient = null;
  492. Packet packet = null;
  493. int packetEnd = buffer.DataLength - 1;
  494. IPEndPoint address = (IPEndPoint)buffer.RemoteEndPoint;
  495. #region Decoding
  496. try
  497. {
  498. packet = Packet.BuildPacket(buffer.Data, ref packetEnd,
  499. // Only allocate a buffer for zerodecoding if the packet is zerocoded
  500. ((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0) ? new byte[4096] : null);
  501. }
  502. catch (MalformedDataException)
  503. {
  504. m_log.ErrorFormat("[LLUDPSERVER]: Malformed data, cannot parse packet from {0}:\n{1}",
  505. buffer.RemoteEndPoint, Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
  506. }
  507. // Fail-safe check
  508. if (packet == null)
  509. {
  510. m_log.Warn("[LLUDPSERVER]: Couldn't build a message from incoming data " + buffer.DataLength +
  511. " bytes long from " + buffer.RemoteEndPoint);
  512. return;
  513. }
  514. #endregion Decoding
  515. #region Packet to Client Mapping
  516. // UseCircuitCode handling
  517. if (packet.Type == PacketType.UseCircuitCode)
  518. {
  519. m_log.Debug("[LLUDPSERVER]: Handling UseCircuitCode packet from " + buffer.RemoteEndPoint);
  520. object[] array = new object[] { buffer, packet };
  521. if (m_asyncPacketHandling)
  522. Util.FireAndForget(HandleUseCircuitCode, array);
  523. else
  524. HandleUseCircuitCode(array);
  525. return;
  526. }
  527. // Determine which agent this packet came from
  528. IClientAPI client;
  529. if (!m_scene.TryGetClient(address, out client) || !(client is LLClientView))
  530. {
  531. //m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet from an unrecognized source: " + address + " in " + m_scene.RegionInfo.RegionName);
  532. return;
  533. }
  534. udpClient = ((LLClientView)client).UDPClient;
  535. if (!udpClient.IsConnected)
  536. return;
  537. #endregion Packet to Client Mapping
  538. // Stats tracking
  539. Interlocked.Increment(ref udpClient.PacketsReceived);
  540. int now = Environment.TickCount & Int32.MaxValue;
  541. udpClient.TickLastPacketReceived = now;
  542. #region ACK Receiving
  543. // Handle appended ACKs
  544. if (packet.Header.AppendedAcks && packet.Header.AckList != null)
  545. {
  546. for (int i = 0; i < packet.Header.AckList.Length; i++)
  547. udpClient.NeedAcks.Remove(packet.Header.AckList[i], now, packet.Header.Resent);
  548. }
  549. // Handle PacketAck packets
  550. if (packet.Type == PacketType.PacketAck)
  551. {
  552. PacketAckPacket ackPacket = (PacketAckPacket)packet;
  553. for (int i = 0; i < ackPacket.Packets.Length; i++)
  554. udpClient.NeedAcks.Remove(ackPacket.Packets[i].ID, now, packet.Header.Resent);
  555. // We don't need to do anything else with PacketAck packets
  556. return;
  557. }
  558. #endregion ACK Receiving
  559. #region ACK Sending
  560. if (packet.Header.Reliable)
  561. {
  562. udpClient.PendingAcks.Enqueue(packet.Header.Sequence);
  563. // This is a somewhat odd sequence of steps to pull the client.BytesSinceLastACK value out,
  564. // add the current received bytes to it, test if 2*MTU bytes have been sent, if so remove
  565. // 2*MTU bytes from the value and send ACKs, and finally add the local value back to
  566. // client.BytesSinceLastACK. Lockless thread safety
  567. int bytesSinceLastACK = Interlocked.Exchange(ref udpClient.BytesSinceLastACK, 0);
  568. bytesSinceLastACK += buffer.DataLength;
  569. if (bytesSinceLastACK > LLUDPServer.MTU * 2)
  570. {
  571. bytesSinceLastACK -= LLUDPServer.MTU * 2;
  572. SendAcks(udpClient);
  573. }
  574. Interlocked.Add(ref udpClient.BytesSinceLastACK, bytesSinceLastACK);
  575. }
  576. #endregion ACK Sending
  577. #region Incoming Packet Accounting
  578. // Check the archive of received reliable packet IDs to see whether we already received this packet
  579. if (packet.Header.Reliable && !udpClient.PacketArchive.TryEnqueue(packet.Header.Sequence))
  580. {
  581. if (packet.Header.Resent)
  582. m_log.Debug("[LLUDPSERVER]: Received a resend of already processed packet #" + packet.Header.Sequence + ", type: " + packet.Type);
  583. else
  584. m_log.Warn("[LLUDPSERVER]: Received a duplicate (not marked as resend) of packet #" + packet.Header.Sequence + ", type: " + packet.Type);
  585. // Avoid firing a callback twice for the same packet
  586. return;
  587. }
  588. #endregion Incoming Packet Accounting
  589. #region BinaryStats
  590. LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
  591. #endregion BinaryStats
  592. #region Ping Check Handling
  593. if (packet.Type == PacketType.StartPingCheck)
  594. {
  595. // We don't need to do anything else with ping checks
  596. StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
  597. CompletePing(udpClient, startPing.PingID.PingID);
  598. if ((Environment.TickCount - m_elapsedMSSinceLastStatReport) >= 3000)
  599. {
  600. udpClient.SendPacketStats();
  601. m_elapsedMSSinceLastStatReport = Environment.TickCount;
  602. }
  603. return;
  604. }
  605. else if (packet.Type == PacketType.CompletePingCheck)
  606. {
  607. // We don't currently track client ping times
  608. return;
  609. }
  610. #endregion Ping Check Handling
  611. // Inbox insertion
  612. packetInbox.Enqueue(new IncomingPacket(udpClient, packet));
  613. }
  614. #region BinaryStats
  615. public class PacketLogger
  616. {
  617. public DateTime StartTime;
  618. public string Path = null;
  619. public System.IO.BinaryWriter Log = null;
  620. }
  621. public static PacketLogger PacketLog;
  622. protected static bool m_shouldCollectStats = false;
  623. // Number of seconds to log for
  624. static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
  625. static object binStatsLogLock = new object();
  626. static string binStatsDir = "";
  627. public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
  628. {
  629. if (!m_shouldCollectStats) return;
  630. // Binary logging format is TTTTTTTTCCCCFPPPSS, T=Time, C=Circuit, F=Flags, P=PacketType, S=size
  631. // Put the incoming bit into the least significant bit of the flags byte
  632. if (incoming)
  633. flags |= 0x01;
  634. else
  635. flags &= 0xFE;
  636. // Put the flags byte into the most significant bits of the type integer
  637. uint type = (uint)packetType;
  638. type |= (uint)flags << 24;
  639. // m_log.Debug("1 LogPacketHeader(): Outside lock");
  640. lock (binStatsLogLock)
  641. {
  642. DateTime now = DateTime.Now;
  643. // m_log.Debug("2 LogPacketHeader(): Inside lock. now is " + now.Ticks);
  644. try
  645. {
  646. if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
  647. {
  648. if (PacketLog != null && PacketLog.Log != null)
  649. {
  650. PacketLog.Log.Close();
  651. }
  652. // First log file or time has expired, start writing to a new log file
  653. PacketLog = new PacketLogger();
  654. PacketLog.StartTime = now;
  655. PacketLog.Path = (binStatsDir.Length > 0 ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
  656. + String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
  657. PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
  658. }
  659. // Serialize the data
  660. byte[] output = new byte[18];
  661. Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
  662. Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
  663. Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
  664. Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);
  665. // Write the serialized data to disk
  666. if (PacketLog != null && PacketLog.Log != null)
  667. PacketLog.Log.Write(output);
  668. }
  669. catch (Exception ex)
  670. {
  671. m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
  672. if (PacketLog.Log != null)
  673. {
  674. PacketLog.Log.Close();
  675. }
  676. PacketLog = null;
  677. }
  678. }
  679. }
  680. #endregion BinaryStats
  681. private void HandleUseCircuitCode(object o)
  682. {
  683. object[] array = (object[])o;
  684. UDPPacketBuffer buffer = (UDPPacketBuffer)array[0];
  685. UseCircuitCodePacket packet = (UseCircuitCodePacket)array[1];
  686. IPEndPoint remoteEndPoint = (IPEndPoint)buffer.RemoteEndPoint;
  687. // Begin the process of adding the client to the simulator
  688. AddNewClient((UseCircuitCodePacket)packet, remoteEndPoint);
  689. // Acknowledge the UseCircuitCode packet
  690. SendAckImmediate(remoteEndPoint, packet.Header.Sequence);
  691. }
  692. private void SendAckImmediate(IPEndPoint remoteEndpoint, uint sequenceNumber)
  693. {
  694. PacketAckPacket ack = new PacketAckPacket();
  695. ack.Header.Reliable = false;
  696. ack.Packets = new PacketAckPacket.PacketsBlock[1];
  697. ack.Packets[0] = new PacketAckPacket.PacketsBlock();
  698. ack.Packets[0].ID = sequenceNumber;
  699. byte[] packetData = ack.ToBytes();
  700. int length = packetData.Length;
  701. UDPPacketBuffer buffer = new UDPPacketBuffer(remoteEndpoint, length);
  702. buffer.DataLength = length;
  703. Buffer.BlockCopy(packetData, 0, buffer.Data, 0, length);
  704. AsyncBeginSend(buffer);
  705. }
  706. private bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, out AuthenticateResponse sessionInfo)
  707. {
  708. UUID agentID = useCircuitCode.CircuitCode.ID;
  709. UUID sessionID = useCircuitCode.CircuitCode.SessionID;
  710. uint circuitCode = useCircuitCode.CircuitCode.Code;
  711. sessionInfo = m_circuitManager.AuthenticateSession(sessionID, agentID, circuitCode);
  712. return sessionInfo.Authorised;
  713. }
  714. private void AddNewClient(UseCircuitCodePacket useCircuitCode, IPEndPoint remoteEndPoint)
  715. {
  716. UUID agentID = useCircuitCode.CircuitCode.ID;
  717. UUID sessionID = useCircuitCode.CircuitCode.SessionID;
  718. uint circuitCode = useCircuitCode.CircuitCode.Code;
  719. if (m_scene.RegionStatus != RegionStatus.SlaveScene)
  720. {
  721. AuthenticateResponse sessionInfo;
  722. if (IsClientAuthorized(useCircuitCode, out sessionInfo))
  723. {
  724. AddClient(circuitCode, agentID, sessionID, remoteEndPoint, sessionInfo);
  725. }
  726. else
  727. {
  728. // Don't create circuits for unauthorized clients
  729. m_log.WarnFormat(
  730. "[LLUDPSERVER]: Connection request for client {0} connecting with unnotified circuit code {1} from {2}",
  731. useCircuitCode.CircuitCode.ID, useCircuitCode.CircuitCode.Code, remoteEndPoint);
  732. }
  733. }
  734. else
  735. {
  736. // Slave regions don't accept new clients
  737. m_log.Debug("[LLUDPSERVER]: Slave region " + m_scene.RegionInfo.RegionName + " ignoring UseCircuitCode packet");
  738. }
  739. }
  740. protected virtual void AddClient(uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
  741. {
  742. // Create the LLUDPClient
  743. LLUDPClient udpClient = new LLUDPClient(this, m_throttleRates, m_throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
  744. IClientAPI existingClient;
  745. if (!m_scene.TryGetClient(agentID, out existingClient))
  746. {
  747. // Create the LLClientView
  748. LLClientView client = new LLClientView(remoteEndPoint, m_scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);
  749. client.OnLogout += LogoutHandler;
  750. // Start the IClientAPI
  751. client.Start();
  752. }
  753. else
  754. {
  755. m_log.WarnFormat("[LLUDPSERVER]: Ignoring a repeated UseCircuitCode from {0} at {1} for circuit {2}",
  756. udpClient.AgentID, remoteEndPoint, circuitCode);
  757. }
  758. }
  759. private void RemoveClient(LLUDPClient udpClient)
  760. {
  761. // Remove this client from the scene
  762. IClientAPI client;
  763. if (m_scene.TryGetClient(udpClient.AgentID, out client))
  764. client.Close();
  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, false);
  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. }