LLUDPServer.cs 90 KB

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