LLUDPServer.cs 88 KB

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