LLPacketHandler.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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 OpenSim 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;
  29. using System.Collections.Generic;
  30. using System.Net;
  31. using System.Net.Sockets;
  32. using System.Threading;
  33. using System.Timers;
  34. using System.Reflection;
  35. using OpenMetaverse;
  36. using OpenMetaverse.Packets;
  37. using Timer = System.Timers.Timer;
  38. using OpenSim.Framework;
  39. using OpenSim.Region.ClientStack.LindenUDP;
  40. using log4net;
  41. namespace OpenSim.Region.ClientStack.LindenUDP
  42. {
  43. public delegate void PacketStats(int inPackets, int outPackets, int unAckedBytes);
  44. public delegate void PacketDrop(Packet pack, Object id);
  45. public delegate bool SynchronizeClientHandler(IScene scene, Packet packet, UUID agentID, ThrottleOutPacketType throttlePacketType);
  46. public interface IPacketHandler
  47. {
  48. event PacketStats OnPacketStats;
  49. event PacketDrop OnPacketDrop;
  50. SynchronizeClientHandler SynchronizeClient { set; }
  51. int PacketsReceived { get; }
  52. int PacketsReceivedReported { get; }
  53. uint ResendTimeout { get; set; }
  54. bool ReliableIsImportant { get; set; }
  55. int MaxReliableResends { get; set; }
  56. void InPacket(Packet packet);
  57. void ProcessInPacket(LLQueItem item);
  58. void ProcessOutPacket(LLQueItem item);
  59. void OutPacket(Packet NewPack,
  60. ThrottleOutPacketType throttlePacketType);
  61. void OutPacket(Packet NewPack,
  62. ThrottleOutPacketType throttlePacketType, Object id);
  63. LLPacketQueue PacketQueue { get; }
  64. void Stop();
  65. void Flush();
  66. void Clear();
  67. ClientInfo GetClientInfo();
  68. void SetClientInfo(ClientInfo info);
  69. void AddImportantPacket(PacketType type);
  70. void RemoveImportantPacket(PacketType type);
  71. }
  72. public class LLPacketHandler : IPacketHandler
  73. {
  74. //private static readonly ILog m_log
  75. // = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  76. //private int m_resentCount;
  77. // Packet queues
  78. //
  79. LLPacketQueue m_PacketQueue;
  80. public LLPacketQueue PacketQueue
  81. {
  82. get { return m_PacketQueue; }
  83. }
  84. // Timer to run stats and acks on
  85. //
  86. private Timer m_AckTimer = new Timer(250);
  87. // A list of the packets we haven't acked yet
  88. //
  89. private Dictionary<uint, uint> m_PendingAcks = new Dictionary<uint, uint>();
  90. private Dictionary<uint, LLQueItem> m_NeedAck =
  91. new Dictionary<uint, LLQueItem>();
  92. /// <summary>
  93. /// The number of milliseconds that can pass before a packet that needs an ack is resent.
  94. /// </param>
  95. private uint m_ResendTimeout = 4000;
  96. public uint ResendTimeout
  97. {
  98. get { return m_ResendTimeout; }
  99. set { m_ResendTimeout = value; }
  100. }
  101. private int m_MaxReliableResends = 3;
  102. public int MaxReliableResends
  103. {
  104. get { return m_MaxReliableResends; }
  105. set { m_MaxReliableResends = value; }
  106. }
  107. // Track duplicated packets. This uses a Dictionary. Both insertion
  108. // and lookup are common operations and need to take advantage of
  109. // the hashing. Expiration is less common and can be allowed the
  110. // time for a linear scan.
  111. //
  112. private Dictionary<uint, int> m_DupeTracker =
  113. new Dictionary<uint, int>();
  114. private uint m_DupeTrackerWindow = 30;
  115. private int m_DupeTrackerLastCheck = System.Environment.TickCount;
  116. // Values for the SimStatsReporter
  117. //
  118. private int m_PacketsReceived = 0;
  119. private int m_PacketsReceivedReported = 0;
  120. private int m_PacketsSent = 0;
  121. private int m_PacketsSentReported = 0;
  122. private int m_UnackedBytes = 0;
  123. private int m_LastResend = 0;
  124. public int PacketsReceived
  125. {
  126. get { return m_PacketsReceived; }
  127. }
  128. public int PacketsReceivedReported
  129. {
  130. get { return m_PacketsReceivedReported; }
  131. }
  132. // The client we are working for
  133. //
  134. private IClientAPI m_Client;
  135. // Some events
  136. //
  137. public event PacketStats OnPacketStats;
  138. public event PacketDrop OnPacketDrop;
  139. private SynchronizeClientHandler m_SynchronizeClient = null;
  140. public SynchronizeClientHandler SynchronizeClient
  141. {
  142. set { m_SynchronizeClient = value; }
  143. }
  144. // Packet sequencing
  145. //
  146. private uint m_Sequence = 0;
  147. private object m_SequenceLock = new object();
  148. private const int MAX_SEQUENCE = 0xFFFFFF;
  149. // Packet dropping
  150. //
  151. List<PacketType> m_ImportantPackets = new List<PacketType>();
  152. private bool m_ReliableIsImportant = false;
  153. public bool ReliableIsImportant
  154. {
  155. get { return m_ReliableIsImportant; }
  156. set { m_ReliableIsImportant = value; }
  157. }
  158. private int m_DropSafeTimeout;
  159. LLPacketServer m_PacketServer;
  160. private byte[] m_ZeroOutBuffer = new byte[4096];
  161. ////////////////////////////////////////////////////////////////////
  162. // Constructors
  163. //
  164. public LLPacketHandler(IClientAPI client, LLPacketServer server, ClientStackUserSettings userSettings)
  165. {
  166. m_Client = client;
  167. m_PacketServer = server;
  168. m_DropSafeTimeout = System.Environment.TickCount + 15000;
  169. m_PacketQueue = new LLPacketQueue(client.AgentId, userSettings);
  170. m_AckTimer.Elapsed += AckTimerElapsed;
  171. m_AckTimer.Start();
  172. }
  173. public void Stop()
  174. {
  175. m_AckTimer.Stop();
  176. m_PacketQueue.Enqueue(null);
  177. m_PacketQueue.Close();
  178. m_Client = null;
  179. }
  180. // Send one packet. This actually doesn't send anything, it queues
  181. // it. Designed to be fire-and-forget, but there is an optional
  182. // notifier.
  183. //
  184. public void OutPacket(
  185. Packet packet, ThrottleOutPacketType throttlePacketType)
  186. {
  187. OutPacket(packet, throttlePacketType, null);
  188. }
  189. public void OutPacket(
  190. Packet packet, ThrottleOutPacketType throttlePacketType,
  191. Object id)
  192. {
  193. // Call the load balancer's hook. If this is not active here
  194. // we defer to the sim server this client is actually connected
  195. // to. Packet drop notifies will not be triggered in this
  196. // configuration!
  197. //
  198. if ((m_SynchronizeClient != null) && (!m_Client.IsActive))
  199. {
  200. if (m_SynchronizeClient(m_Client.Scene, packet,
  201. m_Client.AgentId, throttlePacketType))
  202. return;
  203. }
  204. packet.Header.Sequence = 0;
  205. lock (m_NeedAck)
  206. {
  207. DropResend(id);
  208. AddAcks(ref packet);
  209. QueuePacket(packet, throttlePacketType, id);
  210. }
  211. }
  212. private void AddAcks(ref Packet packet)
  213. {
  214. // These packet types have shown to have issues with
  215. // acks being appended to the payload, just don't send
  216. // any with them until libsl is fixed.
  217. //
  218. if (packet is OpenMetaverse.Packets.ViewerEffectPacket)
  219. return;
  220. if (packet is OpenMetaverse.Packets.SimStatsPacket)
  221. return;
  222. // Add acks to outgoing packets
  223. //
  224. if (m_PendingAcks.Count > 0)
  225. {
  226. int count = m_PendingAcks.Count;
  227. if (count > 10)
  228. count = 10;
  229. packet.Header.AckList = new uint[count];
  230. packet.Header.AppendedAcks = true;
  231. int i = 0;
  232. foreach (uint ack in new List<uint>(m_PendingAcks.Keys))
  233. {
  234. packet.Header.AckList[i] = ack;
  235. i++;
  236. m_PendingAcks.Remove(ack);
  237. if (i >= count) // That is how much space there is
  238. break;
  239. }
  240. }
  241. }
  242. private void QueuePacket(
  243. Packet packet, ThrottleOutPacketType throttlePacketType,
  244. Object id)
  245. {
  246. LLQueItem item = new LLQueItem();
  247. item.Packet = packet;
  248. item.Incoming = false;
  249. item.throttleType = throttlePacketType;
  250. item.TickCount = System.Environment.TickCount;
  251. item.Identifier = id;
  252. item.Resends = 0;
  253. item.Length = packet.ToBytes().Length;
  254. m_PacketQueue.Enqueue(item);
  255. m_PacketsSent++;
  256. }
  257. private void ResendUnacked()
  258. {
  259. int now = System.Environment.TickCount;
  260. int intervalMs = 250;
  261. if (m_LastResend != 0)
  262. intervalMs = now - m_LastResend;
  263. lock (m_NeedAck)
  264. {
  265. if (m_DropSafeTimeout > now ||
  266. intervalMs > 500) // We were frozen!
  267. {
  268. foreach (LLQueItem data in new List<LLQueItem>
  269. (m_NeedAck.Values))
  270. {
  271. if (m_DropSafeTimeout > now)
  272. {
  273. m_NeedAck[data.Packet.Header.Sequence].
  274. TickCount = now;
  275. }
  276. else
  277. {
  278. m_NeedAck[data.Packet.Header.Sequence].
  279. TickCount += intervalMs;
  280. }
  281. }
  282. }
  283. }
  284. m_LastResend = now;
  285. // Unless we have received at least one ack, don't bother resending
  286. // anything. There may not be a client there, don't clog up the
  287. // pipes.
  288. //
  289. lock (m_NeedAck)
  290. {
  291. // Nothing to do
  292. //
  293. if (m_NeedAck.Count == 0)
  294. return;
  295. int resent = 0;
  296. foreach (LLQueItem data in new List<LLQueItem>(m_NeedAck.Values))
  297. {
  298. Packet packet = data.Packet;
  299. // Packets this old get resent
  300. //
  301. if ((now - data.TickCount) > m_ResendTimeout)
  302. {
  303. if (resent < 20)
  304. {
  305. m_NeedAck[packet.Header.Sequence].Resends++;
  306. // The client needs to be told that a packet is being resent, otherwise it appears to believe
  307. // that it should reset its sequence to that packet number.
  308. packet.Header.Resent = true;
  309. if ((m_NeedAck[packet.Header.Sequence].Resends >=
  310. m_MaxReliableResends) && (!m_ReliableIsImportant))
  311. {
  312. m_NeedAck.Remove(packet.Header.Sequence);
  313. TriggerOnPacketDrop(packet, data.Identifier);
  314. PacketPool.Instance.ReturnPacket(packet);
  315. continue;
  316. }
  317. m_NeedAck[packet.Header.Sequence].TickCount =
  318. System.Environment.TickCount;
  319. QueuePacket(packet, ThrottleOutPacketType.Resend,
  320. data.Identifier);
  321. resent++;
  322. }
  323. else
  324. {
  325. m_NeedAck[packet.Header.Sequence].TickCount +=
  326. intervalMs;
  327. }
  328. }
  329. }
  330. }
  331. }
  332. // Send the pending packet acks to the client
  333. // Will send blocks of acks for up to 250 packets
  334. //
  335. private void SendAcks()
  336. {
  337. lock (m_NeedAck)
  338. {
  339. if (m_PendingAcks.Count == 0)
  340. return;
  341. PacketAckPacket acks = (PacketAckPacket)PacketPool.Instance.GetPacket(PacketType.PacketAck);
  342. // The case of equality is more common than one might think,
  343. // because this function will be called unconditionally when
  344. // the counter reaches 250. So there is a good chance another
  345. // packet with 250 blocks exists.
  346. //
  347. if (acks.Packets == null ||
  348. acks.Packets.Length != m_PendingAcks.Count)
  349. acks.Packets = new PacketAckPacket.PacketsBlock[m_PendingAcks.Count];
  350. int i = 0;
  351. foreach (uint ack in new List<uint>(m_PendingAcks.Keys))
  352. {
  353. acks.Packets[i] = new PacketAckPacket.PacketsBlock();
  354. acks.Packets[i].ID = ack;
  355. m_PendingAcks.Remove(ack);
  356. i++;
  357. }
  358. acks.Header.Reliable = false;
  359. OutPacket(acks, ThrottleOutPacketType.Unknown);
  360. }
  361. }
  362. // Queue a packet ack. It will be sent either after 250 acks are
  363. // queued, or when the timer fires.
  364. //
  365. private void AckPacket(Packet packet)
  366. {
  367. lock (m_NeedAck)
  368. {
  369. if (m_PendingAcks.Count < 250)
  370. {
  371. if (!m_PendingAcks.ContainsKey(packet.Header.Sequence))
  372. m_PendingAcks.Add(packet.Header.Sequence,
  373. packet.Header.Sequence);
  374. return;
  375. }
  376. }
  377. SendAcks();
  378. lock (m_NeedAck)
  379. {
  380. // If this is still full we have a truly exceptional
  381. // condition (means, can't happen)
  382. //
  383. if (m_PendingAcks.Count < 250)
  384. {
  385. if (!m_PendingAcks.ContainsKey(packet.Header.Sequence))
  386. m_PendingAcks.Add(packet.Header.Sequence,
  387. packet.Header.Sequence);
  388. return;
  389. }
  390. }
  391. }
  392. // When the timer elapses, send the pending acks, trigger resends
  393. // and report all the stats.
  394. //
  395. private void AckTimerElapsed(object sender, ElapsedEventArgs ea)
  396. {
  397. SendAcks();
  398. ResendUnacked();
  399. SendPacketStats();
  400. }
  401. // Push out pachet counts for the sim status reporter
  402. //
  403. private void SendPacketStats()
  404. {
  405. PacketStats handlerPacketStats = OnPacketStats;
  406. if (handlerPacketStats != null)
  407. {
  408. handlerPacketStats(
  409. m_PacketsReceived - m_PacketsReceivedReported,
  410. m_PacketsSent - m_PacketsSentReported,
  411. m_UnackedBytes);
  412. m_PacketsReceivedReported = m_PacketsReceived;
  413. m_PacketsSentReported = m_PacketsSent;
  414. }
  415. }
  416. // We can't keep an unlimited record of dupes. This will prune the
  417. // dictionary by age.
  418. //
  419. private void PruneDupeTracker()
  420. {
  421. lock (m_DupeTracker)
  422. {
  423. if (m_DupeTracker.Count < 1024)
  424. return;
  425. if (System.Environment.TickCount - m_DupeTrackerLastCheck < 2000)
  426. return;
  427. m_DupeTrackerLastCheck = System.Environment.TickCount;
  428. Dictionary<uint, int> packs =
  429. new Dictionary<uint, int>(m_DupeTracker);
  430. foreach (uint pack in packs.Keys)
  431. {
  432. if (Util.UnixTimeSinceEpoch() - m_DupeTracker[pack] >
  433. m_DupeTrackerWindow)
  434. m_DupeTracker.Remove(pack);
  435. }
  436. }
  437. }
  438. public void InPacket(Packet packet)
  439. {
  440. if (packet == null)
  441. return;
  442. // If this client is on another partial instance, no need
  443. // to handle packets
  444. //
  445. if (!m_Client.IsActive && packet.Type != PacketType.LogoutRequest)
  446. {
  447. PacketPool.Instance.ReturnPacket(packet);
  448. return;
  449. }
  450. // Any packet can have some packet acks in the header.
  451. // Process them here
  452. //
  453. if (packet.Header.AppendedAcks)
  454. {
  455. foreach (uint id in packet.Header.AckList)
  456. {
  457. ProcessAck(id);
  458. }
  459. }
  460. // When too many acks are needed to be sent, the client sends
  461. // a packet consisting of acks only
  462. //
  463. if (packet.Type == PacketType.PacketAck)
  464. {
  465. PacketAckPacket ackPacket = (PacketAckPacket)packet;
  466. foreach (PacketAckPacket.PacketsBlock block in
  467. ackPacket.Packets)
  468. {
  469. ProcessAck(block.ID);
  470. }
  471. PacketPool.Instance.ReturnPacket(packet);
  472. return;
  473. }
  474. else if (packet.Type == PacketType.StartPingCheck)
  475. {
  476. StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
  477. CompletePingCheckPacket endPing = (CompletePingCheckPacket)PacketPool.Instance.GetPacket(PacketType.CompletePingCheck);
  478. endPing.PingID.PingID = startPing.PingID.PingID;
  479. OutPacket(endPing, ThrottleOutPacketType.Task);
  480. }
  481. else
  482. {
  483. LLQueItem item = new LLQueItem();
  484. item.Packet = packet;
  485. item.Incoming = true;
  486. m_PacketQueue.Enqueue(item);
  487. }
  488. }
  489. public void ProcessInPacket(LLQueItem item)
  490. {
  491. Packet packet = item.Packet;
  492. // Always ack the packet!
  493. //
  494. if (packet.Header.Reliable)
  495. AckPacket(packet);
  496. if (packet.Type != PacketType.AgentUpdate)
  497. m_PacketsReceived++;
  498. PruneDupeTracker();
  499. // Check for duplicate packets.. packets that the client is
  500. // resending because it didn't receive our ack
  501. //
  502. lock (m_DupeTracker)
  503. {
  504. if (m_DupeTracker.ContainsKey(packet.Header.Sequence))
  505. return;
  506. m_DupeTracker.Add(packet.Header.Sequence,
  507. Util.UnixTimeSinceEpoch());
  508. }
  509. m_Client.ProcessInPacket(packet);
  510. }
  511. public void Flush()
  512. {
  513. m_PacketQueue.Flush();
  514. m_UnackedBytes = (-1 * m_UnackedBytes);
  515. SendPacketStats();
  516. }
  517. public void Clear()
  518. {
  519. m_UnackedBytes = (-1 * m_UnackedBytes);
  520. SendPacketStats();
  521. m_NeedAck.Clear();
  522. m_PendingAcks.Clear();
  523. m_Sequence += 1000000;
  524. }
  525. private void ProcessAck(uint id)
  526. {
  527. LLQueItem data;
  528. lock (m_NeedAck)
  529. {
  530. //m_log.DebugFormat("[CLIENT]: In {0} received ack for packet {1}", m_Client.Scene.RegionInfo.ExternalEndPoint.Port, id);
  531. if (!m_NeedAck.TryGetValue(id, out data))
  532. return;
  533. m_NeedAck.Remove(id);
  534. PacketPool.Instance.ReturnPacket(data.Packet);
  535. m_UnackedBytes -= data.Length;
  536. }
  537. }
  538. // Allocate packet sequence numbers in a threadsave manner
  539. //
  540. protected uint NextPacketSequenceNumber()
  541. {
  542. // Set the sequence number
  543. uint seq = 1;
  544. lock (m_SequenceLock)
  545. {
  546. if (m_Sequence >= MAX_SEQUENCE)
  547. {
  548. m_Sequence = 1;
  549. }
  550. else
  551. {
  552. m_Sequence++;
  553. }
  554. seq = m_Sequence;
  555. }
  556. return seq;
  557. }
  558. public ClientInfo GetClientInfo()
  559. {
  560. ClientInfo info = new ClientInfo();
  561. info.pendingAcks = m_PendingAcks;
  562. info.needAck = new Dictionary<uint, byte[]>();
  563. lock (m_NeedAck)
  564. {
  565. foreach (uint key in m_NeedAck.Keys)
  566. info.needAck.Add(key, m_NeedAck[key].Packet.ToBytes());
  567. }
  568. LLQueItem[] queitems = m_PacketQueue.GetQueueArray();
  569. for (int i = 0; i < queitems.Length; i++)
  570. {
  571. if (queitems[i].Incoming == false)
  572. info.out_packets.Add(queitems[i].Packet.ToBytes());
  573. }
  574. info.sequence = m_Sequence;
  575. return info;
  576. }
  577. public void SetClientInfo(ClientInfo info)
  578. {
  579. m_PendingAcks = info.pendingAcks;
  580. m_NeedAck = new Dictionary<uint, LLQueItem>();
  581. Packet packet = null;
  582. int packetEnd = 0;
  583. byte[] zero = new byte[3000];
  584. foreach (uint key in info.needAck.Keys)
  585. {
  586. byte[] buff = info.needAck[key];
  587. packetEnd = buff.Length - 1;
  588. try
  589. {
  590. packet = PacketPool.Instance.GetPacket(buff, ref packetEnd, zero);
  591. }
  592. catch (Exception)
  593. {
  594. }
  595. LLQueItem item = new LLQueItem();
  596. item.Packet = packet;
  597. item.Incoming = false;
  598. item.throttleType = 0;
  599. item.TickCount = System.Environment.TickCount;
  600. item.Identifier = 0;
  601. item.Resends = 0;
  602. item.Length = packet.ToBytes().Length;
  603. m_NeedAck.Add(key, item);
  604. }
  605. m_Sequence = info.sequence;
  606. }
  607. public void AddImportantPacket(PacketType type)
  608. {
  609. if (m_ImportantPackets.Contains(type))
  610. return;
  611. m_ImportantPackets.Add(type);
  612. }
  613. public void RemoveImportantPacket(PacketType type)
  614. {
  615. if (!m_ImportantPackets.Contains(type))
  616. return;
  617. m_ImportantPackets.Remove(type);
  618. }
  619. private void DropResend(Object id)
  620. {
  621. foreach (LLQueItem data in new List<LLQueItem>(m_NeedAck.Values))
  622. {
  623. if (data.Identifier != null && data.Identifier == id)
  624. {
  625. m_NeedAck.Remove(data.Packet.Header.Sequence);
  626. PacketPool.Instance.ReturnPacket(data.Packet);
  627. return;
  628. }
  629. }
  630. }
  631. private void TriggerOnPacketDrop(Packet packet, Object id)
  632. {
  633. PacketDrop handlerPacketDrop = OnPacketDrop;
  634. if (handlerPacketDrop == null)
  635. return;
  636. handlerPacketDrop(packet, id);
  637. }
  638. // Convert the packet to bytes and stuff it onto the send queue
  639. //
  640. public void ProcessOutPacket(LLQueItem item)
  641. {
  642. Packet packet = item.Packet;
  643. // Assign sequence number here to prevent out of order packets
  644. if (packet.Header.Sequence == 0)
  645. {
  646. packet.Header.Sequence = NextPacketSequenceNumber();
  647. lock (m_NeedAck)
  648. {
  649. // We want to see that packet arrive if it's reliable
  650. if (packet.Header.Reliable)
  651. {
  652. m_UnackedBytes += item.Length;
  653. // Keep track of when this packet was sent out
  654. item.TickCount = System.Environment.TickCount;
  655. m_NeedAck[packet.Header.Sequence] = item;
  656. }
  657. }
  658. }
  659. // If we sent a killpacket
  660. if (packet is KillPacket)
  661. Abort();
  662. // Actually make the byte array and send it
  663. byte[] sendbuffer = item.Packet.ToBytes();
  664. //m_log.DebugFormat(
  665. // "[CLIENT]: In {0} sending packet {1}",
  666. // m_Client.Scene.RegionInfo.ExternalEndPoint.Port, packet.Header.Sequence);
  667. if (packet.Header.Zerocoded)
  668. {
  669. int packetsize = Helpers.ZeroEncode(sendbuffer,
  670. sendbuffer.Length, m_ZeroOutBuffer);
  671. m_PacketServer.SendPacketTo(m_ZeroOutBuffer, packetsize,
  672. SocketFlags.None, m_Client.CircuitCode);
  673. }
  674. else
  675. {
  676. // Need some extra space in case we need to add proxy
  677. // information to the message later
  678. Buffer.BlockCopy(sendbuffer, 0, m_ZeroOutBuffer, 0,
  679. sendbuffer.Length);
  680. m_PacketServer.SendPacketTo(m_ZeroOutBuffer,
  681. sendbuffer.Length, SocketFlags.None, m_Client.CircuitCode);
  682. }
  683. // If this is a reliable packet, we are still holding a ref
  684. // Dont't return in that case
  685. //
  686. if (!packet.Header.Reliable)
  687. PacketPool.Instance.ReturnPacket(packet);
  688. }
  689. private void Abort()
  690. {
  691. m_PacketQueue.Close();
  692. Thread.CurrentThread.Abort();
  693. }
  694. }
  695. }