LLUDPServer.cs 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087
  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 ExpiringCache<IPEndPoint, Queue<UDPPacketBuffer>> m_pendingCache = new ExpiringCache<IPEndPoint, Queue<UDPPacketBuffer>>();
  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", 0);
  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. bool highPriority = false;
  756. if (category != ThrottleOutPacketType.Unknown && (category & ThrottleOutPacketType.HighPriority) != 0)
  757. {
  758. category = (ThrottleOutPacketType)((int)category & 127);
  759. highPriority = true;
  760. }
  761. OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category, null);
  762. // If we were not provided a method for handling unacked, use the UDPServer default method
  763. if ((outgoingPacket.Buffer.Data[0] & Helpers.MSG_RELIABLE) != 0)
  764. outgoingPacket.UnackedMethod = ((method == null) ? delegate(OutgoingPacket oPacket) { ResendUnacked(oPacket); } : method);
  765. // If a Linden Lab 1.23.5 client receives an update packet after a kill packet for an object, it will
  766. // continue to display the deleted object until relog. Therefore, we need to always queue a kill object
  767. // packet so that it isn't sent before a queued update packet.
  768. bool requestQueue = type == PacketType.KillObject;
  769. if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, requestQueue, highPriority))
  770. {
  771. SendPacketFinal(outgoingPacket);
  772. return true;
  773. }
  774. return false;
  775. #endregion Queue or Send
  776. }
  777. public unsafe UDPPacketBuffer ZeroEncode(UDPPacketBuffer input)
  778. {
  779. UDPPacketBuffer zb = GetNewUDPBuffer(null);
  780. int srclen = input.DataLength;
  781. byte[] src = input.Data;
  782. byte[] dest = zb.Data;
  783. int zerolen = 6;
  784. byte zerocount = 0;
  785. for (int i = zerolen; i < srclen; i++)
  786. {
  787. if (src[i] == 0x00)
  788. {
  789. zerocount++;
  790. if (zerocount == 0)
  791. {
  792. dest[zerolen++] = 0x00;
  793. dest[zerolen++] = 0xff;
  794. zerocount++;
  795. }
  796. }
  797. else
  798. {
  799. if (zerocount != 0)
  800. {
  801. dest[zerolen++] = 0x00;
  802. dest[zerolen++] = zerocount;
  803. zerocount = 0;
  804. }
  805. dest[zerolen++] = src[i];
  806. }
  807. }
  808. if (zerocount != 0)
  809. {
  810. dest[zerolen++] = 0x00;
  811. dest[zerolen++] = zerocount;
  812. }
  813. if(zerolen >= srclen)
  814. {
  815. FreeUDPBuffer(zb);
  816. src[0] &= unchecked((byte)~Helpers.MSG_ZEROCODED);
  817. return input;
  818. }
  819. Buffer.BlockCopy(src, 0, dest, 0, 6);
  820. zb.RemoteEndPoint = input.RemoteEndPoint;
  821. zb.DataLength = zerolen;
  822. FreeUDPBuffer(input);
  823. return zb;
  824. }
  825. public void SendUDPPacket(
  826. LLUDPClient udpClient, UDPPacketBuffer buffer, ThrottleOutPacketType category, UnackedPacketMethod method, bool forcequeue, bool zerocode)
  827. {
  828. bool highPriority = false;
  829. if (zerocode)
  830. buffer = ZeroEncode(buffer);
  831. if (category != ThrottleOutPacketType.Unknown && (category & ThrottleOutPacketType.HighPriority) != 0)
  832. {
  833. category = (ThrottleOutPacketType)((int)category & 127);
  834. highPriority = true;
  835. }
  836. OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category, null);
  837. // If we were not provided a method for handling unacked, use the UDPServer default method
  838. if ((outgoingPacket.Buffer.Data[0] & Helpers.MSG_RELIABLE) != 0)
  839. outgoingPacket.UnackedMethod = ((method == null) ? delegate (OutgoingPacket oPacket) { ResendUnacked(oPacket); } : method);
  840. if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, forcequeue, highPriority))
  841. SendPacketFinal(outgoingPacket);
  842. }
  843. public void SendUDPPacket(LLUDPClient udpClient, UDPPacketBuffer buffer, ThrottleOutPacketType category)
  844. {
  845. bool highPriority = false;
  846. if (category != ThrottleOutPacketType.Unknown && (category & ThrottleOutPacketType.HighPriority) != 0)
  847. {
  848. category = (ThrottleOutPacketType)((int)category & 127);
  849. highPriority = true;
  850. }
  851. OutgoingPacket outgoingPacket = new OutgoingPacket(udpClient, buffer, category, null);
  852. // If we were not provided a method for handling unacked, use the UDPServer default method
  853. if ((outgoingPacket.Buffer.Data[0] & Helpers.MSG_RELIABLE) != 0)
  854. outgoingPacket.UnackedMethod = delegate (OutgoingPacket oPacket) { ResendUnacked(oPacket); };
  855. if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, false, highPriority))
  856. SendPacketFinal(outgoingPacket);
  857. }
  858. static private readonly byte[] PacketAckHeader = new byte[] {
  859. 0,
  860. 0, 0, 0, 0, // sequence number
  861. 0, // extra
  862. 0xff, 0xff, 0xff, 0xfb // ID 65531 (low frequency bigendian)
  863. };
  864. public void SendAcks(LLUDPClient udpClient)
  865. {
  866. if(udpClient.PendingAcks.Count == 0)
  867. return;
  868. UDPPacketBuffer buf = GetNewUDPBuffer(udpClient.RemoteEndPoint);
  869. Buffer.BlockCopy(PacketAckHeader, 0, buf.Data, 0, 10);
  870. byte[] data = buf.Data;
  871. // count at position 10
  872. int pos = 11;
  873. uint ack;
  874. int count = 0;
  875. while (udpClient.PendingAcks.Dequeue(out ack))
  876. {
  877. Utils.UIntToBytes(ack, data, pos); pos += 4;
  878. ++count;
  879. if (count == 255)
  880. {
  881. data[10] = 255;
  882. buf.DataLength = pos;
  883. SendUDPPacket(udpClient, buf, ThrottleOutPacketType.Unknown);
  884. buf = GetNewUDPBuffer(udpClient.RemoteEndPoint);
  885. Buffer.BlockCopy(PacketAckHeader, 0, buf.Data, 0, 10);
  886. data = buf.Data;
  887. pos = 11;
  888. count = 0;
  889. }
  890. }
  891. if (count > 0)
  892. {
  893. data[10] = (byte)count;
  894. buf.DataLength = pos;
  895. SendUDPPacket(udpClient, buf, ThrottleOutPacketType.Unknown);
  896. }
  897. }
  898. static private readonly byte[] StartPingCheckHeader = new byte[] {
  899. 0,
  900. 0, 0, 0, 0, // sequence number
  901. 0, // extra
  902. 1 // ID 1 (high frequency)
  903. };
  904. public void SendPing(LLUDPClient udpClient)
  905. {
  906. UDPPacketBuffer buf = GetNewUDPBuffer(udpClient.RemoteEndPoint);
  907. Buffer.BlockCopy(StartPingCheckHeader, 0, buf.Data, 0, 7);
  908. byte[] data = buf.Data;
  909. data[7] = udpClient.CurrentPingSequence++;
  910. // older seq number of our un ack packets, so viewers could clean deduplication lists TODO
  911. //Utils.UIntToBytes(0, data, 8);
  912. data[8] = 0;
  913. data[9] = 0;
  914. data[10] = 0;
  915. data[11] = 0;
  916. buf.DataLength = 12;
  917. SendUDPPacket(udpClient, buf, ThrottleOutPacketType.Unknown);
  918. udpClient.m_lastStartpingTimeMS = Util.GetTimeStampMS();
  919. }
  920. static private readonly byte[] CompletePingCheckHeader = new byte[] {
  921. 0,
  922. 0, 0, 0, 0, // sequence number
  923. 0, // extra
  924. 2 // ID 1 (high frequency)
  925. };
  926. public void CompletePing(LLUDPClient udpClient, byte pingID)
  927. {
  928. UDPPacketBuffer buf = GetNewUDPBuffer(udpClient.RemoteEndPoint);
  929. Buffer.BlockCopy(CompletePingCheckHeader, 0, buf.Data, 0, 7);
  930. byte[] data = buf.Data;
  931. data[7] = pingID;
  932. buf.DataLength = 8;
  933. SendUDPPacket(udpClient, buf, ThrottleOutPacketType.Unknown);
  934. }
  935. public void HandleUnacked(LLClientView client)
  936. {
  937. LLUDPClient udpClient = client.UDPClient;
  938. if (!client.IsActive || !udpClient.IsConnected)
  939. return;
  940. // Disconnect an agent if no packets are received for some time
  941. int timeoutTicks = m_ackTimeout;
  942. // Allow more slack if the client is "paused" eg file upload dialogue is open
  943. // Some sort of limit is needed in case the client crashes, loses its network connection
  944. // or some other disaster prevents it from sendung the AgentResume
  945. if (udpClient.IsPaused)
  946. timeoutTicks = m_pausedAckTimeout;
  947. if (client.IsActive &&
  948. (Environment.TickCount & Int32.MaxValue) - udpClient.TickLastPacketReceived > timeoutTicks)
  949. {
  950. // We must set IsActive synchronously so that we can stop the packet loop reinvoking this method, even
  951. // though it's set later on by LLClientView.Close()
  952. client.IsActive = false;
  953. // Fire this out on a different thread so that we don't hold up outgoing packet processing for
  954. // everybody else if this is being called due to an ack timeout.
  955. // This is the same as processing as the async process of a logout request.
  956. Util.FireAndForget(
  957. o => DeactivateClientDueToTimeout(client, timeoutTicks), null, "LLUDPServer.DeactivateClientDueToTimeout");
  958. return;
  959. }
  960. // Get a list of all of the packets that have been sitting unacked longer than udpClient.RTO
  961. List<OutgoingPacket> expiredPackets = udpClient.NeedAcks.GetExpiredPackets(udpClient.m_RTO);
  962. if (expiredPackets != null)
  963. {
  964. for (int i = 0; i < expiredPackets.Count; ++i)
  965. expiredPackets[i].UnackedMethod(expiredPackets[i]);
  966. }
  967. }
  968. public void ResendUnacked(OutgoingPacket outgoingPacket)
  969. {
  970. //m_log.DebugFormat("[LLUDPSERVER]: Resending packet #{0} (attempt {1}), {2}ms have passed",
  971. // outgoingPacket.SequenceNumber, outgoingPacket.ResendCount, Environment.TickCount - outgoingPacket.TickCount);
  972. // Set the resent flag
  973. outgoingPacket.Buffer.Data[0] = (byte)(outgoingPacket.Buffer.Data[0] | Helpers.MSG_RESENT);
  974. outgoingPacket.Category = ThrottleOutPacketType.Resend;
  975. // Bump up the resend count on this packet
  976. Interlocked.Increment(ref outgoingPacket.ResendCount);
  977. // Requeue or resend the packet
  978. if (!outgoingPacket.Client.EnqueueOutgoing(outgoingPacket, false))
  979. SendPacketFinal(outgoingPacket);
  980. }
  981. public void Flush(LLUDPClient udpClient)
  982. {
  983. // FIXME: Implement?
  984. }
  985. /// <summary>
  986. /// Actually send a packet to a client.
  987. /// </summary>
  988. /// <param name="outgoingPacket"></param>
  989. internal void SendPacketFinal(OutgoingPacket outgoingPacket)
  990. {
  991. UDPPacketBuffer buffer = outgoingPacket.Buffer;
  992. if(buffer == null) // canceled packet
  993. return;
  994. LLUDPClient udpClient = outgoingPacket.Client;
  995. if (!udpClient.IsConnected)
  996. return;
  997. byte flags = buffer.Data[0];
  998. bool isResend = (flags & Helpers.MSG_RESENT) != 0;
  999. bool isReliable = (flags & Helpers.MSG_RELIABLE) != 0;
  1000. bool isZerocoded = (flags & Helpers.MSG_ZEROCODED) != 0;
  1001. int dataLength = buffer.DataLength;
  1002. // only append acks on plain reliable messages
  1003. if (flags == Helpers.MSG_RELIABLE && outgoingPacket.UnackedMethod == null)
  1004. {
  1005. // Keep appending ACKs until there is no room left in the buffer or there are
  1006. // no more ACKs to append
  1007. int ackCount = 0;
  1008. uint ack;
  1009. while (dataLength + 5 < MTU && ackCount < 256 && udpClient.PendingAcks.Dequeue(out ack))
  1010. {
  1011. Utils.UIntToBytesBig(ack, buffer.Data, dataLength);
  1012. dataLength += 4;
  1013. ++ackCount;
  1014. }
  1015. if (ackCount > 0)
  1016. {
  1017. // Set the last byte of the packet equal to the number of appended ACKs
  1018. buffer.Data[dataLength++] = (byte)ackCount;
  1019. // Set the appended ACKs flag on this packet
  1020. buffer.Data[0] = (byte)(buffer.Data[0] | Helpers.MSG_APPENDED_ACKS);
  1021. }
  1022. buffer.DataLength = dataLength;
  1023. }
  1024. if (!isResend)
  1025. {
  1026. // Not a resend, assign a new sequence number
  1027. uint sequenceNumber = (uint)Interlocked.Increment(ref udpClient.CurrentSequence);
  1028. Utils.UIntToBytesBig(sequenceNumber, buffer.Data, 1);
  1029. outgoingPacket.SequenceNumber = sequenceNumber;
  1030. }
  1031. else
  1032. {
  1033. Interlocked.Increment(ref udpClient.PacketsResent);
  1034. PacketsResentCount++;
  1035. }
  1036. // Stats tracking
  1037. Interlocked.Increment(ref udpClient.PacketsSent);
  1038. PacketsSentCount++;
  1039. SyncSend(buffer);
  1040. // Keep track of when this packet was sent out (right now)
  1041. outgoingPacket.TickCount = Environment.TickCount & Int32.MaxValue;
  1042. if (outgoingPacket.UnackedMethod == null)
  1043. FreeUDPBuffer(buffer);
  1044. else if(!isResend)
  1045. {
  1046. // Add this packet to the list of ACK responses we are waiting on from the server
  1047. udpClient.NeedAcks.Add(outgoingPacket);
  1048. }
  1049. if (udpClient.DebugDataOutLevel > 0)
  1050. m_log.DebugFormat(
  1051. "[LLUDPSERVER]: Sending packet #{0} (rel: {1}, res: {2}) to {3} from {4}",
  1052. outgoingPacket.SequenceNumber, isReliable, isResend, udpClient.AgentID, Scene.Name);
  1053. }
  1054. protected void RecordMalformedInboundPacket(IPEndPoint endPoint)
  1055. {
  1056. // if (m_malformedCount < 100)
  1057. // m_log.DebugFormat("[LLUDPSERVER]: Dropped malformed packet: " + e.ToString());
  1058. IncomingMalformedPacketCount++;
  1059. if ((IncomingMalformedPacketCount % 10000) == 0)
  1060. m_log.WarnFormat(
  1061. "[LLUDPSERVER]: Received {0} malformed packets so far, probable network attack. Last was from {1}",
  1062. IncomingMalformedPacketCount, endPoint);
  1063. }
  1064. public override void PacketReceived(UDPPacketBuffer buffer)
  1065. {
  1066. // Debugging/Profiling
  1067. //try { Thread.CurrentThread.Name = "PacketReceived (" + m_scene.RegionInfo.RegionName + ")"; }
  1068. //catch (Exception) { }
  1069. // m_log.DebugFormat(
  1070. // "[LLUDPSERVER]: Packet received from {0} in {1}", buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);
  1071. LLUDPClient udpClient = null;
  1072. Packet packet = null;
  1073. int packetEnd = buffer.DataLength - 1;
  1074. IPEndPoint endPoint = (IPEndPoint)buffer.RemoteEndPoint;
  1075. #region Decoding
  1076. if (buffer.DataLength < 7)
  1077. {
  1078. // m_log.WarnFormat(
  1079. // "[LLUDPSERVER]: Dropping undersized packet with {0} bytes received from {1} in {2}",
  1080. // buffer.DataLength, buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);
  1081. RecordMalformedInboundPacket(endPoint);
  1082. FreeUDPBuffer(buffer);
  1083. return; // Drop undersized packet
  1084. }
  1085. int headerLen = 7;
  1086. if (buffer.Data[6] == 0xFF)
  1087. {
  1088. if (buffer.Data[7] == 0xFF)
  1089. headerLen = 10;
  1090. else
  1091. headerLen = 8;
  1092. }
  1093. if (buffer.DataLength < headerLen)
  1094. {
  1095. // m_log.WarnFormat(
  1096. // "[LLUDPSERVER]: Dropping packet with malformed header received from {0} in {1}",
  1097. // buffer.RemoteEndPoint, m_scene.RegionInfo.RegionName);
  1098. RecordMalformedInboundPacket(endPoint);
  1099. FreeUDPBuffer(buffer);
  1100. return; // Malformed header
  1101. }
  1102. try
  1103. {
  1104. // get a buffer for zero decode using the udp buffers pool
  1105. UDPPacketBuffer zerodecodebufferholder = null;
  1106. byte[] zerodecodebuffer = null;
  1107. // only if needed
  1108. if (((buffer.Data[0] & Helpers.MSG_ZEROCODED) != 0))
  1109. {
  1110. zerodecodebufferholder = GetNewUDPBuffer(null);
  1111. zerodecodebuffer = zerodecodebufferholder.Data;
  1112. }
  1113. packet = Packet.BuildPacket(buffer.Data, ref packetEnd, zerodecodebuffer);
  1114. // If OpenSimUDPBase.UsePool == true (which is currently separate from the PacketPool) then we
  1115. // assume that packet construction does not retain a reference to byte[] buffer.Data (instead, all
  1116. // bytes are copied out).
  1117. // packet = PacketPool.Instance.GetPacket(buffer.Data, ref packetEnd, zerodecodebuffer);
  1118. if(zerodecodebufferholder != null)
  1119. FreeUDPBuffer(zerodecodebufferholder);
  1120. }
  1121. catch (Exception e)
  1122. {
  1123. if (IncomingMalformedPacketCount < 100)
  1124. m_log.DebugFormat("[LLUDPSERVER]: Dropped malformed packet: " + e.ToString());
  1125. }
  1126. // Fail-safe check
  1127. if (packet == null)
  1128. {
  1129. if (IncomingMalformedPacketCount < 100)
  1130. {
  1131. m_log.WarnFormat("[LLUDPSERVER]: Malformed data, cannot parse {0} byte packet from {1}, data {2}:",
  1132. buffer.DataLength, buffer.RemoteEndPoint, Utils.BytesToHexString(buffer.Data, buffer.DataLength, null));
  1133. }
  1134. RecordMalformedInboundPacket(endPoint);
  1135. FreeUDPBuffer(buffer);
  1136. return;
  1137. }
  1138. #endregion Decoding
  1139. #region Packet to Client Mapping
  1140. // If there is already a client for this endpoint, don't process UseCircuitCode
  1141. IClientAPI client = null;
  1142. if (!Scene.TryGetClient(endPoint, out client) || !(client is LLClientView))
  1143. {
  1144. // UseCircuitCode handling
  1145. if (packet.Type == PacketType.UseCircuitCode)
  1146. {
  1147. // And if there is a UseCircuitCode pending, also drop it
  1148. lock (m_pendingCache)
  1149. {
  1150. if (m_pendingCache.Contains(endPoint))
  1151. {
  1152. FreeUDPBuffer(buffer);
  1153. SendAckImmediate(endPoint, packet.Header.Sequence); // i hear you shutup
  1154. return;
  1155. }
  1156. m_pendingCache.AddOrUpdate(endPoint, new Queue<UDPPacketBuffer>(), 60);
  1157. }
  1158. Util.FireAndForget(HandleUseCircuitCode, new object[] { endPoint, packet });
  1159. FreeUDPBuffer(buffer);
  1160. SendAckImmediate(endPoint, packet.Header.Sequence);
  1161. return;
  1162. }
  1163. }
  1164. // If this is a pending connection, enqueue, don't process yet
  1165. lock (m_pendingCache)
  1166. {
  1167. Queue<UDPPacketBuffer> queue;
  1168. if (m_pendingCache.TryGetValue(endPoint, out queue))
  1169. {
  1170. //m_log.DebugFormat("[LLUDPSERVER]: Enqueued a {0} packet into the pending queue", packet.Type);
  1171. queue.Enqueue(buffer);
  1172. return;
  1173. }
  1174. }
  1175. FreeUDPBuffer(buffer);
  1176. // Determine which agent this packet came from
  1177. if (client == null || !(client is LLClientView))
  1178. {
  1179. //m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet from an unrecognized source: " + address + " in " + m_scene.RegionInfo.RegionName);
  1180. IncomingOrphanedPacketCount++;
  1181. if ((IncomingOrphanedPacketCount % 10000) == 0)
  1182. m_log.WarnFormat(
  1183. "[LLUDPSERVER]: Received {0} orphaned packets so far. Last was from {1}",
  1184. IncomingOrphanedPacketCount, endPoint);
  1185. return;
  1186. }
  1187. udpClient = ((LLClientView)client).UDPClient;
  1188. if (!udpClient.IsConnected)
  1189. {
  1190. m_log.Debug("[LLUDPSERVER]: Received a " + packet.Type + " packet for a unConnected client in " + Scene.RegionInfo.RegionName);
  1191. return;
  1192. }
  1193. #endregion Packet to Client Mapping
  1194. // Stats tracking
  1195. Interlocked.Increment(ref udpClient.PacketsReceived);
  1196. int now = Environment.TickCount & Int32.MaxValue;
  1197. udpClient.TickLastPacketReceived = now;
  1198. #region ACK Receiving
  1199. // Handle appended ACKs
  1200. if (packet.Header.AppendedAcks && packet.Header.AckList != null)
  1201. {
  1202. // m_log.DebugFormat(
  1203. // "[LLUDPSERVER]: Handling {0} appended acks from {1} in {2}",
  1204. // packet.Header.AckList.Length, client.Name, m_scene.Name);
  1205. for (int i = 0; i < packet.Header.AckList.Length; i++)
  1206. udpClient.NeedAcks.Acknowledge(packet.Header.AckList[i], now, packet.Header.Resent);
  1207. }
  1208. // Handle PacketAck packets
  1209. if (packet.Type == PacketType.PacketAck)
  1210. {
  1211. PacketAckPacket ackPacket = (PacketAckPacket)packet;
  1212. // m_log.DebugFormat(
  1213. // "[LLUDPSERVER]: Handling {0} packet acks for {1} in {2}",
  1214. // ackPacket.Packets.Length, client.Name, m_scene.Name);
  1215. for (int i = 0; i < ackPacket.Packets.Length; i++)
  1216. udpClient.NeedAcks.Acknowledge(ackPacket.Packets[i].ID, now, packet.Header.Resent);
  1217. // We don't need to do anything else with PacketAck packets
  1218. return;
  1219. }
  1220. #endregion ACK Receiving
  1221. #region ACK Sending
  1222. if (packet.Header.Reliable)
  1223. {
  1224. // m_log.DebugFormat(
  1225. // "[LLUDPSERVER]: Adding ack request for {0} {1} from {2} in {3}",
  1226. // packet.Type, packet.Header.Sequence, client.Name, m_scene.Name);
  1227. udpClient.PendingAcks.Enqueue(packet.Header.Sequence);
  1228. // This is a somewhat odd sequence of steps to pull the client.BytesSinceLastACK value out,
  1229. // add the current received bytes to it, test if 2*MTU bytes have been sent, if so remove
  1230. // 2*MTU bytes from the value and send ACKs, and finally add the local value back to
  1231. // client.BytesSinceLastACK. Lockless thread safety
  1232. int bytesSinceLastACK = Interlocked.Exchange(ref udpClient.BytesSinceLastACK, 0);
  1233. bytesSinceLastACK += buffer.DataLength;
  1234. if (bytesSinceLastACK > LLUDPServer.MTU * 2)
  1235. {
  1236. bytesSinceLastACK -= LLUDPServer.MTU * 2;
  1237. SendAcks(udpClient);
  1238. }
  1239. Interlocked.Add(ref udpClient.BytesSinceLastACK, bytesSinceLastACK);
  1240. }
  1241. #endregion ACK Sending
  1242. #region Incoming Packet Accounting
  1243. // We're not going to worry about interlock yet since its not currently critical that this total count
  1244. // is 100% correct
  1245. if (packet.Header.Resent)
  1246. IncomingPacketsResentCount++;
  1247. // Check the archive of received reliable packet IDs to see whether we already received this packet
  1248. if (packet.Header.Reliable && !udpClient.PacketArchive.TryEnqueue(packet.Header.Sequence))
  1249. {
  1250. if (packet.Header.Resent)
  1251. m_log.DebugFormat(
  1252. "[LLUDPSERVER]: Received a resend of already processed packet #{0}, type {1} from {2}",
  1253. packet.Header.Sequence, packet.Type, client.Name);
  1254. else
  1255. m_log.WarnFormat(
  1256. "[LLUDPSERVER]: Received a duplicate (not marked as resend) of packet #{0}, type {1} from {2}",
  1257. packet.Header.Sequence, packet.Type, client.Name);
  1258. // Avoid firing a callback twice for the same packet
  1259. return;
  1260. }
  1261. #endregion Incoming Packet Accounting
  1262. #region BinaryStats
  1263. LogPacketHeader(true, udpClient.CircuitCode, 0, packet.Type, (ushort)packet.Length);
  1264. #endregion BinaryStats
  1265. #region Ping Check Handling
  1266. if (packet.Type == PacketType.StartPingCheck)
  1267. {
  1268. // m_log.DebugFormat("[LLUDPSERVER]: Handling ping from {0} in {1}", client.Name, m_scene.Name);
  1269. // We don't need to do anything else with ping checks
  1270. StartPingCheckPacket startPing = (StartPingCheckPacket)packet;
  1271. CompletePing(udpClient, startPing.PingID.PingID);
  1272. if ((Environment.TickCount - m_elapsedMSSinceLastStatReport) >= 3000)
  1273. {
  1274. udpClient.SendPacketStats();
  1275. m_elapsedMSSinceLastStatReport = Environment.TickCount;
  1276. }
  1277. return;
  1278. }
  1279. else if (packet.Type == PacketType.CompletePingCheck)
  1280. {
  1281. double t = Util.GetTimeStampMS() - udpClient.m_lastStartpingTimeMS;
  1282. double c = 0.8 * udpClient.m_pingMS;
  1283. c += 0.2 * t;
  1284. int p = (int)c;
  1285. udpClient.m_pingMS = p;
  1286. udpClient.UpdateRoundTrip(p);
  1287. return;
  1288. }
  1289. #endregion Ping Check Handling
  1290. IncomingPacket incomingPacket;
  1291. incomingPacket = new IncomingPacket((LLClientView)client, packet);
  1292. // if (incomingPacket.Packet.Type == PacketType.AgentUpdate ||
  1293. // incomingPacket.Packet.Type == PacketType.ChatFromViewer)
  1294. // if (incomingPacket.Packet.Type == PacketType.ChatFromViewer)
  1295. // packetInbox.PriorityEnqueue(incomingPacket);
  1296. // else
  1297. // packetInbox.Enqueue(incomingPacket);
  1298. packetInbox.Add(incomingPacket);
  1299. }
  1300. #region BinaryStats
  1301. public class PacketLogger
  1302. {
  1303. public DateTime StartTime;
  1304. public string Path = null;
  1305. public System.IO.BinaryWriter Log = null;
  1306. }
  1307. public static PacketLogger PacketLog;
  1308. protected static bool m_shouldCollectStats = false;
  1309. // Number of seconds to log for
  1310. static TimeSpan binStatsMaxFilesize = TimeSpan.FromSeconds(300);
  1311. static object binStatsLogLock = new object();
  1312. static string binStatsDir = "";
  1313. //for Aggregated In/Out BW logging
  1314. static bool m_aggregatedBWStats = false;
  1315. static long m_aggregatedBytesIn = 0;
  1316. static long m_aggregatedByestOut = 0;
  1317. static object aggBWStatsLock = new object();
  1318. public static long AggregatedLLUDPBytesIn
  1319. {
  1320. get { return m_aggregatedBytesIn; }
  1321. }
  1322. public static long AggregatedLLUDPBytesOut
  1323. {
  1324. get {return m_aggregatedByestOut;}
  1325. }
  1326. public static void LogPacketHeader(bool incoming, uint circuit, byte flags, PacketType packetType, ushort size)
  1327. {
  1328. if (m_aggregatedBWStats)
  1329. {
  1330. lock (aggBWStatsLock)
  1331. {
  1332. if (incoming)
  1333. m_aggregatedBytesIn += size;
  1334. else
  1335. m_aggregatedByestOut += size;
  1336. }
  1337. }
  1338. if (!m_shouldCollectStats) return;
  1339. // Binary logging format is TTTTTTTTCCCCFPPPSS, T=Time, C=Circuit, F=Flags, P=PacketType, S=size
  1340. // Put the incoming bit into the least significant bit of the flags byte
  1341. if (incoming)
  1342. flags |= 0x01;
  1343. else
  1344. flags &= 0xFE;
  1345. // Put the flags byte into the most significant bits of the type integer
  1346. uint type = (uint)packetType;
  1347. type |= (uint)flags << 24;
  1348. // m_log.Debug("1 LogPacketHeader(): Outside lock");
  1349. lock (binStatsLogLock)
  1350. {
  1351. DateTime now = DateTime.Now;
  1352. // m_log.Debug("2 LogPacketHeader(): Inside lock. now is " + now.Ticks);
  1353. try
  1354. {
  1355. if (PacketLog == null || (now > PacketLog.StartTime + binStatsMaxFilesize))
  1356. {
  1357. if (PacketLog != null && PacketLog.Log != null)
  1358. {
  1359. PacketLog.Log.Close();
  1360. }
  1361. // First log file or time has expired, start writing to a new log file
  1362. PacketLog = new PacketLogger();
  1363. PacketLog.StartTime = now;
  1364. PacketLog.Path = (binStatsDir.Length > 0 ? binStatsDir + System.IO.Path.DirectorySeparatorChar.ToString() : "")
  1365. + String.Format("packets-{0}.log", now.ToString("yyyyMMddHHmmss"));
  1366. PacketLog.Log = new BinaryWriter(File.Open(PacketLog.Path, FileMode.Append, FileAccess.Write));
  1367. }
  1368. // Serialize the data
  1369. byte[] output = new byte[18];
  1370. Buffer.BlockCopy(BitConverter.GetBytes(now.Ticks), 0, output, 0, 8);
  1371. Buffer.BlockCopy(BitConverter.GetBytes(circuit), 0, output, 8, 4);
  1372. Buffer.BlockCopy(BitConverter.GetBytes(type), 0, output, 12, 4);
  1373. Buffer.BlockCopy(BitConverter.GetBytes(size), 0, output, 16, 2);
  1374. // Write the serialized data to disk
  1375. if (PacketLog != null && PacketLog.Log != null)
  1376. PacketLog.Log.Write(output);
  1377. }
  1378. catch (Exception ex)
  1379. {
  1380. m_log.Error("Packet statistics gathering failed: " + ex.Message, ex);
  1381. if (PacketLog.Log != null)
  1382. {
  1383. PacketLog.Log.Close();
  1384. }
  1385. PacketLog = null;
  1386. }
  1387. }
  1388. }
  1389. #endregion BinaryStats
  1390. protected void HandleUseCircuitCode(object o)
  1391. {
  1392. IPEndPoint endPoint = null;
  1393. IClientAPI client = null;
  1394. try
  1395. {
  1396. // DateTime startTime = DateTime.Now;
  1397. object[] array = (object[])o;
  1398. endPoint = (IPEndPoint)array[0];
  1399. UseCircuitCodePacket uccp = (UseCircuitCodePacket)array[1];
  1400. m_log.DebugFormat(
  1401. "[LLUDPSERVER]: Handling UseCircuitCode request for circuit {0} to {1} from IP {2}",
  1402. uccp.CircuitCode.Code, Scene.RegionInfo.RegionName, endPoint);
  1403. AuthenticateResponse sessionInfo;
  1404. if (IsClientAuthorized(uccp, out sessionInfo))
  1405. {
  1406. AgentCircuitData aCircuit = Scene.AuthenticateHandler.GetAgentCircuitData(uccp.CircuitCode.Code);
  1407. // Begin the process of adding the client to the simulator
  1408. client
  1409. = AddClient(
  1410. uccp.CircuitCode.Code,
  1411. uccp.CircuitCode.ID,
  1412. uccp.CircuitCode.SessionID,
  1413. endPoint,
  1414. sessionInfo);
  1415. // This will be true if the client is new, e.g. not
  1416. // an existing child agent, and there is no circuit data
  1417. if (client != null && aCircuit == null)
  1418. {
  1419. Scene.CloseAgent(client.AgentId, true);
  1420. return;
  1421. }
  1422. // Now we know we can handle more data
  1423. //Thread.Sleep(200);
  1424. // Obtain the pending queue and remove it from the cache
  1425. Queue<UDPPacketBuffer> queue = null;
  1426. lock (m_pendingCache)
  1427. {
  1428. if (!m_pendingCache.TryGetValue(endPoint, out queue))
  1429. {
  1430. m_log.DebugFormat("[LLUDPSERVER]: Client created but no pending queue present");
  1431. return;
  1432. }
  1433. m_pendingCache.Remove(endPoint);
  1434. }
  1435. m_log.DebugFormat("[LLUDPSERVER]: Client created, processing pending queue, {0} entries", queue.Count);
  1436. // Reinject queued packets
  1437. while (queue.Count > 0)
  1438. {
  1439. UDPPacketBuffer buf = queue.Dequeue();
  1440. PacketReceived(buf);
  1441. }
  1442. queue = null;
  1443. if (client != null)
  1444. {
  1445. if(aCircuit.teleportFlags <= 0)
  1446. client.SendRegionHandshake();
  1447. }
  1448. }
  1449. else
  1450. {
  1451. // Don't create clients for unauthorized requesters.
  1452. m_log.WarnFormat(
  1453. "[LLUDPSERVER]: Ignoring connection request for {0} to {1} with unknown circuit code {2} from IP {3}",
  1454. uccp.CircuitCode.ID, Scene.RegionInfo.RegionName, uccp.CircuitCode.Code, endPoint);
  1455. lock (m_pendingCache)
  1456. m_pendingCache.Remove(endPoint);
  1457. }
  1458. // m_log.DebugFormat(
  1459. // "[LLUDPSERVER]: Handling UseCircuitCode request from {0} took {1}ms",
  1460. // buffer.RemoteEndPoint, (DateTime.Now - startTime).Milliseconds);
  1461. }
  1462. catch (Exception e)
  1463. {
  1464. m_log.ErrorFormat(
  1465. "[LLUDPSERVER]: UseCircuitCode handling from endpoint {0}, client {1} {2} failed. Exception {3}{4}",
  1466. endPoint != null ? endPoint.ToString() : "n/a",
  1467. client != null ? client.Name : "unknown",
  1468. client != null ? client.AgentId.ToString() : "unknown",
  1469. e.Message,
  1470. e.StackTrace);
  1471. }
  1472. }
  1473. /// <summary>
  1474. /// Send an ack immediately to the given endpoint.
  1475. /// </summary>
  1476. /// <remarks>
  1477. /// FIXME: Might be possible to use SendPacketData() like everything else, but this will require refactoring so
  1478. /// that we can obtain the UDPClient easily at this point.
  1479. /// </remarks>
  1480. /// <param name="remoteEndpoint"></param>
  1481. /// <param name="sequenceNumber"></param>
  1482. protected void SendAckImmediate(IPEndPoint remoteEndpoint, uint sequenceNumber)
  1483. {
  1484. PacketAckPacket ack = new PacketAckPacket();
  1485. ack.Header.Reliable = false;
  1486. ack.Packets = new PacketAckPacket.PacketsBlock[1];
  1487. ack.Packets[0] = new PacketAckPacket.PacketsBlock();
  1488. ack.Packets[0].ID = sequenceNumber;
  1489. SendAckImmediate(remoteEndpoint, ack);
  1490. }
  1491. public virtual void SendAckImmediate(IPEndPoint remoteEndpoint, PacketAckPacket ack)
  1492. {
  1493. byte[] packetData = ack.ToBytes();
  1494. int length = packetData.Length;
  1495. UDPPacketBuffer buffer = GetNewUDPBuffer(remoteEndpoint);
  1496. buffer.DataLength = length;
  1497. Buffer.BlockCopy(packetData, 0, buffer.Data, 0, length);
  1498. // AsyncBeginSend(buffer);
  1499. SyncSend(buffer);
  1500. FreeUDPBuffer(buffer);
  1501. }
  1502. protected bool IsClientAuthorized(UseCircuitCodePacket useCircuitCode, out AuthenticateResponse sessionInfo)
  1503. {
  1504. UUID agentID = useCircuitCode.CircuitCode.ID;
  1505. UUID sessionID = useCircuitCode.CircuitCode.SessionID;
  1506. uint circuitCode = useCircuitCode.CircuitCode.Code;
  1507. sessionInfo = m_circuitManager.AuthenticateSession(sessionID, agentID, circuitCode);
  1508. return sessionInfo.Authorised;
  1509. }
  1510. /// <summary>
  1511. /// Add a client.
  1512. /// </summary>
  1513. /// <param name="circuitCode"></param>
  1514. /// <param name="agentID"></param>
  1515. /// <param name="sessionID"></param>
  1516. /// <param name="remoteEndPoint"></param>
  1517. /// <param name="sessionInfo"></param>
  1518. /// <returns>The client if it was added. Null if the client already existed.</returns>
  1519. protected virtual IClientAPI AddClient(
  1520. uint circuitCode, UUID agentID, UUID sessionID, IPEndPoint remoteEndPoint, AuthenticateResponse sessionInfo)
  1521. {
  1522. IClientAPI client = null;
  1523. // We currently synchronize this code across the whole scene to avoid issues such as
  1524. // http://opensimulator.org/mantis/view.php?id=5365 However, once locking per agent circuit can be done
  1525. // consistently, this lock could probably be removed.
  1526. lock (this)
  1527. {
  1528. if (Scene.TryGetClient(agentID, out client))
  1529. {
  1530. if (client.SceneAgent != null &&
  1531. client.CircuitCode == circuitCode &&
  1532. client.SessionId == sessionID &&
  1533. client.RemoteEndPoint == remoteEndPoint &&
  1534. client.SceneAgent.ControllingClient.SecureSessionId == sessionInfo.LoginInfo.SecureSession)
  1535. return client;
  1536. Scene.CloseAgent(agentID, true);
  1537. }
  1538. LLUDPClient udpClient = new LLUDPClient(this, ThrottleRates, Throttle, circuitCode, agentID, remoteEndPoint, m_defaultRTO, m_maxRTO);
  1539. client = new LLClientView(Scene, this, udpClient, sessionInfo, agentID, sessionID, circuitCode);
  1540. client.OnLogout += LogoutHandler;
  1541. client.DebugPacketLevel = DefaultClientPacketDebugLevel;
  1542. ((LLClientView)client).DisableFacelights = m_disableFacelights;
  1543. client.Start();
  1544. }
  1545. return client;
  1546. }
  1547. /// <summary>
  1548. /// Deactivates the client if we don't receive any packets within a certain amount of time (default 60 seconds).
  1549. /// </summary>
  1550. /// <remarks>
  1551. /// If a connection is active then we will always receive packets even if nothing else is happening, due to
  1552. /// regular client pings.
  1553. /// </remarks>
  1554. /// <param name='client'></param>
  1555. /// <param name='timeoutTicks'></param>
  1556. protected void DeactivateClientDueToTimeout(LLClientView client, int timeoutTicks)
  1557. {
  1558. lock (client.CloseSyncLock)
  1559. {
  1560. ClientLogoutsDueToNoReceives++;
  1561. if (client.SceneAgent != null)
  1562. {
  1563. m_log.WarnFormat(
  1564. "[LLUDPSERVER]: No packets received from {0} agent of {1} for {2}ms in {3}. Disconnecting.",
  1565. client.SceneAgent.IsChildAgent ? "child" : "root", client.Name, timeoutTicks, Scene.Name);
  1566. if (!client.SceneAgent.IsChildAgent)
  1567. client.Kick("Simulator logged you out due to connection timeout.");
  1568. }
  1569. }
  1570. if (!Scene.CloseAgent(client.AgentId, true))
  1571. client.Close(true,true);
  1572. }
  1573. protected void IncomingPacketHandler()
  1574. {
  1575. IncomingPacket incomingPacket;
  1576. // Set this culture for the thread that incoming packets are received
  1577. // on to en-US to avoid number parsing issues
  1578. Culture.SetCurrentCulture();
  1579. while (IsRunningInbound)
  1580. {
  1581. Scene.ThreadAlive(1);
  1582. try
  1583. {
  1584. packetInbox.TryTake(out incomingPacket, 4500);
  1585. if (incomingPacket != null && IsRunningInbound)
  1586. {
  1587. ProcessInPacket(incomingPacket);
  1588. incomingPacket = null;
  1589. }
  1590. }
  1591. catch (ThreadAbortException)
  1592. {
  1593. Thread.ResetAbort();
  1594. }
  1595. catch (Exception ex)
  1596. {
  1597. m_log.Error("[LLUDPSERVER]: Error in the incoming packet handler loop: " + ex.Message, ex);
  1598. }
  1599. Watchdog.UpdateThread();
  1600. }
  1601. if (packetInbox.Count > 0)
  1602. m_log.Warn("[LLUDPSERVER]: IncomingPacketHandler is shutting down, dropping " + packetInbox.Count + " packets");
  1603. packetInbox.Dispose();
  1604. Watchdog.RemoveThread();
  1605. }
  1606. protected void OutgoingPacketHandler()
  1607. {
  1608. // Set this culture for the thread that outgoing packets are sent
  1609. // on to en-US to avoid number parsing issues
  1610. Culture.SetCurrentCulture();
  1611. // Typecast the function to an Action<IClientAPI> once here to avoid allocating a new
  1612. // Action generic every round
  1613. Action<IClientAPI> clientPacketHandler = ClientOutgoingPacketHandler;
  1614. while (base.IsRunningOutbound)
  1615. {
  1616. Scene.ThreadAlive(2);
  1617. try
  1618. {
  1619. m_packetSent = false;
  1620. #region Update Timers
  1621. m_resendUnacked = false;
  1622. m_sendAcks = false;
  1623. m_sendPing = false;
  1624. // Update elapsed time
  1625. double thisTick = Util.GetTimeStampMS();
  1626. // update some 1ms resolution chained timers
  1627. m_elapsedMSOutgoingPacketHandler += thisTick - m_tickLastOutgoingPacketHandler;
  1628. m_tickLastOutgoingPacketHandler = thisTick;
  1629. // Check for pending outgoing resends every 100ms
  1630. if (m_elapsedMSOutgoingPacketHandler >= 100.0)
  1631. {
  1632. m_resendUnacked = true;
  1633. m_elapsedMSOutgoingPacketHandler = 0.0;
  1634. m_elapsed100MSOutgoingPacketHandler += 1;
  1635. }
  1636. // Check for pending outgoing ACKs every 500ms
  1637. if (m_elapsed100MSOutgoingPacketHandler >= 5)
  1638. {
  1639. m_sendAcks = true;
  1640. m_elapsed100MSOutgoingPacketHandler = 0;
  1641. m_elapsed500MSOutgoingPacketHandler += 1;
  1642. }
  1643. // Send pings to clients every 5000ms
  1644. if (m_elapsed500MSOutgoingPacketHandler >= 10)
  1645. {
  1646. m_sendPing = true;
  1647. m_elapsed500MSOutgoingPacketHandler = 0;
  1648. }
  1649. #endregion Update Timers
  1650. // Handle outgoing packets, resends, acknowledgements, and pings for each
  1651. // client. m_packetSent will be set to true if a packet is sent
  1652. Scene.ForEachClient(clientPacketHandler);
  1653. // If nothing was sent, sleep for the minimum amount of time before a
  1654. // token bucket could get more tokens
  1655. if(Scene.GetNumberOfClients() == 0)
  1656. {
  1657. Thread.Sleep(100);
  1658. }
  1659. else if (!m_packetSent)
  1660. // Thread.Sleep((int)TickCountResolution); outch this is bad on linux
  1661. Thread.Sleep(15); // match the 16ms of windows, dont ask 16 or win may decide to do 32ms.
  1662. Watchdog.UpdateThread();
  1663. }
  1664. catch (Exception ex)
  1665. {
  1666. m_log.Error("[LLUDPSERVER]: OutgoingPacketHandler loop threw an exception: " + ex.Message, ex);
  1667. }
  1668. }
  1669. Watchdog.RemoveThread();
  1670. }
  1671. protected void ClientOutgoingPacketHandler(IClientAPI client)
  1672. {
  1673. try
  1674. {
  1675. if (client is LLClientView)
  1676. {
  1677. LLClientView llClient = (LLClientView)client;
  1678. LLUDPClient udpClient = llClient.UDPClient;
  1679. if (udpClient.IsConnected)
  1680. {
  1681. if (client.IsActive && m_resendUnacked)
  1682. HandleUnacked(llClient);
  1683. if (client.IsActive)
  1684. {
  1685. if (m_sendAcks)
  1686. SendAcks(udpClient);
  1687. if (m_sendPing)
  1688. SendPing(udpClient);
  1689. }
  1690. // Dequeue any outgoing packets that are within the throttle limits
  1691. if (udpClient.DequeueOutgoing())
  1692. m_packetSent = true;
  1693. }
  1694. }
  1695. }
  1696. catch (Exception ex)
  1697. {
  1698. m_log.Error(
  1699. string.Format("[LLUDPSERVER]: OutgoingPacketHandler iteration for {0} threw ", client.Name), ex);
  1700. }
  1701. }
  1702. #region Emergency Monitoring
  1703. // Alternative packet handler fuull of instrumentation
  1704. // Handy for hunting bugs
  1705. protected Stopwatch watch1 = new Stopwatch();
  1706. protected Stopwatch watch2 = new Stopwatch();
  1707. protected float avgProcessingTicks = 0;
  1708. protected float avgResendUnackedTicks = 0;
  1709. protected float avgSendAcksTicks = 0;
  1710. protected float avgSendPingTicks = 0;
  1711. protected float avgDequeueTicks = 0;
  1712. protected long nticks = 0;
  1713. protected long nticksUnack = 0;
  1714. protected long nticksAck = 0;
  1715. protected long nticksPing = 0;
  1716. protected int npacksSent = 0;
  1717. protected int npackNotSent = 0;
  1718. /// <summary>
  1719. /// Number of inbound packets processed since startup.
  1720. /// </summary>
  1721. public long IncomingPacketsProcessed { get; protected set; }
  1722. #endregion
  1723. protected void ProcessInPacket(IncomingPacket incomingPacket)
  1724. {
  1725. Packet packet = incomingPacket.Packet;
  1726. LLClientView client = incomingPacket.Client;
  1727. if(!client.IsActive)
  1728. return;
  1729. try
  1730. {
  1731. // Process this packet
  1732. client.ProcessInPacket(packet);
  1733. }
  1734. catch(ThreadAbortException)
  1735. {
  1736. // If something is trying to abort the packet processing thread, take that as a hint that it's time to shut down
  1737. m_log.Info("[LLUDPSERVER]: Caught a thread abort, shutting down the LLUDP server");
  1738. Stop();
  1739. }
  1740. catch(Exception e)
  1741. {
  1742. // Don't let a failure in an individual client thread crash the whole sim.
  1743. m_log.Error(
  1744. string.Format(
  1745. "[LLUDPSERVER]: Client packet handler for {0} for packet {1} threw ",
  1746. client.Name,packet.Type),
  1747. e);
  1748. }
  1749. IncomingPacketsProcessed++;
  1750. }
  1751. protected void LogoutHandler(IClientAPI client)
  1752. {
  1753. client.SendLogoutPacket();
  1754. if (!client.IsLoggingOut)
  1755. {
  1756. client.IsLoggingOut = true;
  1757. Scene.CloseAgent(client.AgentId, false);
  1758. }
  1759. }
  1760. }
  1761. }