LLUDPServer.cs 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  1. /*
  2. * Copyright (c) Contributors, http://opensimulator.org/
  3. * See CONTRIBUTORS.TXT for a full list of copyright holders.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. * * Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * * Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. * * Neither the name of the OpenSimulator Project nor the
  13. * names of its contributors may be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
  17. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
  20. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Collections.Generic;
  29. using System.Diagnostics;
  30. using System.IO;
  31. using System.Net;
  32. using System.Net.Sockets;
  33. using System.Reflection;
  34. using System.Threading;
  35. using log4net;
  36. using Nini.Config;
  37. using OpenMetaverse.Packets;
  38. using OpenSim.Framework;
  39. using OpenSim.Framework.Console;
  40. using OpenSim.Framework.Monitoring;
  41. using OpenSim.Region.Framework.Scenes;
  42. using OpenMetaverse;
  43. using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket;
  44. namespace OpenSim.Region.ClientStack.LindenUDP
  45. {
  46. /// <summary>
  47. /// A shim around LLUDPServer that implements the IClientNetworkServer interface
  48. /// </summary>
  49. public sealed class LLUDPServerShim : IClientNetworkServer
  50. {
  51. LLUDPServer m_udpServer;
  52. public LLUDPServerShim()
  53. {
  54. }
  55. public void Initialise(IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port, IConfigSource configSource, AgentCircuitManager circuitManager)
  56. {
  57. m_udpServer = new LLUDPServer(listenIP, ref port, proxyPortOffsetParm, allow_alternate_port, configSource, circuitManager);
  58. }
  59. public void AddScene(IScene scene)
  60. {
  61. m_udpServer.AddScene(scene);
  62. StatsManager.RegisterStat(
  63. new Stat(
  64. "ClientLogoutsDueToNoReceives",
  65. "Number of times a client has been logged out because no packets were received before the timeout.",
  66. "",
  67. "",
  68. "clientstack",
  69. scene.Name,
  70. StatType.Pull,
  71. MeasuresOfInterest.None,
  72. stat => stat.Value = m_udpServer.ClientLogoutsDueToNoReceives,
  73. StatVerbosity.Debug));
  74. StatsManager.RegisterStat(
  75. new Stat(
  76. "IncomingUDPReceivesCount",
  77. "Number of UDP receives performed",
  78. "",
  79. "",
  80. "clientstack",
  81. scene.Name,
  82. StatType.Pull,
  83. MeasuresOfInterest.AverageChangeOverTime,
  84. stat => stat.Value = m_udpServer.UdpReceives,
  85. StatVerbosity.Debug));
  86. StatsManager.RegisterStat(
  87. new Stat(
  88. "IncomingPacketsProcessedCount",
  89. "Number of inbound LL protocol packets processed",
  90. "",
  91. "",
  92. "clientstack",
  93. scene.Name,
  94. StatType.Pull,
  95. MeasuresOfInterest.AverageChangeOverTime,
  96. stat => stat.Value = m_udpServer.IncomingPacketsProcessed,
  97. StatVerbosity.Debug));
  98. StatsManager.RegisterStat(
  99. new Stat(
  100. "IncomingPacketsMalformedCount",
  101. "Number of inbound UDP packets that could not be recognized as LL protocol packets.",
  102. "",
  103. "",
  104. "clientstack",
  105. scene.Name,
  106. StatType.Pull,
  107. MeasuresOfInterest.AverageChangeOverTime,
  108. stat => stat.Value = m_udpServer.IncomingMalformedPacketCount,
  109. StatVerbosity.Info));
  110. StatsManager.RegisterStat(
  111. new Stat(
  112. "IncomingPacketsOrphanedCount",
  113. "Number of inbound packets that were not initial connections packets and could not be associated with a viewer.",
  114. "",
  115. "",
  116. "clientstack",
  117. scene.Name,
  118. StatType.Pull,
  119. MeasuresOfInterest.AverageChangeOverTime,
  120. stat => stat.Value = m_udpServer.IncomingOrphanedPacketCount,
  121. StatVerbosity.Info));
  122. StatsManager.RegisterStat(
  123. new Stat(
  124. "IncomingPacketsResentCount",
  125. "Number of inbound packets that clients indicate are resends.",
  126. "",
  127. "",
  128. "clientstack",
  129. scene.Name,
  130. StatType.Pull,
  131. MeasuresOfInterest.AverageChangeOverTime,
  132. stat => stat.Value = m_udpServer.IncomingPacketsResentCount,
  133. StatVerbosity.Debug));
  134. StatsManager.RegisterStat(
  135. new Stat(
  136. "OutgoingUDPSendsCount",
  137. "Number of UDP sends performed",
  138. "",
  139. "",
  140. "clientstack",
  141. scene.Name,
  142. StatType.Pull,
  143. MeasuresOfInterest.AverageChangeOverTime,
  144. stat => stat.Value = m_udpServer.UdpSends,
  145. StatVerbosity.Debug));
  146. StatsManager.RegisterStat(
  147. new Stat(
  148. "OutgoingPacketsResentCount",
  149. "Number of packets resent because a client did not acknowledge receipt",
  150. "",
  151. "",
  152. "clientstack",
  153. scene.Name,
  154. StatType.Pull,
  155. MeasuresOfInterest.AverageChangeOverTime,
  156. stat => stat.Value = m_udpServer.PacketsResentCount,
  157. StatVerbosity.Debug));
  158. StatsManager.RegisterStat(
  159. new Stat(
  160. "AverageUDPProcessTime",
  161. "Average number of milliseconds taken to process each incoming UDP packet in a sample.",
  162. "This is for initial receive processing which is separate from the later client LL packet processing stage.",
  163. "ms",
  164. "clientstack",
  165. scene.Name,
  166. StatType.Pull,
  167. MeasuresOfInterest.None,
  168. stat => stat.Value = m_udpServer.AverageReceiveTicksForLastSamplePeriod,
  169. // stat =>
  170. // stat.Value = Math.Round(m_udpServer.AverageReceiveTicksForLastSamplePeriod, 7),
  171. StatVerbosity.Debug));
  172. }
  173. public bool HandlesRegion(Location x)
  174. {
  175. return m_udpServer.HandlesRegion(x);
  176. }
  177. public void Start()
  178. {
  179. m_udpServer.Start();
  180. }
  181. public void Stop()
  182. {
  183. m_udpServer.Stop();
  184. }
  185. }
  186. /// <summary>
  187. /// The LLUDP server for a region. This handles incoming and outgoing
  188. /// packets for all UDP connections to the region
  189. /// </summary>
  190. public class LLUDPServer : OpenSimUDPBase
  191. {
  192. private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  193. /// <summary>Maximum transmission unit, or UDP packet size, for the LLUDP protocol</summary>
  194. public const int MTU = 1400;
  195. /// <summary>Number of forced client logouts due to no receipt of packets before timeout.</summary>
  196. public int ClientLogoutsDueToNoReceives { get; private set; }
  197. /// <summary>
  198. /// Default packet debug level given to new clients
  199. /// </summary>
  200. public int DefaultClientPacketDebugLevel { get; set; }
  201. /// <summary>
  202. /// If set then all inbound agent updates are discarded. For debugging purposes.
  203. /// discard agent update.
  204. /// </summary>
  205. public bool DiscardInboundAgentUpdates { get; set; }
  206. /// <summary>The measured resolution of Environment.TickCount</summary>
  207. public readonly float TickCountResolution;
  208. /// <summary>Number of prim updates to put on the queue each time the
  209. /// OnQueueEmpty event is triggered for updates</summary>
  210. public readonly int PrimUpdatesPerCallback;
  211. /// <summary>Number of texture packets to put on the queue each time the
  212. /// OnQueueEmpty event is triggered for textures</summary>
  213. public readonly int TextureSendLimit;
  214. /// <summary>Handlers for incoming packets</summary>
  215. //PacketEventDictionary packetEvents = new PacketEventDictionary();
  216. /// <summary>Incoming packets that are awaiting handling</summary>
  217. private OpenMetaverse.BlockingQueue<IncomingPacket> packetInbox = new OpenMetaverse.BlockingQueue<IncomingPacket>();
  218. /// <summary>Bandwidth throttle for this UDP server</summary>
  219. public TokenBucket Throttle { get; private set; }
  220. /// <summary>Per client throttle rates enforced by this server</summary>
  221. /// <remarks>
  222. /// If the total rate is non-zero, then this is the maximum total throttle setting that any client can ever have.
  223. /// The other rates (resend, asset, etc.) are the defaults for a new client and can be changed (and usually
  224. /// do get changed immediately). They do not need to sum to the total.
  225. /// </remarks>
  226. public ThrottleRates ThrottleRates { get; private set; }
  227. /// <summary>Manages authentication for agent circuits</summary>
  228. private AgentCircuitManager m_circuitManager;
  229. /// <summary>Reference to the scene this UDP server is attached to</summary>
  230. public Scene Scene { get; private set; }
  231. /// <summary>The X/Y coordinates of the scene this UDP server is attached to</summary>
  232. private Location m_location;
  233. /// <summary>The size of the receive buffer for the UDP socket. This value
  234. /// is passed up to the operating system and used in the system networking
  235. /// stack. Use zero to leave this value as the default</summary>
  236. private int m_recvBufferSize;
  237. /// <summary>Flag to process packets asynchronously or synchronously</summary>
  238. private bool m_asyncPacketHandling;
  239. /// <summary>Tracks whether or not a packet was sent each round so we know
  240. /// whether or not to sleep</summary>
  241. private bool m_packetSent;
  242. /// <summary>Environment.TickCount of the last time that packet stats were reported to the scene</summary>
  243. private int m_elapsedMSSinceLastStatReport = 0;
  244. /// <summary>Environment.TickCount of the last time the outgoing packet handler executed</summary>
  245. private int m_tickLastOutgoingPacketHandler;
  246. /// <summary>Keeps track of the number of elapsed milliseconds since the last time the outgoing packet handler looped</summary>
  247. private int m_elapsedMSOutgoingPacketHandler;
  248. /// <summary>Keeps track of the number of 100 millisecond periods elapsed in the outgoing packet handler executed</summary>
  249. private int m_elapsed100MSOutgoingPacketHandler;
  250. /// <summary>Keeps track of the number of 500 millisecond periods elapsed in the outgoing packet handler executed</summary>
  251. private int m_elapsed500MSOutgoingPacketHandler;
  252. /// <summary>Flag to signal when clients should check for resends</summary>
  253. protected bool m_resendUnacked;
  254. /// <summary>Flag to signal when clients should send ACKs</summary>
  255. protected bool m_sendAcks;
  256. /// <summary>Flag to signal when clients should send pings</summary>
  257. protected bool m_sendPing;
  258. /// <summary>
  259. /// Event used to signal when queued packets are available for sending.
  260. /// </summary>
  261. /// <remarks>
  262. /// This allows the outbound loop to only operate when there is data to send rather than continuously polling.
  263. /// Some data is sent immediately and not queued. That data would not trigger this event.
  264. /// </remarks>
  265. private AutoResetEvent m_dataPresentEvent = new AutoResetEvent(false);
  266. private Pool<IncomingPacket> m_incomingPacketPool;
  267. /// <summary>
  268. /// Stat for number of packets in the main pool awaiting use.
  269. /// </summary>
  270. private Stat m_poolCountStat;
  271. /// <summary>
  272. /// Stat for number of packets in the inbound packet pool awaiting use.
  273. /// </summary>
  274. private Stat m_incomingPacketPoolStat;
  275. private int m_defaultRTO = 0;
  276. private int m_maxRTO = 0;
  277. private int m_ackTimeout = 0;
  278. private int m_pausedAckTimeout = 0;
  279. private bool m_disableFacelights = false;
  280. public Socket Server { get { return null; } }
  281. /// <summary>
  282. /// Record how many packets have been resent
  283. /// </summary>
  284. internal int PacketsResentCount { get; set; }
  285. /// <summary>
  286. /// Record how many packets have been sent
  287. /// </summary>
  288. internal int PacketsSentCount { get; set; }
  289. /// <summary>
  290. /// Record how many incoming packets are indicated as resends by clients.
  291. /// </summary>
  292. internal int IncomingPacketsResentCount { get; set; }
  293. /// <summary>
  294. /// Record how many inbound packets could not be recognized as LLUDP packets.
  295. /// </summary>
  296. public int IncomingMalformedPacketCount { get; private set; }
  297. /// <summary>
  298. /// Record how many inbound packets could not be associated with a simulator circuit.
  299. /// </summary>
  300. public int IncomingOrphanedPacketCount { get; private set; }
  301. /// <summary>
  302. /// Record current outgoing client for monitoring purposes.
  303. /// </summary>
  304. private IClientAPI m_currentOutgoingClient;
  305. /// <summary>
  306. /// Recording current incoming client for monitoring purposes.
  307. /// </summary>
  308. private IClientAPI m_currentIncomingClient;
  309. /// <summary>
  310. /// Queue some low priority but potentially high volume async requests so that they don't overwhelm available
  311. /// threadpool threads.
  312. /// </summary>
  313. public JobEngine IpahEngine { get; private set; }
  314. /// <summary>
  315. /// Run queue empty processing within a single persistent thread.
  316. /// </summary>
  317. /// <remarks>
  318. /// This is the alternative to having every
  319. /// connection schedule its own job in the threadpool which causes performance problems when there are many
  320. /// connections.
  321. /// </remarks>
  322. public JobEngine OqrEngine { get; private set; }
  323. public LLUDPServer(
  324. IPAddress listenIP, ref uint port, int proxyPortOffsetParm, bool allow_alternate_port,
  325. IConfigSource configSource, AgentCircuitManager circuitManager)
  326. : base(listenIP, (int)port)
  327. {
  328. #region Environment.TickCount Measurement
  329. // Measure the resolution of Environment.TickCount
  330. TickCountResolution = 0f;
  331. for (int i = 0; i < 5; i++)
  332. {
  333. int start = Environment.TickCount;
  334. int now = start;
  335. while (now == start)
  336. now = Environment.TickCount;
  337. TickCountResolution += (float)(now - start) * 0.2f;
  338. }
  339. m_log.Info("[LLUDPSERVER]: Average Environment.TickCount resolution: " + TickCountResolution + "ms");
  340. TickCountResolution = (float)Math.Ceiling(TickCountResolution);
  341. #endregion Environment.TickCount Measurement
  342. m_circuitManager = circuitManager;
  343. int sceneThrottleBps = 0;
  344. bool usePools = false;
  345. IConfig config = configSource.Configs["ClientStack.LindenUDP"];
  346. if (config != null)
  347. {
  348. m_asyncPacketHandling = config.GetBoolean("async_packet_handling", true);
  349. m_recvBufferSize = config.GetInt("client_socket_rcvbuf_size", 0);
  350. sceneThrottleBps = config.GetInt("scene_throttle_max_bps", 0);
  351. PrimUpdatesPerCallback = config.GetInt("PrimUpdatesPerCallback", 100);
  352. TextureSendLimit = config.GetInt("TextureSendLimit", 20);
  353. m_defaultRTO = config.GetInt("DefaultRTO", 0);
  354. m_maxRTO = config.GetInt("MaxRTO", 0);
  355. m_disableFacelights = config.GetBoolean("DisableFacelights", false);
  356. m_ackTimeout = 1000 * config.GetInt("AckTimeout", 60);
  357. m_pausedAckTimeout = 1000 * config.GetInt("PausedAckTimeout", 300);
  358. }
  359. else
  360. {
  361. PrimUpdatesPerCallback = 100;
  362. TextureSendLimit = 20;
  363. m_ackTimeout = 1000 * 60; // 1 minute
  364. m_pausedAckTimeout = 1000 * 300; // 5 minutes
  365. }
  366. // FIXME: This actually only needs to be done once since the PacketPool is shared across all servers.
  367. // However, there is no harm in temporarily doing it multiple times.
  368. IConfig packetConfig = configSource.Configs["PacketPool"];
  369. if (packetConfig != null)
  370. {
  371. PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
  372. PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
  373. usePools = packetConfig.GetBoolean("RecycleBaseUDPPackets", usePools);
  374. }
  375. #region BinaryStats
  376. config = configSource.Configs["Statistics.Binary"];
  377. m_shouldCollectStats = false;
  378. if (config != null)
  379. {
  380. m_shouldCollectStats = config.GetBoolean("Enabled", false);
  381. binStatsMaxFilesize = TimeSpan.FromSeconds(config.GetInt("packet_headers_period_seconds", 300));
  382. binStatsDir = config.GetString("stats_dir", ".");
  383. m_aggregatedBWStats = config.GetBoolean("aggregatedBWStats", false);
  384. }
  385. #endregion BinaryStats
  386. // FIXME: Can't add info here because don't know scene yet.
  387. // m_throttle
  388. // = new TokenBucket(
  389. // string.Format("server throttle bucket for {0}", Scene.Name), null, sceneThrottleBps);
  390. Throttle = new TokenBucket("server throttle bucket", null, 0, sceneThrottleBps);
  391. ThrottleRates = new ThrottleRates(configSource);
  392. if (usePools)
  393. EnablePools();
  394. }
  395. public void Start()
  396. {
  397. StartInbound();
  398. StartOutbound();
  399. IpahEngine.Start();
  400. OqrEngine.Start();
  401. m_elapsedMSSinceLastStatReport = Environment.TickCount;
  402. }
  403. public void StartInbound()
  404. {
  405. m_log.InfoFormat(
  406. "[LLUDPSERVER]: Starting inbound packet processing for the LLUDP server in {0} mode with UsePools = {1}",
  407. m_asyncPacketHandling ? "asynchronous" : "synchronous", UsePools);
  408. base.StartInbound(m_recvBufferSize, m_asyncPacketHandling);
  409. // This thread will process the packets received that are placed on the packetInbox
  410. WorkManager.StartThread(
  411. IncomingPacketHandler,
  412. string.Format("Incoming Packets ({0})", Scene.Name),
  413. ThreadPriority.Normal,
  414. false,
  415. true,
  416. GetWatchdogIncomingAlarmData,
  417. Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS);
  418. }
  419. public override void StartOutbound()
  420. {
  421. m_log.Info("[LLUDPSERVER]: Starting outbound packet processing for the LLUDP server");
  422. base.StartOutbound();
  423. WorkManager.StartThread(
  424. OutgoingPacketHandler,
  425. string.Format("Outgoing Packets ({0})", Scene.Name),
  426. ThreadPriority.Normal,
  427. false,
  428. true,
  429. GetWatchdogOutgoingAlarmData,
  430. Watchdog.DEFAULT_WATCHDOG_TIMEOUT_MS);
  431. }
  432. public void Stop()
  433. {
  434. m_log.Info("[LLUDPSERVER]: Shutting down the LLUDP server for " + Scene.Name);
  435. base.StopOutbound();
  436. base.StopInbound();
  437. IpahEngine.Stop();
  438. OqrEngine.Stop();
  439. }
  440. public override bool EnablePools()
  441. {
  442. if (!UsePools)
  443. {
  444. base.EnablePools();
  445. m_incomingPacketPool = new Pool<IncomingPacket>(() => new IncomingPacket(), 500);
  446. return true;
  447. }
  448. return false;
  449. }
  450. public override bool DisablePools()
  451. {
  452. if (UsePools)
  453. {
  454. base.DisablePools();
  455. StatsManager.DeregisterStat(m_incomingPacketPoolStat);
  456. // We won't null out the pool to avoid a race condition with code that may be in the middle of using it.
  457. return true;
  458. }
  459. return false;
  460. }
  461. /// <summary>
  462. /// This is a seperate method so that it can be called once we have an m_scene to distinguish different scene
  463. /// stats.
  464. /// </summary>
  465. protected internal void EnablePoolStats()
  466. {
  467. m_poolCountStat
  468. = new Stat(
  469. "UDPPacketBufferPoolCount",
  470. "Objects within the UDPPacketBuffer pool",
  471. "The number of objects currently stored within the UDPPacketBuffer pool",
  472. "",
  473. "clientstack",
  474. Scene.Name,
  475. StatType.Pull,
  476. stat => stat.Value = Pool.Count,
  477. StatVerbosity.Debug);
  478. StatsManager.RegisterStat(m_poolCountStat);
  479. m_incomingPacketPoolStat
  480. = new Stat(
  481. "IncomingPacketPoolCount",
  482. "Objects within incoming packet pool",
  483. "The number of objects currently stored within the incoming packet pool",
  484. "",
  485. "clientstack",
  486. Scene.Name,
  487. StatType.Pull,
  488. stat => stat.Value = m_incomingPacketPool.Count,
  489. StatVerbosity.Debug);
  490. StatsManager.RegisterStat(m_incomingPacketPoolStat);
  491. }
  492. /// <summary>
  493. /// Disables pool stats.
  494. /// </summary>
  495. protected internal void DisablePoolStats()
  496. {
  497. StatsManager.DeregisterStat(m_poolCountStat);
  498. m_poolCountStat = null;
  499. StatsManager.DeregisterStat(m_incomingPacketPoolStat);
  500. m_incomingPacketPoolStat = null;
  501. }
  502. /// <summary>
  503. /// If the outgoing UDP thread times out, then return client that was being processed to help with debugging.
  504. /// </summary>
  505. /// <returns></returns>
  506. private string GetWatchdogIncomingAlarmData()
  507. {
  508. return string.Format(
  509. "Client is {0}",
  510. m_currentIncomingClient != null ? m_currentIncomingClient.Name : "none");
  511. }
  512. /// <summary>
  513. /// If the outgoing UDP thread times out, then return client that was being processed to help with debugging.
  514. /// </summary>
  515. /// <returns></returns>
  516. private string GetWatchdogOutgoingAlarmData()
  517. {
  518. return string.Format(
  519. "Client is {0}",
  520. m_currentOutgoingClient != null ? m_currentOutgoingClient.Name : "none");
  521. }
  522. public void AddScene(IScene scene)
  523. {
  524. if (Scene != null)
  525. {
  526. m_log.Error("[LLUDPSERVER]: AddScene() called on an LLUDPServer that already has a scene");
  527. return;
  528. }
  529. if (!(scene is Scene))
  530. {
  531. m_log.Error("[LLUDPSERVER]: AddScene() called with an unrecognized scene type " + scene.GetType());
  532. return;
  533. }
  534. Scene = (Scene)scene;
  535. m_location = new Location(Scene.RegionInfo.RegionHandle);
  536. IpahEngine
  537. = new JobEngine(
  538. string.Format("Incoming Packet Async Handling Engine ({0})", Scene.Name),
  539. "INCOMING PACKET ASYNC HANDLING ENGINE");
  540. OqrEngine
  541. = new JobEngine(
  542. string.Format("Outgoing Queue Refill Engine ({0})", Scene.Name),
  543. "OUTGOING QUEUE REFILL ENGINE");
  544. StatsManager.RegisterStat(
  545. new Stat(
  546. "InboxPacketsCount",
  547. "Number of LL protocol packets waiting for the second stage of processing after initial receive.",
  548. "Number of LL protocol packets waiting for the second stage of processing after initial receive.",
  549. "",
  550. "clientstack",
  551. scene.Name,
  552. StatType.Pull,
  553. MeasuresOfInterest.AverageChangeOverTime,
  554. stat => stat.Value = packetInbox.Count,
  555. StatVerbosity.Debug));
  556. // XXX: These stats are also pool stats but we register them separately since they are currently not
  557. // turned on and off by EnablePools()/DisablePools()
  558. StatsManager.RegisterStat(
  559. new PercentageStat(
  560. "PacketsReused",
  561. "Packets reused",
  562. "Number of packets reused out of all requests to the packet pool",
  563. "clientstack",
  564. Scene.Name,
  565. StatType.Pull,
  566. stat =>
  567. { PercentageStat pstat = (PercentageStat)stat;
  568. pstat.Consequent = PacketPool.Instance.PacketsRequested;
  569. pstat.Antecedent = PacketPool.Instance.PacketsReused; },
  570. StatVerbosity.Debug));
  571. StatsManager.RegisterStat(
  572. new PercentageStat(
  573. "PacketDataBlocksReused",
  574. "Packet data blocks reused",
  575. "Number of data blocks reused out of all requests to the packet pool",
  576. "clientstack",
  577. Scene.Name,
  578. StatType.Pull,
  579. stat =>
  580. { PercentageStat pstat = (PercentageStat)stat;
  581. pstat.Consequent = PacketPool.Instance.BlocksRequested;
  582. pstat.Antecedent = PacketPool.Instance.BlocksReused; },
  583. StatVerbosity.Debug));
  584. StatsManager.RegisterStat(
  585. new Stat(
  586. "PacketsPoolCount",
  587. "Objects within the packet pool",
  588. "The number of objects currently stored within the packet pool",
  589. "",
  590. "clientstack",
  591. Scene.Name,
  592. StatType.Pull,
  593. stat => stat.Value = PacketPool.Instance.PacketsPooled,
  594. StatVerbosity.Debug));
  595. StatsManager.RegisterStat(
  596. new Stat(
  597. "PacketDataBlocksPoolCount",
  598. "Objects within the packet data block pool",
  599. "The number of objects currently stored within the packet data block pool",
  600. "",
  601. "clientstack",
  602. Scene.Name,
  603. StatType.Pull,
  604. stat => stat.Value = PacketPool.Instance.BlocksPooled,
  605. StatVerbosity.Debug));
  606. StatsManager.RegisterStat(
  607. new Stat(
  608. "OutgoingPacketsQueuedCount",
  609. "Packets queued for outgoing send",
  610. "Number of queued outgoing packets across all connections",
  611. "",
  612. "clientstack",
  613. Scene.Name,
  614. StatType.Pull,
  615. MeasuresOfInterest.AverageChangeOverTime,
  616. stat => stat.Value = GetTotalQueuedOutgoingPackets(),
  617. StatVerbosity.Info));
  618. StatsManager.RegisterStat(
  619. new Stat(
  620. "IncomingPacketAsyncRequestsWaiting",
  621. "Number of incoming packets waiting for async processing in engine.",
  622. "",
  623. "",
  624. "clientstack",
  625. Scene.Name,
  626. StatType.Pull,
  627. MeasuresOfInterest.None,
  628. stat => stat.Value = IpahEngine.JobsWaiting,
  629. StatVerbosity.Debug));
  630. StatsManager.RegisterStat(
  631. new Stat(
  632. "OQRERequestsWaiting",
  633. "Number of outgong queue refill requests waiting for processing.",
  634. "",
  635. "",
  636. "clientstack",
  637. Scene.Name,
  638. StatType.Pull,
  639. MeasuresOfInterest.None,
  640. stat => stat.Value = OqrEngine.JobsWaiting,
  641. StatVerbosity.Debug));
  642. // We delay enabling pool stats to AddScene() instead of Initialize() so that we can distinguish pool stats by
  643. // scene name
  644. if (UsePools)
  645. EnablePoolStats();
  646. LLUDPServerCommands commands = new LLUDPServerCommands(MainConsole.Instance, this);
  647. commands.Register();
  648. }
  649. public bool HandlesRegion(Location x)
  650. {
  651. return x == m_location;
  652. }
  653. public int GetTotalQueuedOutgoingPackets()
  654. {
  655. int total = 0;
  656. foreach (ScenePresence sp in Scene.GetScenePresences())
  657. {
  658. // XXX: Need a better way to determine which IClientAPIs have UDPClients (NPCs do not, for instance).
  659. if (sp.ControllingClient is LLClientView)
  660. {
  661. LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient;
  662. total += udpClient.GetTotalPacketsQueuedCount();
  663. }
  664. }
  665. return total;
  666. }
  667. // public void BroadcastPacket(Packet packet, ThrottleOutPacketType category, bool sendToPausedAgents, bool allowSplitting)
  668. // {
  669. // // CoarseLocationUpdate and AvatarGroupsReply packets cannot be split in an automated way
  670. // if ((packet.Type == PacketType.CoarseLocationUpdate || packet.Type == PacketType.AvatarGroupsReply) && allowSplitting)
  671. // allowSplitting = false;
  672. //
  673. // if (allowSplitting && packet.HasVariableBlocks)
  674. // {
  675. // byte[][] datas = packet.ToBytesMultiple();
  676. // int packetCount = datas.Length;
  677. //
  678. // if (packetCount < 1)
  679. // m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
  680. //
  681. // for (int i = 0; i < packetCount; i++)
  682. // {
  683. // byte[] data = datas[i];
  684. // m_scene.ForEachClient(
  685. // delegate(IClientAPI client)
  686. // {
  687. // if (client is LLClientView)
  688. // SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category, null);
  689. // }
  690. // );
  691. // }
  692. // }
  693. // else
  694. // {
  695. // byte[] data = packet.ToBytes();
  696. // m_scene.ForEachClient(
  697. // delegate(IClientAPI client)
  698. // {
  699. // if (client is LLClientView)
  700. // SendPacketData(((LLClientView)client).UDPClient, data, packet.Type, category, null);
  701. // }
  702. // );
  703. // }
  704. // }
  705. /// <summary>
  706. /// Start the process of sending a packet to the client.
  707. /// </summary>
  708. /// <param name="udpClient"></param>
  709. /// <param name="packet"></param>
  710. /// <param name="category"></param>
  711. /// <param name="allowSplitting"></param>
  712. /// <param name="method">
  713. /// The method to call if the packet is not acked by the client. If null, then a standard
  714. /// resend of the packet is done.
  715. /// </param>
  716. public virtual void SendPacket(
  717. LLUDPClient udpClient, Packet packet, ThrottleOutPacketType category, bool allowSplitting, UnackedPacketMethod method)
  718. {
  719. // CoarseLocationUpdate packets cannot be split in an automated way
  720. if (packet.Type == PacketType.CoarseLocationUpdate && allowSplitting)
  721. allowSplitting = false;
  722. bool packetQueued = false;
  723. if (allowSplitting && packet.HasVariableBlocks)
  724. {
  725. byte[][] datas = packet.ToBytesMultiple();
  726. int packetCount = datas.Length;
  727. if (packetCount < 1)
  728. m_log.Error("[LLUDPSERVER]: Failed to split " + packet.Type + " with estimated length " + packet.Length);
  729. for (int i = 0; i < packetCount; i++)
  730. {
  731. byte[] data = datas[i];
  732. if (!SendPacketData(udpClient, data, packet.Type, category, method))
  733. packetQueued = true;
  734. }
  735. }
  736. else
  737. {
  738. byte[] data = packet.ToBytes();
  739. if (!SendPacketData(udpClient, data, packet.Type, category, method))
  740. packetQueued = true;
  741. }
  742. PacketPool.Instance.ReturnPacket(packet);
  743. if (packetQueued)
  744. m_dataPresentEvent.Set();
  745. }
  746. /// <summary>
  747. /// Start the process of sending a packet to the client.
  748. /// </summary>
  749. /// <param name="udpClient"></param>
  750. /// <param name="data"></param>
  751. /// <param name="type"></param>
  752. /// <param name="category"></param>
  753. /// <param name="method">
  754. /// The method to call if the packet is not acked by the client. If null, then a standard
  755. /// resend of the packet is done.
  756. /// </param>
  757. /// <returns>true if the data was sent immediately, false if it was queued for sending</returns>
  758. public bool SendPacketData(
  759. LLUDPClient udpClient, byte[] data, PacketType type, ThrottleOutPacketType category, UnackedPacketMethod method)
  760. {
  761. int dataLength = data.Length;
  762. bool doZerocode = (data[0] & Helpers.MSG_ZEROCODED) != 0;
  763. bool doCopy = true;
  764. // Frequency analysis of outgoing packet sizes shows a large clump of packets at each end of the spectrum.
  765. // The vast majority of packets are less than 200 bytes, although due to asset transfers and packet splitting
  766. // there are a decent number of packets in the 1000-1140 byte range. We allocate one of two sizes of data here
  767. // to accomodate for both common scenarios and provide ample room for ACK appending in both
  768. int bufferSize = (dataLength > 180) ? LLUDPServer.MTU : 200;
  769. UDPPacketBuffer buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
  770. // Zerocode if needed
  771. if (doZerocode)
  772. {
  773. try
  774. {
  775. dataLength = Helpers.ZeroEncode(data, dataLength, buffer.Data);
  776. doCopy = false;
  777. }
  778. catch (IndexOutOfRangeException)
  779. {
  780. // The packet grew larger than the bufferSize while zerocoding.
  781. // Remove the MSG_ZEROCODED flag and send the unencoded data
  782. // instead
  783. m_log.Debug("[LLUDPSERVER]: Packet exceeded buffer size during zerocoding for " + type + ". DataLength=" + dataLength +
  784. " and BufferLength=" + buffer.Data.Length + ". Removing MSG_ZEROCODED flag");
  785. data[0] = (byte)(data[0] & ~Helpers.MSG_ZEROCODED);
  786. }
  787. }
  788. // If the packet data wasn't already copied during zerocoding, copy it now
  789. if (doCopy)
  790. {
  791. if (dataLength <= buffer.Data.Length)
  792. {
  793. Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
  794. }
  795. else
  796. {
  797. bufferSize = dataLength;
  798. buffer = new UDPPacketBuffer(udpClient.RemoteEndPoint, bufferSize);
  799. // m_log.Error("[LLUDPSERVER]: Packet exceeded buffer size! This could be an indication of packet assembly not obeying the MTU. Type=" +
  800. // type + ", DataLength=" + dataLength + ", BufferLength=" + buffer.Data.Length + ". Dropping packet");
  801. Buffer.BlockCopy(data, 0, buffer.Data, 0, dataLength);
  802. }
  803. }
  804. buffer.DataLength = dataLength;
  805. #region Queue or Send
  806. OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category, null);
  807. // If we were not provided a method for handling unacked, use the UDPServer default method
  808. if ((outgoingPacket.Buffer.Data[0] & Helpers.MSG_RELIABLE) != 0)
  809. outgoingPacket.UnackedMethod = ((method == null) ? delegate(OutgoingPacket oPacket) { ResendUnacked(oPacket); } : method);
  810. // If a Linden Lab 1.23.5 client receives an update packet after a kill packet for an object, it will
  811. // continue to display the deleted object until relog. Therefore, we need to always queue a kill object
  812. // packet so that it isn't sent before a queued update packet.
  813. bool forceQueue = (type == PacketType.KillObject);
  814. // if (type == PacketType.ImprovedTerseObjectUpdate)
  815. // {
  816. // m_log.DebugFormat("Direct send ITOU to {0} in {1}", udpClient.AgentID, Scene.Name);
  817. // SendPacketFinal(outgoingPacket);
  818. // return false;
  819. // }
  820. // else
  821. // {
  822. if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, forceQueue))
  823. {
  824. SendPacketFinal(outgoingPacket);
  825. return true;
  826. }
  827. else
  828. {
  829. return false;
  830. }
  831. // }
  832. #endregion Queue or Send
  833. }
  834. public void SendAcks(LLUDPClient udpClient)
  835. {
  836. uint ack;
  837. if (udpClient.PendingAcks.Dequeue(out ack))
  838. {
  839. List<PacketAckPacket.PacketsBlock> blocks = new List<PacketAckPacket.PacketsBlock>();
  840. PacketAckPacket.PacketsBlock block = new PacketAckPacket.PacketsBlock();
  841. block.ID = ack;
  842. blocks.Add(block);
  843. while (udpClient.PendingAcks.Dequeue(out ack))
  844. {
  845. block = new PacketAckPacket.PacketsBlock();
  846. block.ID = ack;
  847. blocks.Add(block);
  848. }
  849. PacketAckPacket packet = new PacketAckPacket();
  850. packet.Header.Reliable = false;
  851. packet.Packets = blocks.ToArray();
  852. SendPacket(udpClient, packet, ThrottleOutPacketType.Unknown, true, null);
  853. }
  854. }
  855. public void SendPing(LLUDPClient udpClient)
  856. {
  857. StartPingCheckPacket pc = (StartPingCheckPacket)PacketPool.Instance.GetPacket(PacketType.StartPingCheck);
  858. pc.Header.Reliable = false;
  859. pc.PingID.PingID = (byte)udpClient.CurrentPingSequence++;
  860. // We *could* get OldestUnacked, but it would hurt performance and not provide any benefit
  861. pc.PingID.OldestUnacked = 0;
  862. SendPacket(udpClient, pc, ThrottleOutPacketType.Unknown, false, null);
  863. }
  864. public void CompletePing(LLUDPClient udpClient, byte pingID)
  865. {
  866. CompletePingCheckPacket completePing = new CompletePingCheckPacket();
  867. completePing.PingID.PingID = pingID;
  868. SendPacket(udpClient, completePing, ThrottleOutPacketType.Unknown, false, null);
  869. }
  870. public void HandleUnacked(LLClientView client)
  871. {
  872. LLUDPClient udpClient = client.UDPClient;
  873. if (!udpClient.IsConnected)
  874. return;
  875. // Disconnect an agent if no packets are received for some time
  876. int timeoutTicks = m_ackTimeout;
  877. // Allow more slack if the client is "paused" eg file upload dialogue is open
  878. // Some sort of limit is needed in case the client crashes, loses its network connection
  879. // or some other disaster prevents it from sendung the AgentResume
  880. if (udpClient.IsPaused)
  881. timeoutTicks = m_pausedAckTimeout;
  882. if (client.IsActive &&
  883. (Environment.TickCount & Int32.MaxValue) - udpClient.TickLastPacketReceived > timeoutTicks)
  884. {
  885. // We must set IsActive synchronously so that we can stop the packet loop reinvoking this method, even
  886. // though it's set later on by LLClientView.Close()
  887. client.IsActive = false;
  888. // Fire this out on a different thread so that we don't hold up outgoing packet processing for
  889. // everybody else if this is being called due to an ack timeout.
  890. // This is the same as processing as the async process of a logout request.
  891. Util.FireAndForget(
  892. o => DeactivateClientDueToTimeout(client, timeoutTicks), null, "LLUDPServer.DeactivateClientDueToTimeout");
  893. return;
  894. }
  895. // Get a list of all of the packets that have been sitting unacked longer than udpClient.RTO
  896. List<OutgoingPacket> expiredPackets = udpClient.NeedAcks.GetExpiredPackets(udpClient.RTO);
  897. if (expiredPackets != null)
  898. {
  899. //m_log.Debug("[LLUDPSERVER]: Handling " + expiredPackets.Count + " packets to " + udpClient.AgentID + ", RTO=" + udpClient.RTO);
  900. // Exponential backoff of the retransmission timeout
  901. udpClient.BackoffRTO();
  902. for (int i = 0; i < expiredPackets.Count; ++i)
  903. expiredPackets[i].UnackedMethod(expiredPackets[i]);
  904. }
  905. }
  906. public void ResendUnacked(OutgoingPacket outgoingPacket)
  907. {
  908. //m_log.DebugFormat("[LLUDPSERVER]: Resending packet #{0} (attempt {1}), {2}ms have passed",
  909. // outgoingPacket.SequenceNumber, outgoingPacket.ResendCount, Environment.TickCount - outgoingPacket.TickCount);
  910. // Set the resent flag
  911. outgoingPacket.Buffer.Data[0] = (byte)(outgoingPacket.Buffer.Data[0] | Helpers.MSG_RESENT);
  912. outgoingPacket.Category = ThrottleOutPacketType.Resend;
  913. // Bump up the resend count on this packet
  914. Interlocked.Increment(ref outgoingPacket.ResendCount);
  915. // Requeue or resend the packet
  916. if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, false))
  917. SendPacketFinal(outgoingPacket);
  918. }
  919. public void Flush(LLUDPClient udpClient)
  920. {
  921. // FIXME: Implement?
  922. }
  923. /// <summary>
  924. /// Actually send a packet to a client.
  925. /// </summary>
  926. /// <param name="outgoingPacket"></param>
  927. internal void SendPacketFinal(OutgoingPacket outgoingPacket)
  928. {
  929. UDPPacketBuffer buffer = outgoingPacket.Buffer;
  930. byte flags = buffer.Data[0];
  931. bool isResend = (flags & Helpers.MSG_RESENT) != 0;
  932. bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
  933. bool isZerocoded = (flags & Helpers.MSG_ZEROCODED) != 0;
  934. LLUDPClient udpClient = outgoingPacket.Client;
  935. if (!udpClient.IsConnected)
  936. return;
  937. #region ACK Appending
  938. int dataLength = buffer.DataLength;
  939. // NOTE: I'm seeing problems with some viewers when ACKs are appended to zerocoded packets so I've disabled that here
  940. if (!isZerocoded)
  941. {
  942. // Keep appending ACKs until there is no room left in the buffer or there are
  943. // no more ACKs to append
  944. uint ackCount = 0;
  945. uint ack;
  946. while (dataLength + 5 < buffer.Data.Length && udpClient.PendingAcks.Dequeue(out ack))
  947. {
  948. Utils.UIntToBytesBig(ack, buffer.Data, dataLength);
  949. dataLength += 4;
  950. ++ackCount;
  951. }
  952. if (ackCount > 0)
  953. {
  954. // Set the last byte of the packet equal to the number of appended ACKs
  955. buffer.Data[dataLength++] = (byte)ackCount;
  956. // Set the appended ACKs flag on this packet
  957. buffer.Data[0] = (byte)(buffer.Data[0] | Helpers.MSG_APPENDED_ACKS);
  958. }
  959. }
  960. buffer.DataLength = dataLength;
  961. #endregion ACK Appending
  962. #region Sequence Number Assignment
  963. if (!isResend)
  964. {
  965. // Not a resend, assign a new sequence number
  966. uint sequenceNumber = (uint)Interlocked.Increment(ref udpClient.CurrentSequence);
  967. Utils.UIntToBytesBig(sequenceNumber, buffer.Data, 1);
  968. outgoingPacket.SequenceNumber = sequenceNumber;
  969. if (udpClient.ProcessUnackedSends && isReliable)
  970. {
  971. // Add this packet to the list of ACK responses we are waiting on from the server
  972. udpClient.NeedAcks.Add(outgoingPacket);
  973. }
  974. }
  975. else
  976. {
  977. Interlocked.Increment(ref udpClient.PacketsResent);
  978. // We're not going to worry about interlock yet since its not currently critical that this total count
  979. // is 100% correct
  980. PacketsResentCount++;
  981. }
  982. #endregion Sequence Number Assignment
  983. // Stats tracking
  984. Interlocked.Increment(ref udpClient.PacketsSent);
  985. // We're not going to worry about interlock yet since its not currently critical that this total count
  986. // is 100% correct
  987. PacketsSentCount++;
  988. if (udpClient.DebugDataOutLevel > 0)
  989. m_log.DebugFormat(
  990. "[LLUDPSERVER]: Sending packet #{0} (rel: {1}, res: {2}) to {3} from {4}",
  991. outgoingPacket.SequenceNumber, isReliable, isResend, udpClient.AgentID, Scene.Name);
  992. // Put the UDP payload on the wire
  993. AsyncBeginSend(buffer);
  994. // Keep track of when this packet was sent out (right now)
  995. outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
  996. }
  997. private void RecordMalformedInboundPacket(IPEndPoint endPoint)
  998. {
  999. // if (m_malformedCount < 100)
  1000. // m_log.DebugFormat("[LLUDPSERVER]: Dropped malformed packet: " + e.ToString());
  1001. IncomingMalformedPacketCount++;
  1002. if ((IncomingMalformedPacketCount % 10000) == 0)
  1003. m_log.WarnFormat(
  1004. "[LLUDPSERVER]: Received {0} malformed packets so far, probable network attack. Last was from {1}",
  1005. IncomingMalformedPacketCount, endPoint);
  1006. }
  1007. public override void PacketReceived(UDPPacketBuffer buffer)
  1008. {
  1009. // Debugging/Profiling
  1010. //try { Thread.CurrentThread.Name = "PacketReceived (" + m_scene.RegionInfo.RegionName + ")"; }
  1011. //catch (Exception) { }
  1012. // m_log.DebugFormat(
  1013. // "[LLUDPSERVER]: Packet received from {0} in {1}", buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);
  1014. LLUDPClient udpClient = null;
  1015. Packet packet = null;
  1016. int packetEnd = buffer.DataLength - 1;
  1017. IPEndPoint endPoint = (IPEndPoint)buffer.RemoteEndPoint;
  1018. #region Decoding
  1019. if (buffer.DataLength < 7)
  1020. {
  1021. // m_log.WarnFormat(
  1022. // "[LLUDPSERVER]: Dropping undersized packet with {0} bytes received from {1} in {2}",
  1023. // buffer.DataLength, buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);
  1024. RecordMalformedInboundPacket(endPoint);
  1025. return; // Drop undersized packet
  1026. }
  1027. int headerLen = 7;
  1028. if (buffer.Data[6] == 0xFF)
  1029. {
  1030. if (buffer.Data[7] == 0xFF)
  1031. headerLen = 10;
  1032. else
  1033. headerLen = 8;
  1034. }
  1035. if (buffer.DataLength < headerLen)
  1036. {
  1037. // m_log.WarnFormat(
  1038. // "[LLUDPSERVER]: Dropping packet with malformed header received from {0} in {1}",
  1039. // buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);
  1040. RecordMalformedInboundPacket(endPoint);
  1041. return; // Malformed header
  1042. }
  1043. try
  1044. {
  1045. // packet = Packet.BuildPacket(buffer.Data, ref packetEnd,
  1046. // // Only allocate a buffer for zerodecoding if the packet is zerocoded
  1047. // ((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0) ? new byte[4096] : null);
  1048. // If OpenSimUDPBase.UsePool == true (which is currently separate from the PacketPool) then we
  1049. // assume that packet construction does not retain a reference to byte[] buffer.Data (instead, all
  1050. // bytes are copied out).
  1051. packet = PacketPool.Instance.GetPacket(buffer.Data, ref packetEnd,
  1052. // Only allocate a buffer for zerodecoding if the packet is zerocoded
  1053. ((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0) ? new byte[4096] : null);
  1054. }
  1055. catch (Exception e)
  1056. {
  1057. if (IncomingMalformedPacketCount < 100)
  1058. m_log.DebugFormat("[LLUDPSERVER]: Dropped malformed packet: " + e.ToString());
  1059. }
  1060. // Fail-safe check
  1061. if (packet == null)
  1062. {
  1063. if (IncomingMalformedPacketCount < 100)
  1064. {
  1065. m_log.WarnFormat("[LLUDPSERVER]: Malformed data, cannot parse {0} byte packet from {1}, data {2}:",
  1066. buffer.DataLength, buffer.RemoteEndPoint, Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
  1067. }
  1068. RecordMalformedInboundPacket(endPoint);
  1069. return;
  1070. }
  1071. #endregion Decoding
  1072. #region Packet to Client Mapping
  1073. // UseCircuitCode handling
  1074. if (packet.Type == PacketType.UseCircuitCode)
  1075. {
  1076. // We need to copy the endpoint so that it doesn't get changed when another thread reuses the
  1077. // buffer.
  1078. object[] array = new object[] { new IPEndPoint(endPoint.Address, endPoint.Port), packet };
  1079. Util.FireAndForget(HandleUseCircuitCode, array, "LLUDPServer.HandleUseCircuitCode");
  1080. return;
  1081. }
  1082. else if (packet.Type == PacketType.CompleteAgentMovement)
  1083. {
  1084. // Send ack straight away to let the viewer know that we got it.
  1085. SendAckImmediate(endPoint, packet.Header.Sequence);
  1086. // We need to copy the endpoint so that it doesn't get changed when another thread reuses the
  1087. // buffer.
  1088. object[] array = new object[] { new IPEndPoint(endPoint.Address, endPoint.Port), packet };
  1089. Util.FireAndForget(
  1090. HandleCompleteMovementIntoRegion, array, "LLUDPServer.HandleCompleteMovementIntoRegion");
  1091. return;
  1092. }
  1093. // Determine which agent this packet came from
  1094. IClientAPI client;
  1095. if (!Scene.TryGetClient(endPoint, out client) || !(client is LLClientView))
  1096. {
  1097. //m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet from an unrecognized source: " + address + " in " + m_scene.RegionInfo.RegionName);
  1098. IncomingOrphanedPacketCount++;
  1099. if ((IncomingOrphanedPacketCount % 10000) == 0)
  1100. m_log.WarnFormat(
  1101. "[LLUDPSERVER]: Received {0} orphaned packets so far. Last was from {1}",
  1102. IncomingOrphanedPacketCount, endPoint);
  1103. return;
  1104. }
  1105. udpClient = ((LLClientView)client).UDPClient;
  1106. if (!udpClient.IsConnected)
  1107. return;
  1108. #endregion Packet to Client Mapping
  1109. // Stats tracking
  1110. Interlocked.Increment(ref udpClient.PacketsReceived);
  1111. int now = Environment.TickCount & Int32.MaxValue;
  1112. udpClient.TickLastPacketReceived = now;
  1113. #region ACK Receiving
  1114. if (udpClient.ProcessUnackedSends)
  1115. {
  1116. // Handle appended ACKs
  1117. if (packet.Header.AppendedAcks && packet.Header.AckList != null)
  1118. {
  1119. // m_log.DebugFormat(
  1120. // "[LLUDPSERVER]: Handling {0} appended acks from {1} in {2}",
  1121. // packet.Header.AckList.Length, client.Name, m_scene.Name);
  1122. for (int i = 0; i < packet.Header.AckList.Length; i++)
  1123. udpClient.NeedAcks.Acknowledge(packet.Header.AckList[i], now, packet.Header.Resent);
  1124. }
  1125. // Handle PacketAck packets
  1126. if (packet.Type == PacketType.PacketAck)
  1127. {
  1128. PacketAckPacket ackPacket = (PacketAckPacket)packet;
  1129. // m_log.DebugFormat(
  1130. // "[LLUDPSERVER]: Handling {0} packet acks for {1} in {2}",
  1131. // ackPacket.Packets.Length, client.Name, m_scene.Name);
  1132. for (int i = 0; i < ackPacket.Packets.Length; i++)
  1133. udpClient.NeedAcks.Acknowledge(ackPacket.Packets[i].ID, now, packet.Header.Resent);
  1134. // We don't need to do anything else with PacketAck packets
  1135. return;
  1136. }
  1137. }
  1138. else if (packet.Type == PacketType.PacketAck)
  1139. {
  1140. return;
  1141. }
  1142. #endregion ACK Receiving
  1143. #region ACK Sending
  1144. if (packet.Header.Reliable)
  1145. {
  1146. // m_log.DebugFormat(
  1147. // "[LLUDPSERVER]: Adding ack request for {0} {1} from {2} in {3}",
  1148. // packet.Type, packet.Header.Sequence, client.Name, m_scene.Name);
  1149. udpClient.PendingAcks.Enqueue(packet.Header.Sequence);
  1150. // This is a somewhat odd sequence of steps to pull the client.BytesSinceLastACK value out,
  1151. // add the current received bytes to it, test if 2*MTU bytes have been sent, if so remove
  1152. // 2*MTU bytes from the value and send ACKs, and finally add the local value back to
  1153. // client.BytesSinceLastACK. Lockless thread safety
  1154. int bytesSinceLastACK = Interlocked.Exchange(ref udpClient.BytesSinceLastACK, 0);
  1155. bytesSinceLastACK += buffer.DataLength;
  1156. if (bytesSinceLastACK > LLUDPServer.MTU * 2)
  1157. {
  1158. bytesSinceLastACK -= LLUDPServer.MTU * 2;
  1159. SendAcks(udpClient);
  1160. }
  1161. Interlocked.Add(ref udpClient.BytesSinceLastACK, bytesSinceLastACK);
  1162. }
  1163. #endregion ACK Sending
  1164. #region Incoming Packet Accounting
  1165. // We're not going to worry about interlock yet since its not currently critical that this total count
  1166. // is 100% correct
  1167. if (packet.Header.Resent)
  1168. IncomingPacketsResentCount++;
  1169. // Check the archive of received reliable packet IDs to see whether we already received this packet
  1170. if (packet.Header.Reliable && !udpClient.PacketArchive.TryEnqueue(packet.Header.Sequence))
  1171. {
  1172. if (packet.Header.Resent)
  1173. m_log.DebugFormat(
  1174. "[LLUDPSERVER]: Received a resend of already processed packet #{0}, type {1} from {2}",
  1175. packet.Header.Sequence, packet.Type, client.Name);
  1176. else
  1177. m_log.WarnFormat(
  1178. "[LLUDPSERVER]: Received a duplicate (not marked as resend) of packet #{0}, type {1} from {2}",
  1179. packet.Header.Sequence, packet.Type, client.Name);
  1180. // Avoid firing a callback twice for the same packet
  1181. return;
  1182. }
  1183. #endregion Incoming Packet Accounting
  1184. #region BinaryStats
  1185. LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
  1186. #endregion BinaryStats
  1187. if (packet.Type == PacketType.AgentUpdate)
  1188. {
  1189. if (DiscardInboundAgentUpdates)
  1190. return;
  1191. ((LLClientView)client).TotalAgentUpdates++;
  1192. AgentUpdatePacket agentUpdate = (AgentUpdatePacket)packet;
  1193. LLClientView llClient = client as LLClientView;
  1194. if (agentUpdate.AgentData.SessionID != client.SessionId
  1195. || agentUpdate.AgentData.AgentID != client.AgentId
  1196. || !(llClient == null || llClient.CheckAgentUpdateSignificance(agentUpdate.AgentData)) )
  1197. {
  1198. PacketPool.Instance.ReturnPacket(packet);
  1199. return;
  1200. }
  1201. }
  1202. #region Ping Check Handling
  1203. if (packet.Type == PacketType.StartPingCheck)
  1204. {
  1205. // m_log.DebugFormat("[LLUDPSERVER]: Handling ping from {0} in {1}", client.Name, m_scene.Name);
  1206. // We don't need to do anything else with ping checks
  1207. StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
  1208. CompletePing(udpClient, startPing.PingID.PingID);
  1209. if ((Environment.TickCount - m_elapsedMSSinceLastStatReport) >= 3000)
  1210. {
  1211. udpClient.SendPacketStats();
  1212. m_elapsedMSSinceLastStatReport = Environment.TickCount;
  1213. }
  1214. return;
  1215. }
  1216. else if (packet.Type == PacketType.CompletePingCheck)
  1217. {
  1218. // We don't currently track client ping times
  1219. return;
  1220. }
  1221. #endregion Ping Check Handling
  1222. IncomingPacket incomingPacket;
  1223. // Inbox insertion
  1224. if (UsePools)
  1225. {
  1226. incomingPacket = m_incomingPacketPool.GetObject();
  1227. incomingPacket.Client = (LLClientView)client;
  1228. incomingPacket.Packet = packet;
  1229. }
  1230. else
  1231. {
  1232. incomingPacket = new IncomingPacket((LLClientView)client, packet);
  1233. }
  1234. packetInbox.Enqueue(incomingPacket);
  1235. }
  1236. #region BinaryStats
  1237. public class PacketLogger
  1238. {
  1239. public DateTime StartTime;
  1240. public string Path = null;
  1241. public System.IO.BinaryWriter Log = null;
  1242. }
  1243. public static PacketLogger PacketLog;
  1244. protected static bool m_shouldCollectStats = false;
  1245. // Number of seconds to log for
  1246. static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
  1247. static object binStatsLogLock = new object();
  1248. static string binStatsDir = "";
  1249. //for Aggregated In/Out BW logging
  1250. static bool m_aggregatedBWStats = false;
  1251. static long m_aggregatedBytesIn = 0;
  1252. static long m_aggregatedByestOut = 0;
  1253. static object aggBWStatsLock = new object();
  1254. public static long AggregatedLLUDPBytesIn
  1255. {
  1256. get { return m_aggregatedBytesIn; }
  1257. }
  1258. public static long AggregatedLLUDPBytesOut
  1259. {
  1260. get {return m_aggregatedByestOut;}
  1261. }
  1262. public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
  1263. {
  1264. if (m_aggregatedBWStats)
  1265. {
  1266. lock (aggBWStatsLock)
  1267. {
  1268. if (incoming)
  1269. m_aggregatedBytesIn += size;
  1270. else
  1271. m_aggregatedByestOut += size;
  1272. }
  1273. }
  1274. if (!m_shouldCollectStats) return;
  1275. // Binary logging format is TTTTTTTTCCCCFPPPSS, T=Time, C=Circuit, F=Flags, P=PacketType, S=size
  1276. // Put the incoming bit into the least significant bit of the flags byte
  1277. if (incoming)
  1278. flags |= 0x01;
  1279. else
  1280. flags &= 0xFE;
  1281. // Put the flags byte into the most significant bits of the type integer
  1282. uint type = (uint)packetType;
  1283. type |= (uint)flags << 24;
  1284. // m_log.Debug("1 LogPacketHeader(): Outside lock");
  1285. lock (binStatsLogLock)
  1286. {
  1287. DateTime now = DateTime.Now;
  1288. // m_log.Debug("2 LogPacketHeader(): Inside lock. now is " + now.Ticks);
  1289. try
  1290. {
  1291. if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
  1292. {
  1293. if (PacketLog != null && PacketLog.Log != null)
  1294. {
  1295. PacketLog.Log.Close();
  1296. }
  1297. // First log file or time has expired, start writing to a new log file
  1298. PacketLog = new PacketLogger();
  1299. PacketLog.StartTime = now;
  1300. PacketLog.Path = (binStatsDir.Length > 0 ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
  1301. + String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
  1302. PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
  1303. }
  1304. // Serialize the data
  1305. byte[] output = new byte[18];
  1306. Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
  1307. Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
  1308. Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
  1309. Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);
  1310. // Write the serialized data to disk
  1311. if (PacketLog != null && PacketLog.Log != null)
  1312. PacketLog.Log.Write(output);
  1313. }
  1314. catch (Exception ex)
  1315. {
  1316. m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
  1317. if (PacketLog.Log != null)
  1318. {
  1319. PacketLog.Log.Close();
  1320. }
  1321. PacketLog = null;
  1322. }
  1323. }
  1324. }
  1325. #endregion BinaryStats
  1326. private void HandleUseCircuitCode(object o)
  1327. {
  1328. IPEndPoint endPoint = null;
  1329. IClientAPI client = null;
  1330. try
  1331. {
  1332. // DateTime startTime = DateTime.Now;
  1333. object[] array = (object[])o;
  1334. endPoint = (IPEndPoint)array[0];
  1335. UseCircuitCodePacket uccp = (UseCircuitCodePacket)array[1];
  1336. m_log.DebugFormat(
  1337. "[LLUDPSERVER]: Handling UseCircuitCode request for circuit {0} to {1} from IP {2}",
  1338. uccp.CircuitCode.Code, Scene.RegionInfo.RegionName, endPoint);
  1339. AuthenticateResponse sessionInfo;
  1340. if (IsClientAuthorized(uccp, out sessionInfo))
  1341. {
  1342. // Begin the process of adding the client to the simulator
  1343. client
  1344. = AddClient(
  1345. uccp.CircuitCode.Code,
  1346. uccp.CircuitCode.ID,
  1347. uccp.CircuitCode.SessionID,
  1348. endPoint,
  1349. sessionInfo);
  1350. // Send ack straight away to let the viewer know that the connection is active.
  1351. // The client will be null if it already exists (e.g. if on a region crossing the client sends a use
  1352. // circuit code to the existing child agent. This is not particularly obvious.
  1353. SendAckImmediate(endPoint, uccp.Header.Sequence);
  1354. // We only want to send initial data to new clients, not ones which are being converted from child to root.
  1355. if (client != null)
  1356. {
  1357. AgentCircuitData aCircuit = Scene.AuthenticateHandler.GetAgentCircuitData(uccp.CircuitCode.Code);
  1358. bool tp = (aCircuit.teleportFlags > 0);
  1359. // Let's delay this for TP agents, otherwise the viewer doesn't know where to get resources from
  1360. if (!tp && !client.SceneAgent.SentInitialDataToClient)
  1361. client.SceneAgent.SendInitialDataToClient();
  1362. }
  1363. }
  1364. else
  1365. {
  1366. // Don't create clients for unauthorized requesters.
  1367. m_log.WarnFormat(
  1368. "[LLUDPSERVER]: Ignoring connection request for {0} to {1} with unknown circuit code {2} from IP {3}",
  1369. uccp.CircuitCode.ID, Scene.RegionInfo.RegionName, uccp.CircuitCode.Code, endPoint);
  1370. }
  1371. // m_log.DebugFormat(
  1372. // "[LLUDPSERVER]: Handling UseCircuitCode request from {0} took {1}ms",
  1373. // buffer.RemoteEndPoint, (DateTime.Now - startTime).Milliseconds);
  1374. }
  1375. catch (Exception e)
  1376. {
  1377. m_log.ErrorFormat(
  1378. "[LLUDPSERVER]: UseCircuitCode handling from endpoint {0}, client {1} {2} failed. Exception {3}{4}",
  1379. endPoint != null ? endPoint.ToString() : "n/a",
  1380. client != null ? client.Name : "unknown",
  1381. client != null ? client.AgentId.ToString() : "unknown",
  1382. e.Message,
  1383. e.StackTrace);
  1384. }
  1385. }
  1386. private void HandleCompleteMovementIntoRegion(object o)
  1387. {
  1388. IPEndPoint endPoint = null;
  1389. IClientAPI client = null;
  1390. try
  1391. {
  1392. object[] array = (object[])o;
  1393. endPoint = (IPEndPoint)array[0];
  1394. CompleteAgentMovementPacket packet = (CompleteAgentMovementPacket)array[1];
  1395. m_log.DebugFormat(
  1396. "[LLUDPSERVER]: Handling CompleteAgentMovement request from {0} in {1}", endPoint, Scene.Name);
  1397. // Determine which agent this packet came from
  1398. // We need to wait here because in when using the OpenSimulator V2 teleport protocol to travel to a destination
  1399. // simulator with no existing child presence, the viewer (at least LL 3.3.4) will send UseCircuitCode
  1400. // and then CompleteAgentMovement immediately without waiting for an ack. As we are now handling these
  1401. // packets asynchronously, we need to account for this thread proceeding more quickly than the
  1402. // UseCircuitCode thread.
  1403. int count = 40;
  1404. while (count-- > 0)
  1405. {
  1406. if (Scene.TryGetClient(endPoint, out client))
  1407. {
  1408. if (!client.IsActive)
  1409. {
  1410. // This check exists to catch a condition where the client has been closed by another thread
  1411. // but has not yet been removed from the client manager (and possibly a new connection has
  1412. // not yet been established).
  1413. m_log.DebugFormat(
  1414. "[LLUDPSERVER]: Received a CompleteAgentMovement from {0} for {1} in {2} but client is not active yet. Waiting.",
  1415. endPoint, client.Name, Scene.Name);
  1416. }
  1417. else if (client.SceneAgent == null)
  1418. {
  1419. // This check exists to catch a condition where the new client has been added to the client
  1420. // manager but the SceneAgent has not yet been set in Scene.AddNewAgent(). If we are too
  1421. // eager, then the new ScenePresence may not have registered a listener for this messsage
  1422. // before we try to process it.
  1423. // XXX: A better long term fix may be to add the SceneAgent before the client is added to
  1424. // the client manager
  1425. m_log.DebugFormat(
  1426. "[LLUDPSERVER]: Received a CompleteAgentMovement from {0} for {1} in {2} but client SceneAgent not set yet. Waiting.",
  1427. endPoint, client.Name, Scene.Name);
  1428. }
  1429. else
  1430. {
  1431. break;
  1432. }
  1433. }
  1434. else
  1435. {
  1436. m_log.DebugFormat(
  1437. "[LLUDPSERVER]: Received a CompleteAgentMovement from {0} in {1} but no client exists yet. Waiting.",
  1438. endPoint, Scene.Name);
  1439. }
  1440. Thread.Sleep(200);
  1441. }
  1442. if (client == null)
  1443. {
  1444. m_log.DebugFormat(
  1445. "[LLUDPSERVER]: No client found for CompleteAgentMovement from {0} in {1} after wait. Dropping.",
  1446. endPoint, Scene.Name);
  1447. return;
  1448. }
  1449. else if (!client.IsActive || client.SceneAgent == null)
  1450. {
  1451. // This check exists to catch a condition where the client has been closed by another thread
  1452. // but has not yet been removed from the client manager.
  1453. // The packet could be simply ignored but it is useful to know if this condition occurred for other debugging
  1454. // purposes.
  1455. m_log.DebugFormat(
  1456. "[LLUDPSERVER]: Received a CompleteAgentMovement from {0} for {1} in {2} but client is not active after wait. Dropping.",
  1457. endPoint, client.Name, Scene.Name);
  1458. return;
  1459. }
  1460. IncomingPacket incomingPacket1;
  1461. // Inbox insertion
  1462. if (UsePools)
  1463. {
  1464. incomingPacket1 = m_incomingPacketPool.GetObject();
  1465. incomingPacket1.Client = (LLClientView)client;
  1466. incomingPacket1.Packet = packet;
  1467. }
  1468. else
  1469. {
  1470. incomingPacket1 = new IncomingPacket((LLClientView)client, packet);
  1471. }
  1472. packetInbox.Enqueue(incomingPacket1);
  1473. }
  1474. catch (Exception e)
  1475. {
  1476. m_log.ErrorFormat(
  1477. "[LLUDPSERVER]: CompleteAgentMovement handling from endpoint {0}, client {1} {2} failed. Exception {3}{4}",
  1478. endPoint != null ? endPoint.ToString() : "n/a",
  1479. client != null ? client.Name : "unknown",
  1480. client != null ? client.AgentId.ToString() : "unknown",
  1481. e.Message,
  1482. e.StackTrace);
  1483. }
  1484. }
  1485. /// <summary>
  1486. /// Send an ack immediately to the given endpoint.
  1487. /// </summary>
  1488. /// <remarks>
  1489. /// FIXME: Might be possible to use SendPacketData() like everything else, but this will require refactoring so
  1490. /// that we can obtain the UDPClient easily at this point.
  1491. /// </remarks>
  1492. /// <param name="remoteEndpoint"></param>
  1493. /// <param name="sequenceNumber"></param>
  1494. private void SendAckImmediate(IPEndPoint remoteEndpoint, uint sequenceNumber)
  1495. {
  1496. PacketAckPacket ack = new PacketAckPacket();
  1497. ack.Header.Reliable = false;
  1498. ack.Packets = new PacketAckPacket.PacketsBlock[1];
  1499. ack.Packets[0] = new PacketAckPacket.PacketsBlock();
  1500. ack.Packets[0].ID = sequenceNumber;
  1501. SendAckImmediate(remoteEndpoint, ack);
  1502. }
  1503. public virtual void SendAckImmediate(IPEndPoint remoteEndpoint, PacketAckPacket ack)
  1504. {
  1505. byte[] packetData = ack.ToBytes();
  1506. int length = packetData.Length;
  1507. UDPPacketBuffer buffer = new UDPPacketBuffer(remoteEndpoint, length);
  1508. buffer.DataLength = length;
  1509. Buffer.BlockCopy(packetData, 0, buffer.Data, 0, length);
  1510. AsyncBeginSend(buffer);
  1511. }
  1512. private bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, out AuthenticateResponse sessionInfo)
  1513. {
  1514. UUID agentID = useCircuitCode.CircuitCode.ID;
  1515. UUID sessionID = useCircuitCode.CircuitCode.SessionID;
  1516. uint circuitCode = useCircuitCode.CircuitCode.Code;
  1517. sessionInfo = m_circuitManager.AuthenticateSession(sessionID, agentID, circuitCode);
  1518. return sessionInfo.Authorised;
  1519. }
  1520. /// <summary>
  1521. /// Add a client.
  1522. /// </summary>
  1523. /// <param name="circuitCode"></param>
  1524. /// <param name="agentID"></param>
  1525. /// <param name="sessionID"></param>
  1526. /// <param name="remoteEndPoint"></param>
  1527. /// <param name="sessionInfo"></param>
  1528. /// <returns>The client if it was added. Null if the client already existed.</returns>
  1529. protected virtual IClientAPI AddClient(
  1530. uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
  1531. {
  1532. IClientAPI client = null;
  1533. // We currently synchronize this code across the whole scene to avoid issues such as
  1534. // http://opensimulator.org/mantis/view.php?id=5365 However, once locking per agent circuit can be done
  1535. // consistently, this lock could probably be removed.
  1536. lock (this)
  1537. {
  1538. if (!Scene.TryGetClient(agentID, out client))
  1539. {
  1540. LLUDPClient udpClient = new LLUDPClient(this, ThrottleRates, Throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
  1541. client = new LLClientView(Scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);
  1542. client.OnLogout += LogoutHandler;
  1543. client.DebugPacketLevel = DefaultClientPacketDebugLevel;
  1544. ((LLClientView)client).DisableFacelights = m_disableFacelights;
  1545. client.Start();
  1546. }
  1547. }
  1548. return client;
  1549. }
  1550. /// <summary>
  1551. /// Deactivates the client if we don't receive any packets within a certain amount of time (default 60 seconds).
  1552. /// </summary>
  1553. /// <remarks>
  1554. /// If a connection is active then we will always receive packets even if nothing else is happening, due to
  1555. /// regular client pings.
  1556. /// </remarks>
  1557. /// <param name='client'></param>
  1558. /// <param name='timeoutTicks'></param>
  1559. private void DeactivateClientDueToTimeout(LLClientView client, int timeoutTicks)
  1560. {
  1561. lock (client.CloseSyncLock)
  1562. {
  1563. ClientLogoutsDueToNoReceives++;
  1564. m_log.WarnFormat(
  1565. "[LLUDPSERVER]: No packets received from {0} agent of {1} for {2}ms in {3}. Disconnecting.",
  1566. client.SceneAgent.IsChildAgent ? "child" : "root", client.Name, timeoutTicks, Scene.Name);
  1567. if (!client.SceneAgent.IsChildAgent)
  1568. client.Kick("Simulator logged you out due to connection timeout.");
  1569. }
  1570. Scene.CloseAgent(client.AgentId, true);
  1571. }
  1572. private void IncomingPacketHandler()
  1573. {
  1574. Thread.CurrentThread.Priority = ThreadPriority.Highest;
  1575. // Set this culture for the thread that incoming packets are received
  1576. // on to en-US to avoid number parsing issues
  1577. Culture.SetCurrentCulture();
  1578. while (IsRunningInbound)
  1579. {
  1580. try
  1581. {
  1582. IncomingPacket incomingPacket = null;
  1583. /*
  1584. // HACK: This is a test to try and rate limit packet handling on Mono.
  1585. // If it works, a more elegant solution can be devised
  1586. if (Util.FireAndForgetCount() < 2)
  1587. {
  1588. //m_log.Debug("[LLUDPSERVER]: Incoming packet handler is sleeping");
  1589. Thread.Sleep(30);
  1590. }
  1591. */
  1592. if (packetInbox.Dequeue(100, ref incomingPacket))
  1593. {
  1594. ProcessInPacket(incomingPacket);//, incomingPacket); Util.FireAndForget(ProcessInPacket, incomingPacket);
  1595. if (UsePools)
  1596. m_incomingPacketPool.ReturnObject(incomingPacket);
  1597. }
  1598. }
  1599. catch (Exception ex)
  1600. {
  1601. m_log.Error("[LLUDPSERVER]: Error in the incoming packet handler loop: " + ex.Message, ex);
  1602. }
  1603. Watchdog.UpdateThread();
  1604. }
  1605. if (packetInbox.Count > 0)
  1606. m_log.Warn("[LLUDPSERVER]: IncomingPacketHandler is shutting down, dropping " + packetInbox.Count + " packets");
  1607. packetInbox.Clear();
  1608. Watchdog.RemoveThread();
  1609. }
  1610. private void OutgoingPacketHandler()
  1611. {
  1612. Thread.CurrentThread.Priority = ThreadPriority.Highest;
  1613. // Set this culture for the thread that outgoing packets are sent
  1614. // on to en-US to avoid number parsing issues
  1615. Culture.SetCurrentCulture();
  1616. // Typecast the function to an Action<IClientAPI> once here to avoid allocating a new
  1617. // Action generic every round
  1618. Action<IClientAPI> clientPacketHandler = ClientOutgoingPacketHandler;
  1619. while (base.IsRunningOutbound)
  1620. {
  1621. try
  1622. {
  1623. m_packetSent = false;
  1624. #region Update Timers
  1625. m_resendUnacked = false;
  1626. m_sendAcks = false;
  1627. m_sendPing = false;
  1628. // Update elapsed time
  1629. int thisTick = Environment.TickCount & Int32.MaxValue;
  1630. if (m_tickLastOutgoingPacketHandler > thisTick)
  1631. m_elapsedMSOutgoingPacketHandler += ((Int32.MaxValue - m_tickLastOutgoingPacketHandler) + thisTick);
  1632. else
  1633. m_elapsedMSOutgoingPacketHandler += (thisTick - m_tickLastOutgoingPacketHandler);
  1634. m_tickLastOutgoingPacketHandler = thisTick;
  1635. // Check for pending outgoing resends every 100ms
  1636. if (m_elapsedMSOutgoingPacketHandler >= 100)
  1637. {
  1638. m_resendUnacked = true;
  1639. m_elapsedMSOutgoingPacketHandler = 0;
  1640. m_elapsed100MSOutgoingPacketHandler += 1;
  1641. }
  1642. // Check for pending outgoing ACKs every 500ms
  1643. if (m_elapsed100MSOutgoingPacketHandler >= 5)
  1644. {
  1645. m_sendAcks = true;
  1646. m_elapsed100MSOutgoingPacketHandler = 0;
  1647. m_elapsed500MSOutgoingPacketHandler += 1;
  1648. }
  1649. // Send pings to clients every 5000ms
  1650. if (m_elapsed500MSOutgoingPacketHandler >= 10)
  1651. {
  1652. m_sendPing = true;
  1653. m_elapsed500MSOutgoingPacketHandler = 0;
  1654. }
  1655. #endregion Update Timers
  1656. // Use this for emergency monitoring -- bug hunting
  1657. //if (m_scene.EmergencyMonitoring)
  1658. // clientPacketHandler = MonitoredClientOutgoingPacketHandler;
  1659. //else
  1660. // clientPacketHandler = ClientOutgoingPacketHandler;
  1661. // Handle outgoing packets, resends, acknowledgements, and pings for each
  1662. // client. m_packetSent will be set to true if a packet is sent
  1663. Scene.ForEachClient(clientPacketHandler);
  1664. m_currentOutgoingClient = null;
  1665. // If nothing was sent, sleep for the minimum amount of time before a
  1666. // token bucket could get more tokens
  1667. //if (!m_packetSent)
  1668. // Thread.Sleep((int)TickCountResolution);
  1669. //
  1670. // Instead, now wait for data present to be explicitly signalled. Evidence so far is that with
  1671. // modern mono it reduces CPU base load since there is no more continuous polling.
  1672. if (!m_packetSent)
  1673. m_dataPresentEvent.WaitOne(100);
  1674. Watchdog.UpdateThread();
  1675. }
  1676. catch (Exception ex)
  1677. {
  1678. m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler loop threw an exception: " + ex.Message, ex);
  1679. }
  1680. }
  1681. Watchdog.RemoveThread();
  1682. }
  1683. protected void ClientOutgoingPacketHandler(IClientAPI client)
  1684. {
  1685. m_currentOutgoingClient = client;
  1686. try
  1687. {
  1688. if (client is LLClientView)
  1689. {
  1690. LLClientView llClient = (LLClientView)client;
  1691. LLUDPClient udpClient = llClient.UDPClient;
  1692. if (udpClient.IsConnected)
  1693. {
  1694. if (udpClient.ProcessUnackedSends && m_resendUnacked)
  1695. HandleUnacked(llClient);
  1696. if (m_sendAcks)
  1697. SendAcks(udpClient);
  1698. if (m_sendPing)
  1699. SendPing(udpClient);
  1700. // Dequeue any outgoing packets that are within the throttle limits
  1701. if (udpClient.DequeueOutgoing())
  1702. m_packetSent = true;
  1703. }
  1704. }
  1705. }
  1706. catch (Exception ex)
  1707. {
  1708. m_log.Error(
  1709. string.Format("[LLUDPSERVER]: OutgoingPacketHandler iteration for {0} threw ", client.Name), ex);
  1710. }
  1711. }
  1712. #region Emergency Monitoring
  1713. // Alternative packet handler fuull of instrumentation
  1714. // Handy for hunting bugs
  1715. private Stopwatch watch1 = new Stopwatch();
  1716. private Stopwatch watch2 = new Stopwatch();
  1717. private float avgProcessingTicks = 0;
  1718. private float avgResendUnackedTicks = 0;
  1719. private float avgSendAcksTicks = 0;
  1720. private float avgSendPingTicks = 0;
  1721. private float avgDequeueTicks = 0;
  1722. private long nticks = 0;
  1723. private long nticksUnack = 0;
  1724. private long nticksAck = 0;
  1725. private long nticksPing = 0;
  1726. private int npacksSent = 0;
  1727. private int npackNotSent = 0;
  1728. /// <summary>
  1729. /// Number of inbound packets processed since startup.
  1730. /// </summary>
  1731. public long IncomingPacketsProcessed { get; private set; }
  1732. private void MonitoredClientOutgoingPacketHandler(IClientAPI client)
  1733. {
  1734. nticks++;
  1735. watch1.Start();
  1736. m_currentOutgoingClient = client;
  1737. try
  1738. {
  1739. if (client is LLClientView)
  1740. {
  1741. LLClientView llClient = (LLClientView)client;
  1742. LLUDPClient udpClient = llClient.UDPClient;
  1743. if (udpClient.IsConnected)
  1744. {
  1745. if (m_resendUnacked)
  1746. {
  1747. nticksUnack++;
  1748. watch2.Start();
  1749. HandleUnacked(llClient);
  1750. watch2.Stop();
  1751. avgResendUnackedTicks = (nticksUnack - 1)/(float)nticksUnack * avgResendUnackedTicks + (watch2.ElapsedTicks / (float)nticksUnack);
  1752. watch2.Reset();
  1753. }
  1754. if (m_sendAcks)
  1755. {
  1756. nticksAck++;
  1757. watch2.Start();
  1758. SendAcks(udpClient);
  1759. watch2.Stop();
  1760. avgSendAcksTicks = (nticksAck - 1) / (float)nticksAck * avgSendAcksTicks + (watch2.ElapsedTicks / (float)nticksAck);
  1761. watch2.Reset();
  1762. }
  1763. if (m_sendPing)
  1764. {
  1765. nticksPing++;
  1766. watch2.Start();
  1767. SendPing(udpClient);
  1768. watch2.Stop();
  1769. avgSendPingTicks = (nticksPing - 1) / (float)nticksPing * avgSendPingTicks + (watch2.ElapsedTicks / (float)nticksPing);
  1770. watch2.Reset();
  1771. }
  1772. watch2.Start();
  1773. // Dequeue any outgoing packets that are within the throttle limits
  1774. if (udpClient.DequeueOutgoing())
  1775. {
  1776. m_packetSent = true;
  1777. npacksSent++;
  1778. }
  1779. else
  1780. {
  1781. npackNotSent++;
  1782. }
  1783. watch2.Stop();
  1784. avgDequeueTicks = (nticks - 1) / (float)nticks * avgDequeueTicks + (watch2.ElapsedTicks / (float)nticks);
  1785. watch2.Reset();
  1786. }
  1787. else
  1788. {
  1789. m_log.WarnFormat("[LLUDPSERVER]: Client is not connected");
  1790. }
  1791. }
  1792. }
  1793. catch (Exception ex)
  1794. {
  1795. m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler iteration for " + client.Name +
  1796. " threw an exception: " + ex.Message, ex);
  1797. }
  1798. watch1.Stop();
  1799. avgProcessingTicks = (nticks - 1) / (float)nticks * avgProcessingTicks + (watch1.ElapsedTicks / (float)nticks);
  1800. watch1.Reset();
  1801. // reuse this -- it's every ~100ms
  1802. if (Scene.EmergencyMonitoring && nticks % 100 == 0)
  1803. {
  1804. m_log.InfoFormat("[LLUDPSERVER]: avg processing ticks: {0} avg unacked: {1} avg acks: {2} avg ping: {3} avg dequeue: {4} (TickCountRes: {5} sent: {6} notsent: {7})",
  1805. avgProcessingTicks, avgResendUnackedTicks, avgSendAcksTicks, avgSendPingTicks, avgDequeueTicks, TickCountResolution, npacksSent, npackNotSent);
  1806. npackNotSent = npacksSent = 0;
  1807. }
  1808. }
  1809. #endregion
  1810. private void ProcessInPacket(IncomingPacket incomingPacket)
  1811. {
  1812. Packet packet = incomingPacket.Packet;
  1813. LLClientView client = incomingPacket.Client;
  1814. if (client.IsActive)
  1815. {
  1816. m_currentIncomingClient = client;
  1817. try
  1818. {
  1819. // Process this packet
  1820. client.ProcessInPacket(packet);
  1821. }
  1822. catch (ThreadAbortException)
  1823. {
  1824. // If something is trying to abort the packet processing thread, take that as a hint that it's time to shut down
  1825. m_log.Info("[LLUDPSERVER]: Caught a thread abort, shutting down the LLUDP server");
  1826. Stop();
  1827. }
  1828. catch (Exception e)
  1829. {
  1830. // Don't let a failure in an individual client thread crash the whole sim.
  1831. m_log.Error(
  1832. string.Format(
  1833. "[LLUDPSERVER]: Client packet handler for {0} for packet {1} threw ",
  1834. client.Name, packet.Type),
  1835. e);
  1836. }
  1837. finally
  1838. {
  1839. m_currentIncomingClient = null;
  1840. }
  1841. }
  1842. else
  1843. {
  1844. m_log.DebugFormat(
  1845. "[LLUDPSERVER]: Dropped incoming {0} for dead client {1} in {2}",
  1846. packet.Type, client.Name, Scene.RegionInfo.RegionName);
  1847. }
  1848. IncomingPacketsProcessed++;
  1849. }
  1850. protected void LogoutHandler(IClientAPI client)
  1851. {
  1852. client.SendLogoutPacket();
  1853. if (!client.IsLoggingOut)
  1854. {
  1855. client.IsLoggingOut = true;
  1856. Scene.CloseAgent(client.AgentId, false);
  1857. }
  1858. }
  1859. }
  1860. }