LLUDPServer.cs 88 KB

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