LLUDPServer.cs 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057
  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");
  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. LLUDPClient udpClient = null;
  1052. Packet packet = null;
  1053. int packetEnd = buffer.DataLength - 1;
  1054. IPEndPoint endPoint = (IPEndPoint)buffer.RemoteEndPoint;
  1055. #region Decoding
  1056. if (buffer.DataLength < 7)
  1057. {
  1058. // m_log.WarnFormat(
  1059. // "[LLUDPSERVER]: Dropping undersized packet with {0} bytes received from {1} in {2}",
  1060. // buffer.DataLength, buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);
  1061. RecordMalformedInboundPacket(endPoint);
  1062. FreeUDPBuffer(buffer);
  1063. return; // Drop undersized packet
  1064. }
  1065. int headerLen = 7;
  1066. if (buffer.Data[6] == 0xFF)
  1067. {
  1068. if (buffer.Data[7] == 0xFF)
  1069. headerLen = 10;
  1070. else
  1071. headerLen = 8;
  1072. }
  1073. if (buffer.DataLength < headerLen)
  1074. {
  1075. // m_log.WarnFormat(
  1076. // "[LLUDPSERVER]: Dropping packet with malformed header received from {0} in {1}",
  1077. // buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);
  1078. RecordMalformedInboundPacket(endPoint);
  1079. FreeUDPBuffer(buffer);
  1080. return; // Malformed header
  1081. }
  1082. try
  1083. {
  1084. // get a buffer for zero decode using the udp buffers pool
  1085. UDPPacketBuffer zerodecodebufferholder = null;
  1086. byte[] zerodecodebuffer = null;
  1087. // only if needed
  1088. if (((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0))
  1089. {
  1090. zerodecodebufferholder = GetNewUDPBuffer(null);
  1091. zerodecodebuffer = zerodecodebufferholder.Data;
  1092. }
  1093. packet = Packet.BuildPacket(buffer.Data, ref packetEnd, zerodecodebuffer);
  1094. // If OpenSimUDPBase.UsePool == true (which is currently separate from the PacketPool) then we
  1095. // assume that packet construction does not retain a reference to byte[] buffer.Data (instead, all
  1096. // bytes are copied out).
  1097. // packet = PacketPool.Instance.GetPacket(buffer.Data, ref packetEnd, zerodecodebuffer);
  1098. if(zerodecodebufferholder != null)
  1099. FreeUDPBuffer(zerodecodebufferholder);
  1100. }
  1101. catch (Exception e)
  1102. {
  1103. if (IncomingMalformedPacketCount < 100)
  1104. m_log.DebugFormat("[LLUDPSERVER]: Dropped malformed packet: " + e.ToString());
  1105. }
  1106. // Fail-safe check
  1107. if (packet == null)
  1108. {
  1109. if (IncomingMalformedPacketCount < 100)
  1110. {
  1111. m_log.WarnFormat("[LLUDPSERVER]: Malformed data, cannot parse {0} byte packet from {1}, data {2}:",
  1112. buffer.DataLength, buffer.RemoteEndPoint, Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
  1113. }
  1114. RecordMalformedInboundPacket(endPoint);
  1115. FreeUDPBuffer(buffer);
  1116. return;
  1117. }
  1118. #endregion Decoding
  1119. #region Packet to Client Mapping
  1120. // If there is already a client for this endpoint, don't process UseCircuitCode
  1121. IClientAPI client = null;
  1122. if (!Scene.TryGetClient(endPoint, out client) || !(client is LLClientView))
  1123. {
  1124. // UseCircuitCode handling
  1125. if (packet.Type == PacketType.UseCircuitCode)
  1126. {
  1127. // And if there is a UseCircuitCode pending, also drop it
  1128. lock (m_pendingCache)
  1129. {
  1130. if (m_pendingCache.Contains(endPoint))
  1131. {
  1132. FreeUDPBuffer(buffer);
  1133. SendAckImmediate(endPoint, packet.Header.Sequence); // i hear you shutup
  1134. return;
  1135. }
  1136. m_pendingCache.AddOrUpdate(endPoint, new Queue<UDPPacketBuffer>(), 60);
  1137. }
  1138. Util.FireAndForget(HandleUseCircuitCode, new object[] { endPoint, packet });
  1139. FreeUDPBuffer(buffer);
  1140. SendAckImmediate(endPoint, packet.Header.Sequence);
  1141. return;
  1142. }
  1143. }
  1144. // If this is a pending connection, enqueue, don't process yet
  1145. lock (m_pendingCache)
  1146. {
  1147. if (m_pendingCache.TryGetValue(endPoint, out Queue<UDPPacketBuffer> queue))
  1148. {
  1149. //m_log.DebugFormat("[LLUDPSERVER]: Enqueued a {0} packet into the pending queue", packet.Type);
  1150. queue.Enqueue(buffer);
  1151. return;
  1152. }
  1153. }
  1154. FreeUDPBuffer(buffer);
  1155. // Determine which agent this packet came from
  1156. if (client == null || !(client is LLClientView))
  1157. {
  1158. //m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet from an unrecognized source: " + address + " in " + m_scene.RegionInfo.RegionName);
  1159. IncomingOrphanedPacketCount++;
  1160. if ((IncomingOrphanedPacketCount % 10000) == 0)
  1161. m_log.WarnFormat(
  1162. "[LLUDPSERVER]: Received {0} orphaned packets so far. Last was from {1}",
  1163. IncomingOrphanedPacketCount, endPoint);
  1164. return;
  1165. }
  1166. udpClient = ((LLClientView)client).UDPClient;
  1167. if (!udpClient.IsConnected)
  1168. {
  1169. m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet for a unConnected client in " + Scene.RegionInfo.RegionName);
  1170. return;
  1171. }
  1172. #endregion Packet to Client Mapping
  1173. // Stats tracking
  1174. Interlocked.Increment(ref udpClient.PacketsReceived);
  1175. int now = Environment.TickCount & Int32.MaxValue;
  1176. udpClient.TickLastPacketReceived = now;
  1177. #region ACK Receiving
  1178. // Handle appended ACKs
  1179. if (packet.Header.AppendedAcks && packet.Header.AckList != null)
  1180. {
  1181. // m_log.DebugFormat(
  1182. // "[LLUDPSERVER]: Handling {0} appended acks from {1} in {2}",
  1183. // packet.Header.AckList.Length, client.Name, m_scene.Name);
  1184. for (int i = 0; i < packet.Header.AckList.Length; i++)
  1185. udpClient.NeedAcks.Acknowledge(packet.Header.AckList[i], now, packet.Header.Resent);
  1186. }
  1187. // Handle PacketAck packets
  1188. if (packet.Type == PacketType.PacketAck)
  1189. {
  1190. PacketAckPacket ackPacket = (PacketAckPacket)packet;
  1191. // m_log.DebugFormat(
  1192. // "[LLUDPSERVER]: Handling {0} packet acks for {1} in {2}",
  1193. // ackPacket.Packets.Length, client.Name, m_scene.Name);
  1194. for (int i = 0; i < ackPacket.Packets.Length; i++)
  1195. udpClient.NeedAcks.Acknowledge(ackPacket.Packets[i].ID, now, packet.Header.Resent);
  1196. // We don't need to do anything else with PacketAck packets
  1197. return;
  1198. }
  1199. #endregion ACK Receiving
  1200. #region ACK Sending
  1201. if (packet.Header.Reliable)
  1202. {
  1203. // m_log.DebugFormat(
  1204. // "[LLUDPSERVER]: Adding ack request for {0} {1} from {2} in {3}",
  1205. // packet.Type, packet.Header.Sequence, client.Name, m_scene.Name);
  1206. udpClient.PendingAcks.Enqueue(packet.Header.Sequence);
  1207. // This is a somewhat odd sequence of steps to pull the client.BytesSinceLastACK value out,
  1208. // add the current received bytes to it, test if 2*MTU bytes have been sent, if so remove
  1209. // 2*MTU bytes from the value and send ACKs, and finally add the local value back to
  1210. // client.BytesSinceLastACK. Lockless thread safety
  1211. int bytesSinceLastACK = Interlocked.Exchange(ref udpClient.BytesSinceLastACK, 0);
  1212. bytesSinceLastACK += buffer.DataLength;
  1213. if (bytesSinceLastACK > LLUDPServer.MTU * 2)
  1214. {
  1215. bytesSinceLastACK -= LLUDPServer.MTU * 2;
  1216. SendAcks(udpClient);
  1217. }
  1218. Interlocked.Add(ref udpClient.BytesSinceLastACK, bytesSinceLastACK);
  1219. }
  1220. #endregion ACK Sending
  1221. #region Incoming Packet Accounting
  1222. // We're not going to worry about interlock yet since its not currently critical that this total count
  1223. // is 100% correct
  1224. if (packet.Header.Resent)
  1225. IncomingPacketsResentCount++;
  1226. // Check the archive of received reliable packet IDs to see whether we already received this packet
  1227. if (packet.Header.Reliable && !udpClient.PacketArchive.TryEnqueue(packet.Header.Sequence))
  1228. {
  1229. if (packet.Header.Resent)
  1230. m_log.DebugFormat(
  1231. "[LLUDPSERVER]: Received a resend of already processed packet #{0}, type {1} from {2}",
  1232. packet.Header.Sequence, packet.Type, client.Name);
  1233. else
  1234. m_log.WarnFormat(
  1235. "[LLUDPSERVER]: Received a duplicate (not marked as resend) of packet #{0}, type {1} from {2}",
  1236. packet.Header.Sequence, packet.Type, client.Name);
  1237. // Avoid firing a callback twice for the same packet
  1238. return;
  1239. }
  1240. #endregion Incoming Packet Accounting
  1241. #region BinaryStats
  1242. LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
  1243. #endregion BinaryStats
  1244. #region Ping Check Handling
  1245. if (packet.Type == PacketType.StartPingCheck)
  1246. {
  1247. // m_log.DebugFormat("[LLUDPSERVER]: Handling ping from {0} in {1}", client.Name, m_scene.Name);
  1248. // We don't need to do anything else with ping checks
  1249. StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
  1250. CompletePing(udpClient, startPing.PingID.PingID);
  1251. if ((Environment.TickCount - m_elapsedMSSinceLastStatReport) >= 3000)
  1252. {
  1253. udpClient.SendPacketStats();
  1254. m_elapsedMSSinceLastStatReport = Environment.TickCount;
  1255. }
  1256. return;
  1257. }
  1258. else if (packet.Type == PacketType.CompletePingCheck)
  1259. {
  1260. double t = Util.GetTimeStampMS() - udpClient.m_lastStartpingTimeMS;
  1261. double c = 0.8 * udpClient.m_pingMS;
  1262. c += 0.2 * t;
  1263. int p = (int)c;
  1264. udpClient.m_pingMS = p;
  1265. udpClient.UpdateRoundTrip(p);
  1266. return;
  1267. }
  1268. #endregion Ping Check Handling
  1269. IncomingPacket incomingPacket;
  1270. incomingPacket = new IncomingPacket((LLClientView)client, packet);
  1271. // if (incomingPacket.Packet.Type == PacketType.AgentUpdate ||
  1272. // incomingPacket.Packet.Type == PacketType.ChatFromViewer)
  1273. // if (incomingPacket.Packet.Type == PacketType.ChatFromViewer)
  1274. // packetInbox.PriorityEnqueue(incomingPacket);
  1275. // else
  1276. // packetInbox.Enqueue(incomingPacket);
  1277. packetInbox.Add(incomingPacket);
  1278. }
  1279. #region BinaryStats
  1280. public class PacketLogger
  1281. {
  1282. public DateTime StartTime;
  1283. public string Path = null;
  1284. public System.IO.BinaryWriter Log = null;
  1285. }
  1286. public static PacketLogger PacketLog;
  1287. protected static bool m_shouldCollectStats = false;
  1288. // Number of seconds to log for
  1289. static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
  1290. static object binStatsLogLock = new object();
  1291. static string binStatsDir = "";
  1292. //for Aggregated In/Out BW logging
  1293. static bool m_aggregatedBWStats = false;
  1294. static long m_aggregatedBytesIn = 0;
  1295. static long m_aggregatedByestOut = 0;
  1296. static object aggBWStatsLock = new object();
  1297. public static long AggregatedLLUDPBytesIn
  1298. {
  1299. get { return m_aggregatedBytesIn; }
  1300. }
  1301. public static long AggregatedLLUDPBytesOut
  1302. {
  1303. get {return m_aggregatedByestOut;}
  1304. }
  1305. public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
  1306. {
  1307. if (m_aggregatedBWStats)
  1308. {
  1309. lock (aggBWStatsLock)
  1310. {
  1311. if (incoming)
  1312. m_aggregatedBytesIn += size;
  1313. else
  1314. m_aggregatedByestOut += size;
  1315. }
  1316. }
  1317. if (!m_shouldCollectStats) return;
  1318. // Binary logging format is TTTTTTTTCCCCFPPPSS, T=Time, C=Circuit, F=Flags, P=PacketType, S=size
  1319. // Put the incoming bit into the least significant bit of the flags byte
  1320. if (incoming)
  1321. flags |= 0x01;
  1322. else
  1323. flags &= 0xFE;
  1324. // Put the flags byte into the most significant bits of the type integer
  1325. uint type = (uint)packetType;
  1326. type |= (uint)flags << 24;
  1327. // m_log.Debug("1 LogPacketHeader(): Outside lock");
  1328. lock (binStatsLogLock)
  1329. {
  1330. DateTime now = DateTime.Now;
  1331. // m_log.Debug("2 LogPacketHeader(): Inside lock. now is " + now.Ticks);
  1332. try
  1333. {
  1334. if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
  1335. {
  1336. if (PacketLog != null && PacketLog.Log != null)
  1337. {
  1338. PacketLog.Log.Close();
  1339. }
  1340. // First log file or time has expired, start writing to a new log file
  1341. PacketLog = new PacketLogger();
  1342. PacketLog.StartTime = now;
  1343. PacketLog.Path = (binStatsDir.Length > 0 ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
  1344. + String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
  1345. PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
  1346. }
  1347. // Serialize the data
  1348. byte[] output = new byte[18];
  1349. Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
  1350. Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
  1351. Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
  1352. Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);
  1353. // Write the serialized data to disk
  1354. if (PacketLog != null && PacketLog.Log != null)
  1355. PacketLog.Log.Write(output);
  1356. }
  1357. catch (Exception ex)
  1358. {
  1359. m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
  1360. if (PacketLog.Log != null)
  1361. {
  1362. PacketLog.Log.Close();
  1363. }
  1364. PacketLog = null;
  1365. }
  1366. }
  1367. }
  1368. #endregion BinaryStats
  1369. protected void HandleUseCircuitCode(object o)
  1370. {
  1371. IPEndPoint endPoint = null;
  1372. IClientAPI client = null;
  1373. try
  1374. {
  1375. // DateTime startTime = DateTime.Now;
  1376. object[] array = (object[])o;
  1377. endPoint = (IPEndPoint)array[0];
  1378. UseCircuitCodePacket uccp = (UseCircuitCodePacket)array[1];
  1379. m_log.DebugFormat(
  1380. "[LLUDPSERVER]: Handling UseCircuitCode request for circuit {0} to {1} from IP {2}",
  1381. uccp.CircuitCode.Code, Scene.RegionInfo.RegionName, endPoint);
  1382. AuthenticateResponse sessionInfo;
  1383. if (IsClientAuthorized(uccp, out sessionInfo))
  1384. {
  1385. AgentCircuitData aCircuit = Scene.AuthenticateHandler.GetAgentCircuitData(uccp.CircuitCode.Code);
  1386. // Begin the process of adding the client to the simulator
  1387. client
  1388. = AddClient(
  1389. uccp.CircuitCode.Code,
  1390. uccp.CircuitCode.ID,
  1391. uccp.CircuitCode.SessionID,
  1392. endPoint,
  1393. sessionInfo);
  1394. // This will be true if the client is new, e.g. not
  1395. // an existing child agent, and there is no circuit data
  1396. if (client != null && aCircuit == null)
  1397. {
  1398. Scene.CloseAgent(client.AgentId, true);
  1399. return;
  1400. }
  1401. // Obtain the pending queue and remove it from the cache
  1402. Queue<UDPPacketBuffer> queue = null;
  1403. lock (m_pendingCache)
  1404. {
  1405. if (!m_pendingCache.TryGetValue(endPoint, out queue))
  1406. {
  1407. m_log.DebugFormat("[LLUDPSERVER]: Client created but no pending queue present");
  1408. return;
  1409. }
  1410. m_pendingCache.Remove(endPoint);
  1411. }
  1412. m_log.DebugFormat("[LLUDPSERVER]: Client created, processing pending queue, {0} entries", queue.Count);
  1413. // Reinject queued packets
  1414. while (queue.Count > 0)
  1415. {
  1416. UDPPacketBuffer buf = queue.Dequeue();
  1417. PacketReceived(buf);
  1418. }
  1419. queue = null;
  1420. if (client != null)
  1421. {
  1422. if(aCircuit.teleportFlags <= 0)
  1423. client.SendRegionHandshake();
  1424. }
  1425. }
  1426. else
  1427. {
  1428. // Don't create clients for unauthorized requesters.
  1429. m_log.WarnFormat(
  1430. "[LLUDPSERVER]: Ignoring connection request for {0} to {1} with unknown circuit code {2} from IP {3}",
  1431. uccp.CircuitCode.ID, Scene.RegionInfo.RegionName, uccp.CircuitCode.Code, endPoint);
  1432. lock (m_pendingCache)
  1433. m_pendingCache.Remove(endPoint);
  1434. }
  1435. // m_log.DebugFormat(
  1436. // "[LLUDPSERVER]: Handling UseCircuitCode request from {0} took {1}ms",
  1437. // buffer.RemoteEndPoint, (DateTime.Now - startTime).Milliseconds);
  1438. }
  1439. catch (Exception e)
  1440. {
  1441. m_log.ErrorFormat(
  1442. "[LLUDPSERVER]: UseCircuitCode handling from endpoint {0}, client {1} {2} failed. Exception {3}{4}",
  1443. endPoint != null ? endPoint.ToString() : "n/a",
  1444. client != null ? client.Name : "unknown",
  1445. client != null ? client.AgentId.ToString() : "unknown",
  1446. e.Message,
  1447. e.StackTrace);
  1448. }
  1449. }
  1450. /// <summary>
  1451. /// Send an ack immediately to the given endpoint.
  1452. /// </summary>
  1453. /// <remarks>
  1454. /// FIXME: Might be possible to use SendPacketData() like everything else, but this will require refactoring so
  1455. /// that we can obtain the UDPClient easily at this point.
  1456. /// </remarks>
  1457. /// <param name="remoteEndpoint"></param>
  1458. /// <param name="sequenceNumber"></param>
  1459. protected void SendAckImmediate(IPEndPoint remoteEndpoint, uint sequenceNumber)
  1460. {
  1461. PacketAckPacket ack = new PacketAckPacket();
  1462. ack.Header.Reliable = false;
  1463. ack.Packets = new PacketAckPacket.PacketsBlock[1];
  1464. ack.Packets[0] = new PacketAckPacket.PacketsBlock();
  1465. ack.Packets[0].ID = sequenceNumber;
  1466. SendAckImmediate(remoteEndpoint, ack);
  1467. }
  1468. public virtual void SendAckImmediate(IPEndPoint remoteEndpoint, PacketAckPacket ack)
  1469. {
  1470. byte[] packetData = ack.ToBytes();
  1471. int length = packetData.Length;
  1472. UDPPacketBuffer buffer = GetNewUDPBuffer(remoteEndpoint);
  1473. buffer.DataLength = length;
  1474. Buffer.BlockCopy(packetData, 0, buffer.Data, 0, length);
  1475. // AsyncBeginSend(buffer);
  1476. SyncSend(buffer);
  1477. FreeUDPBuffer(buffer);
  1478. }
  1479. protected bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, out AuthenticateResponse sessionInfo)
  1480. {
  1481. UUID agentID = useCircuitCode.CircuitCode.ID;
  1482. UUID sessionID = useCircuitCode.CircuitCode.SessionID;
  1483. uint circuitCode = useCircuitCode.CircuitCode.Code;
  1484. sessionInfo = m_circuitManager.AuthenticateSession(sessionID, agentID, circuitCode);
  1485. return sessionInfo.Authorised;
  1486. }
  1487. /// <summary>
  1488. /// Add a client.
  1489. /// </summary>
  1490. /// <param name="circuitCode"></param>
  1491. /// <param name="agentID"></param>
  1492. /// <param name="sessionID"></param>
  1493. /// <param name="remoteEndPoint"></param>
  1494. /// <param name="sessionInfo"></param>
  1495. /// <returns>The client if it was added. Null if the client already existed.</returns>
  1496. protected virtual IClientAPI AddClient(
  1497. uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
  1498. {
  1499. IClientAPI client = null;
  1500. // We currently synchronize this code across the whole scene to avoid issues such as
  1501. // http://opensimulator.org/mantis/view.php?id=5365 However, once locking per agent circuit can be done
  1502. // consistently, this lock could probably be removed.
  1503. lock (this)
  1504. {
  1505. if (Scene.TryGetClient(agentID, out client))
  1506. {
  1507. if (client.SceneAgent != null &&
  1508. client.CircuitCode == circuitCode &&
  1509. client.SessionId == sessionID &&
  1510. client.RemoteEndPoint == remoteEndPoint &&
  1511. client.SceneAgent.ControllingClient.SecureSessionId == sessionInfo.LoginInfo.SecureSession)
  1512. return client;
  1513. Scene.CloseAgent(agentID, true);
  1514. }
  1515. LLUDPClient udpClient = new LLUDPClient(this, ThrottleRates, Throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
  1516. client = new LLClientView(Scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);
  1517. client.OnLogout += LogoutHandler;
  1518. client.DebugPacketLevel = DefaultClientPacketDebugLevel;
  1519. ((LLClientView)client).DisableFacelights = m_disableFacelights;
  1520. client.Start();
  1521. }
  1522. return client;
  1523. }
  1524. /// <summary>
  1525. /// Deactivates the client if we don't receive any packets within a certain amount of time (default 60 seconds).
  1526. /// </summary>
  1527. /// <remarks>
  1528. /// If a connection is active then we will always receive packets even if nothing else is happening, due to
  1529. /// regular client pings.
  1530. /// </remarks>
  1531. /// <param name='client'></param>
  1532. /// <param name='timeoutTicks'></param>
  1533. protected void DeactivateClientDueToTimeout(LLClientView client, int timeoutTicks)
  1534. {
  1535. lock (client.CloseSyncLock)
  1536. {
  1537. ClientLogoutsDueToNoReceives++;
  1538. if (client.SceneAgent != null)
  1539. {
  1540. m_log.WarnFormat(
  1541. "[LLUDPSERVER]: No packets received from {0} agent of {1} for {2}ms in {3}. Disconnecting.",
  1542. client.SceneAgent.IsChildAgent ? "child" : "root", client.Name, timeoutTicks, Scene.Name);
  1543. if (!client.SceneAgent.IsChildAgent)
  1544. client.Kick("Simulator logged you out due to connection timeout.");
  1545. }
  1546. }
  1547. if (!Scene.CloseAgent(client.AgentId, true))
  1548. client.Close(true,true);
  1549. }
  1550. protected void IncomingPacketHandler()
  1551. {
  1552. IncomingPacket incomingPacket;
  1553. // Set this culture for the thread that incoming packets are received
  1554. // on to en-US to avoid number parsing issues
  1555. Culture.SetCurrentCulture();
  1556. while (IsRunningInbound)
  1557. {
  1558. Scene.ThreadAlive(1);
  1559. try
  1560. {
  1561. packetInbox.TryTake(out incomingPacket, 4500);
  1562. if (incomingPacket != null && IsRunningInbound)
  1563. {
  1564. ProcessInPacket(incomingPacket);
  1565. incomingPacket = null;
  1566. }
  1567. }
  1568. catch (ThreadAbortException)
  1569. {
  1570. Thread.ResetAbort();
  1571. }
  1572. catch (Exception ex)
  1573. {
  1574. m_log.Error("[LLUDPSERVER]: Error in the incoming packet handler loop: " + ex.Message, ex);
  1575. }
  1576. Watchdog.UpdateThread();
  1577. }
  1578. if (packetInbox.Count > 0)
  1579. m_log.Warn("[LLUDPSERVER]: IncomingPacketHandler is shutting down, dropping " + packetInbox.Count + " packets");
  1580. packetInbox.Dispose();
  1581. Watchdog.RemoveThread();
  1582. }
  1583. protected void OutgoingPacketHandler()
  1584. {
  1585. // Set this culture for the thread that outgoing packets are sent
  1586. // on to en-US to avoid number parsing issues
  1587. Culture.SetCurrentCulture();
  1588. // Typecast the function to an Action<IClientAPI> once here to avoid allocating a new
  1589. // Action generic every round
  1590. Action<IClientAPI> clientPacketHandler = ClientOutgoingPacketHandler;
  1591. while (base.IsRunningOutbound)
  1592. {
  1593. Scene.ThreadAlive(2);
  1594. try
  1595. {
  1596. m_packetSent = false;
  1597. #region Update Timers
  1598. m_resendUnacked = false;
  1599. m_sendAcks = false;
  1600. m_sendPing = false;
  1601. // Update elapsed time
  1602. double thisTick = Util.GetTimeStampMS();
  1603. // update some 1ms resolution chained timers
  1604. m_elapsedMSOutgoingPacketHandler += thisTick - m_tickLastOutgoingPacketHandler;
  1605. m_tickLastOutgoingPacketHandler = thisTick;
  1606. // Check for pending outgoing resends every 100ms
  1607. if (m_elapsedMSOutgoingPacketHandler >= 100.0)
  1608. {
  1609. m_resendUnacked = true;
  1610. m_elapsedMSOutgoingPacketHandler = 0.0;
  1611. ++m_elapsed100MSOutgoingPacketHandler;
  1612. }
  1613. // Check for pending outgoing ACKs every 500ms
  1614. if (m_elapsed100MSOutgoingPacketHandler >= 5)
  1615. {
  1616. m_sendAcks = true;
  1617. m_elapsed100MSOutgoingPacketHandler = 0;
  1618. ++m_elapsed500MSOutgoingPacketHandler;
  1619. }
  1620. // Send pings to clients every 5000ms
  1621. if (m_elapsed500MSOutgoingPacketHandler >= 10)
  1622. {
  1623. m_sendPing = true;
  1624. m_elapsed500MSOutgoingPacketHandler = 0;
  1625. }
  1626. #endregion Update Timers
  1627. // Handle outgoing packets, resends, acknowledgements, and pings for each
  1628. // client. m_packetSent will be set to true if a packet is sent
  1629. Scene.ForEachClient(clientPacketHandler);
  1630. // If nothing was sent, sleep for the minimum amount of time before a
  1631. // token bucket could get more tokens
  1632. if(Scene.GetNumberOfClients() == 0)
  1633. {
  1634. Thread.Sleep(100);
  1635. }
  1636. else if (!m_packetSent)
  1637. // Thread.Sleep((int)TickCountResolution); outch this is bad on linux
  1638. Thread.Sleep(15); // match the 16ms of windows, dont ask 16 or win may decide to do 32ms.
  1639. Watchdog.UpdateThread();
  1640. }
  1641. catch (Exception ex)
  1642. {
  1643. m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler loop threw an exception: " + ex.Message, ex);
  1644. }
  1645. }
  1646. Watchdog.RemoveThread();
  1647. }
  1648. protected void ClientOutgoingPacketHandler(IClientAPI client)
  1649. {
  1650. try
  1651. {
  1652. if (client is LLClientView)
  1653. {
  1654. LLClientView llClient = (LLClientView)client;
  1655. LLUDPClient udpClient = llClient.UDPClient;
  1656. if (udpClient.IsConnected)
  1657. {
  1658. if (client.IsActive && m_resendUnacked)
  1659. HandleUnacked(llClient);
  1660. if (client.IsActive)
  1661. {
  1662. if (m_sendAcks)
  1663. SendAcks(udpClient);
  1664. if (m_sendPing)
  1665. SendPing(udpClient);
  1666. }
  1667. // Dequeue any outgoing packets that are within the throttle limits
  1668. if (udpClient.DequeueOutgoing())
  1669. m_packetSent = true;
  1670. }
  1671. }
  1672. }
  1673. catch (Exception ex)
  1674. {
  1675. m_log.Error(
  1676. string.Format("[LLUDPSERVER]: OutgoingPacketHandler iteration for {0} threw ", client.Name), ex);
  1677. }
  1678. }
  1679. #region Emergency Monitoring
  1680. // Alternative packet handler fuull of instrumentation
  1681. // Handy for hunting bugs
  1682. protected Stopwatch watch1 = new Stopwatch();
  1683. protected Stopwatch watch2 = new Stopwatch();
  1684. protected float avgProcessingTicks = 0;
  1685. protected float avgResendUnackedTicks = 0;
  1686. protected float avgSendAcksTicks = 0;
  1687. protected float avgSendPingTicks = 0;
  1688. protected float avgDequeueTicks = 0;
  1689. protected long nticks = 0;
  1690. protected long nticksUnack = 0;
  1691. protected long nticksAck = 0;
  1692. protected long nticksPing = 0;
  1693. protected int npacksSent = 0;
  1694. protected int npackNotSent = 0;
  1695. /// <summary>
  1696. /// Number of inbound packets processed since startup.
  1697. /// </summary>
  1698. public long IncomingPacketsProcessed { get; protected set; }
  1699. #endregion
  1700. protected void ProcessInPacket(IncomingPacket incomingPacket)
  1701. {
  1702. Packet packet = incomingPacket.Packet;
  1703. LLClientView client = incomingPacket.Client;
  1704. if(!client.IsActive)
  1705. return;
  1706. try
  1707. {
  1708. // Process this packet
  1709. client.ProcessInPacket(packet);
  1710. }
  1711. catch(ThreadAbortException)
  1712. {
  1713. // If something is trying to abort the packet processing thread, take that as a hint that it's time to shut down
  1714. m_log.Info("[LLUDPSERVER]: Caught a thread abort, shutting down the LLUDP server");
  1715. Stop();
  1716. }
  1717. catch(Exception e)
  1718. {
  1719. // Don't let a failure in an individual client thread crash the whole sim.
  1720. m_log.Error(
  1721. string.Format(
  1722. "[LLUDPSERVER]: Client packet handler for {0} for packet {1} threw ",
  1723. client.Name,packet.Type),
  1724. e);
  1725. }
  1726. IncomingPacketsProcessed++;
  1727. }
  1728. protected void LogoutHandler(IClientAPI client)
  1729. {
  1730. client.SendLogoutPacket();
  1731. if (!client.IsLoggingOut)
  1732. {
  1733. client.IsLoggingOut = true;
  1734. Scene.CloseAgent(client.AgentId, false);
  1735. }
  1736. }
  1737. }
  1738. }