OpenSimUDPBase.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*
  2. * Copyright (c) 2006, Clutch, Inc.
  3. * Original Author: Jeff Cesnik
  4. * All rights reserved.
  5. *
  6. * - Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * - Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. * - Neither the name of the openmetaverse.org nor the names
  12. * of its contributors may be used to endorse or promote products derived from
  13. * this software without specific prior written permission.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  19. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  20. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  21. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  22. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  23. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  24. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  25. * POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. using System;
  28. using System.Net;
  29. using System.Net.Sockets;
  30. using System.Threading;
  31. using log4net;
  32. using OpenSim.Framework;
  33. using OpenSim.Framework.Monitoring;
  34. namespace OpenMetaverse
  35. {
  36. /// <summary>
  37. /// Base UDP server
  38. /// </summary>
  39. public abstract class OpenSimUDPBase
  40. {
  41. private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  42. /// <summary>
  43. /// This method is called when an incoming packet is received
  44. /// </summary>
  45. /// <param name="buffer">Incoming packet buffer</param>
  46. public abstract void PacketReceived(UDPPacketBuffer buffer);
  47. /// <summary>UDP port to bind to in server mode</summary>
  48. protected int m_udpPort;
  49. /// <summary>Local IP address to bind to in server mode</summary>
  50. protected IPAddress m_localBindAddress;
  51. /// <summary>UDP socket, used in either client or server mode</summary>
  52. private Socket m_udpSocket;
  53. /// <summary>
  54. /// Are we to use object pool(s) to reduce memory churn when receiving data?
  55. /// </summary>
  56. public bool UsePools { get; protected set; }
  57. /// <summary>
  58. /// Pool to use for handling data. May be null if UsePools = false;
  59. /// </summary>
  60. protected OpenSim.Framework.Pool<UDPPacketBuffer> Pool { get; private set; }
  61. /// <summary>Returns true if the server is currently listening for inbound packets, otherwise false</summary>
  62. public bool IsRunningInbound { get; private set; }
  63. /// <summary>Returns true if the server is currently sending outbound packets, otherwise false</summary>
  64. /// <remarks>If IsRunningOut = false, then any request to send a packet is simply dropped.</remarks>
  65. public bool IsRunningOutbound { get; private set; }
  66. /// <summary>
  67. /// Number of UDP receives.
  68. /// </summary>
  69. public int UdpReceives { get; private set; }
  70. /// <summary>
  71. /// Number of UDP sends
  72. /// </summary>
  73. public int UdpSends { get; private set; }
  74. /// <summary>
  75. /// Number of receives over which to establish a receive time average.
  76. /// </summary>
  77. private readonly static int s_receiveTimeSamples = 500;
  78. /// <summary>
  79. /// Current number of samples taken to establish a receive time average.
  80. /// </summary>
  81. private int m_currentReceiveTimeSamples;
  82. /// <summary>
  83. /// Cumulative receive time for the sample so far.
  84. /// </summary>
  85. private int m_receiveTicksInCurrentSamplePeriod;
  86. /// <summary>
  87. /// The average time taken for each require receive in the last sample.
  88. /// </summary>
  89. public float AverageReceiveTicksForLastSamplePeriod { get; private set; }
  90. public int Port
  91. {
  92. get { return m_udpPort; }
  93. }
  94. #region PacketDropDebugging
  95. /// <summary>
  96. /// For debugging purposes only... random number generator for dropping
  97. /// outbound packets.
  98. /// </summary>
  99. private Random m_dropRandomGenerator = new Random();
  100. /// <summary>
  101. /// For debugging purposes only... parameters for a simplified
  102. /// model of packet loss with bursts, overall drop rate should
  103. /// be roughly 1 - m_dropLengthProbability / (m_dropProbabiliy + m_dropLengthProbability)
  104. /// which is about 1% for parameters 0.0015 and 0.15
  105. /// </summary>
  106. private double m_dropProbability = 0.0030;
  107. private double m_dropLengthProbability = 0.15;
  108. private bool m_dropState = false;
  109. /// <summary>
  110. /// For debugging purposes only... parameters to control the time
  111. /// duration over which packet loss bursts can occur, if no packets
  112. /// have been sent for m_dropResetTicks milliseconds, then reset the
  113. /// state of the packet dropper to its default.
  114. /// </summary>
  115. private int m_dropLastTick = 0;
  116. private int m_dropResetTicks = 500;
  117. /// <summary>
  118. /// Debugging code used to simulate dropped packets with bursts
  119. /// </summary>
  120. private bool DropOutgoingPacket()
  121. {
  122. double rnum = m_dropRandomGenerator.NextDouble();
  123. // if the connection has been idle for awhile (more than m_dropResetTicks) then
  124. // reset the state to the default state, don't continue a burst
  125. int curtick = Util.EnvironmentTickCount();
  126. if (Util.EnvironmentTickCountSubtract(curtick, m_dropLastTick) > m_dropResetTicks)
  127. m_dropState = false;
  128. m_dropLastTick = curtick;
  129. // if we are dropping packets, then the probability of dropping
  130. // this packet is the probability that we stay in the burst
  131. if (m_dropState)
  132. {
  133. m_dropState = (rnum < (1.0 - m_dropLengthProbability)) ? true : false;
  134. }
  135. else
  136. {
  137. m_dropState = (rnum < m_dropProbability) ? true : false;
  138. }
  139. return m_dropState;
  140. }
  141. #endregion PacketDropDebugging
  142. /// <summary>
  143. /// Default constructor
  144. /// </summary>
  145. /// <param name="bindAddress">Local IP address to bind the server to</param>
  146. /// <param name="port">Port to listening for incoming UDP packets on</param>
  147. /// /// <param name="usePool">Are we to use an object pool to get objects for handing inbound data?</param>
  148. public OpenSimUDPBase(IPAddress bindAddress, int port)
  149. {
  150. m_localBindAddress = bindAddress;
  151. m_udpPort = port;
  152. // for debugging purposes only, initializes the random number generator
  153. // used for simulating packet loss
  154. // m_dropRandomGenerator = new Random();
  155. }
  156. ~OpenSimUDPBase()
  157. {
  158. if(m_udpSocket !=null)
  159. try { m_udpSocket.Close(); } catch { }
  160. }
  161. /// <summary>
  162. /// Start inbound UDP packet handling.
  163. /// </summary>
  164. /// <param name="recvBufferSize">The size of the receive buffer for
  165. /// the UDP socket. This value is passed up to the operating system
  166. /// and used in the system networking stack. Use zero to leave this
  167. /// value as the default</param>
  168. /// <param name="asyncPacketHandling">Set this to true to start
  169. /// receiving more packets while current packet handler callbacks are
  170. /// still running. Setting this to false will complete each packet
  171. /// callback before the next packet is processed</param>
  172. /// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag
  173. /// on the socket to get newer versions of Windows to behave in a sane
  174. /// manner (not throwing an exception when the remote side resets the
  175. /// connection). This call is ignored on Mono where the flag is not
  176. /// necessary</remarks>
  177. public virtual void StartInbound(int recvBufferSize)
  178. {
  179. if (!IsRunningInbound)
  180. {
  181. m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop");
  182. const int SIO_UDP_CONNRESET = -1744830452;
  183. IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort);
  184. m_udpSocket = new Socket(
  185. AddressFamily.InterNetwork,
  186. SocketType.Dgram,
  187. ProtocolType.Udp);
  188. try
  189. {
  190. if (m_udpSocket.Ttl < 128)
  191. {
  192. m_udpSocket.Ttl = 128;
  193. }
  194. }
  195. catch (SocketException)
  196. {
  197. m_log.Debug("[UDPBASE]: Failed to increase default TTL");
  198. }
  199. try
  200. {
  201. // This udp socket flag is not supported under mono,
  202. // so we'll catch the exception and continue
  203. m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
  204. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set");
  205. }
  206. catch (SocketException)
  207. {
  208. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
  209. }
  210. // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment
  211. // we never want two regions to listen on the same port as they cannot demultiplex each other's messages,
  212. // leading to a confusing bug.
  213. // By default, Windows does not allow two sockets to bind to the same port.
  214. //
  215. // Unfortunately, this also causes a crashed sim to leave the socket in a state
  216. // where it appears to be in use but is really just hung from the old process
  217. // crashing rather than closing it. While this protects agains misconfiguration,
  218. // allowing crashed sims to be started up again right away, rather than having to
  219. // wait 2 minutes for the socket to clear is more valuable. Commented 12/13/2016
  220. // m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);
  221. if (recvBufferSize != 0)
  222. m_udpSocket.ReceiveBufferSize = recvBufferSize;
  223. m_udpSocket.Bind(ipep);
  224. if (m_udpPort == 0)
  225. m_udpPort = ((IPEndPoint)m_udpSocket.LocalEndPoint).Port;
  226. IsRunningInbound = true;
  227. // kick off an async receive. The Start() method will return, the
  228. // actual receives will occur asynchronously and will be caught in
  229. // AsyncEndRecieve().
  230. AsyncBeginReceive();
  231. }
  232. }
  233. /// <summary>
  234. /// Start outbound UDP packet handling.
  235. /// </summary>
  236. public virtual void StartOutbound()
  237. {
  238. m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop");
  239. IsRunningOutbound = true;
  240. }
  241. public virtual void StopInbound()
  242. {
  243. if (IsRunningInbound)
  244. {
  245. m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop");
  246. IsRunningInbound = false;
  247. m_udpSocket.Close();
  248. }
  249. }
  250. public virtual void StopOutbound()
  251. {
  252. m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop");
  253. IsRunningOutbound = false;
  254. }
  255. public virtual bool EnablePools()
  256. {
  257. if (!UsePools)
  258. {
  259. Pool = new Pool<UDPPacketBuffer>(() => new UDPPacketBuffer(), 500);
  260. UsePools = true;
  261. return true;
  262. }
  263. return false;
  264. }
  265. public virtual bool DisablePools()
  266. {
  267. if (UsePools)
  268. {
  269. UsePools = false;
  270. // We won't null out the pool to avoid a race condition with code that may be in the middle of using it.
  271. return true;
  272. }
  273. return false;
  274. }
  275. private void AsyncBeginReceive()
  276. {
  277. UDPPacketBuffer buf;
  278. // FIXME: Disabled for now as this causes issues with reused packet objects interfering with each other
  279. // on Windows with m_asyncPacketHandling = true, though this has not been seen on Linux.
  280. // Possibly some unexpected issue with fetching UDP data concurrently with multiple threads. Requires more investigation.
  281. // if (UsePools)
  282. // buf = Pool.GetObject();
  283. // else
  284. buf = new UDPPacketBuffer();
  285. if (IsRunningInbound)
  286. {
  287. try
  288. {
  289. // kick off an async read
  290. m_udpSocket.BeginReceiveFrom(
  291. //wrappedBuffer.Instance.Data,
  292. buf.Data,
  293. 0,
  294. UDPPacketBuffer.BUFFER_SIZE,
  295. SocketFlags.None,
  296. ref buf.RemoteEndPoint,
  297. AsyncEndReceive,
  298. //wrappedBuffer);
  299. buf);
  300. }
  301. catch (SocketException e)
  302. {
  303. if (e.SocketErrorCode == SocketError.ConnectionReset)
  304. {
  305. m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
  306. bool salvaged = false;
  307. while (!salvaged)
  308. {
  309. try
  310. {
  311. m_udpSocket.BeginReceiveFrom(
  312. //wrappedBuffer.Instance.Data,
  313. buf.Data,
  314. 0,
  315. UDPPacketBuffer.BUFFER_SIZE,
  316. SocketFlags.None,
  317. ref buf.RemoteEndPoint,
  318. AsyncEndReceive,
  319. //wrappedBuffer);
  320. buf);
  321. salvaged = true;
  322. }
  323. catch (SocketException) { }
  324. catch (ObjectDisposedException) { return; }
  325. }
  326. m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
  327. }
  328. }
  329. catch (ObjectDisposedException e)
  330. {
  331. m_log.Error(
  332. string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
  333. }
  334. catch (Exception e)
  335. {
  336. m_log.Error(
  337. string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
  338. }
  339. }
  340. }
  341. private void AsyncEndReceive(IAsyncResult iar)
  342. {
  343. // Asynchronous receive operations will complete here through the call
  344. // to AsyncBeginReceive
  345. if (IsRunningInbound)
  346. {
  347. UdpReceives++;
  348. try
  349. {
  350. // get the buffer that was created in AsyncBeginReceive
  351. // this is the received data
  352. UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
  353. int startTick = Util.EnvironmentTickCount();
  354. // get the length of data actually read from the socket, store it with the
  355. // buffer
  356. buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
  357. // call the abstract method PacketReceived(), passing the buffer that
  358. // has just been filled from the socket read.
  359. PacketReceived(buffer);
  360. // If more than one thread can be calling AsyncEndReceive() at once (e.g. if m_asyncPacketHandler)
  361. // then a particular stat may be inaccurate due to a race condition. We won't worry about this
  362. // since this should be rare and won't cause a runtime problem.
  363. if (m_currentReceiveTimeSamples >= s_receiveTimeSamples)
  364. {
  365. AverageReceiveTicksForLastSamplePeriod
  366. = (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples;
  367. m_receiveTicksInCurrentSamplePeriod = 0;
  368. m_currentReceiveTimeSamples = 0;
  369. }
  370. else
  371. {
  372. m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick);
  373. m_currentReceiveTimeSamples++;
  374. }
  375. }
  376. catch (SocketException se)
  377. {
  378. m_log.Error(
  379. string.Format(
  380. "[UDPBASE]: Error processing UDP end receive {0}, socket error code {1}. Exception ",
  381. UdpReceives, se.ErrorCode),
  382. se);
  383. }
  384. catch (ObjectDisposedException e)
  385. {
  386. m_log.Error(
  387. string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
  388. }
  389. catch (Exception e)
  390. {
  391. m_log.Error(
  392. string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
  393. }
  394. finally
  395. {
  396. // if (UsePools)
  397. // Pool.ReturnObject(buffer);
  398. AsyncBeginReceive();
  399. }
  400. }
  401. }
  402. public void AsyncBeginSend(UDPPacketBuffer buf)
  403. {
  404. // if (IsRunningOutbound)
  405. // {
  406. // This is strictly for debugging purposes to simulate dropped
  407. // packets when testing throttles & retransmission code
  408. // if (DropOutgoingPacket())
  409. // return;
  410. try
  411. {
  412. m_udpSocket.BeginSendTo(
  413. buf.Data,
  414. 0,
  415. buf.DataLength,
  416. SocketFlags.None,
  417. buf.RemoteEndPoint,
  418. AsyncEndSend,
  419. buf);
  420. }
  421. catch (SocketException) { }
  422. catch (ObjectDisposedException) { }
  423. // }
  424. }
  425. void AsyncEndSend(IAsyncResult result)
  426. {
  427. try
  428. {
  429. // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
  430. m_udpSocket.EndSendTo(result);
  431. UdpSends++;
  432. }
  433. catch (SocketException) { }
  434. catch (ObjectDisposedException) { }
  435. }
  436. public void SyncSend(UDPPacketBuffer buf)
  437. {
  438. try
  439. {
  440. m_udpSocket.SendTo(
  441. buf.Data,
  442. 0,
  443. buf.DataLength,
  444. SocketFlags.None,
  445. buf.RemoteEndPoint
  446. );
  447. UdpSends++;
  448. }
  449. catch (SocketException e)
  450. {
  451. m_log.Warn("[UDPBASE]: sync send SocketException {0} " + e.Message);
  452. }
  453. catch (ObjectDisposedException) { }
  454. }
  455. }
  456. }