LLUDPServer.cs 88 KB

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