LLUDPServer.cs 81 KB

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