LLUDPServer.cs 94 KB

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