1
0

LLUDPServer.cs 77 KB

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