LLUDPServer.cs 89 KB

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