OpenSimUDPBase.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. // Try does not protect some mono versions on mac
  204. if(Util.IsWindows())
  205. {
  206. m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
  207. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set");
  208. }
  209. else
  210. {
  211. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
  212. }
  213. }
  214. catch
  215. {
  216. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
  217. }
  218. // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment
  219. // we never want two regions to listen on the same port as they cannot demultiplex each other's messages,
  220. // leading to a confusing bug.
  221. // By default, Windows does not allow two sockets to bind to the same port.
  222. //
  223. // Unfortunately, this also causes a crashed sim to leave the socket in a state
  224. // where it appears to be in use but is really just hung from the old process
  225. // crashing rather than closing it. While this protects agains misconfiguration,
  226. // allowing crashed sims to be started up again right away, rather than having to
  227. // wait 2 minutes for the socket to clear is more valuable. Commented 12/13/2016
  228. // m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);
  229. if (recvBufferSize != 0)
  230. m_udpSocket.ReceiveBufferSize = recvBufferSize;
  231. m_udpSocket.Bind(ipep);
  232. if (m_udpPort == 0)
  233. m_udpPort = ((IPEndPoint)m_udpSocket.LocalEndPoint).Port;
  234. IsRunningInbound = true;
  235. // kick off an async receive. The Start() method will return, the
  236. // actual receives will occur asynchronously and will be caught in
  237. // AsyncEndRecieve().
  238. AsyncBeginReceive();
  239. }
  240. }
  241. /// <summary>
  242. /// Start outbound UDP packet handling.
  243. /// </summary>
  244. public virtual void StartOutbound()
  245. {
  246. m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop");
  247. IsRunningOutbound = true;
  248. }
  249. public virtual void StopInbound()
  250. {
  251. if (IsRunningInbound)
  252. {
  253. m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop");
  254. IsRunningInbound = false;
  255. m_udpSocket.Close();
  256. }
  257. }
  258. public virtual void StopOutbound()
  259. {
  260. m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop");
  261. IsRunningOutbound = false;
  262. }
  263. public virtual bool EnablePools()
  264. {
  265. if (!UsePools)
  266. {
  267. Pool = new Pool<UDPPacketBuffer>(() => new UDPPacketBuffer(), 500);
  268. UsePools = true;
  269. return true;
  270. }
  271. return false;
  272. }
  273. public virtual bool DisablePools()
  274. {
  275. if (UsePools)
  276. {
  277. UsePools = false;
  278. // We won't null out the pool to avoid a race condition with code that may be in the middle of using it.
  279. return true;
  280. }
  281. return false;
  282. }
  283. private void AsyncBeginReceive()
  284. {
  285. UDPPacketBuffer buf;
  286. // FIXME: Disabled for now as this causes issues with reused packet objects interfering with each other
  287. // on Windows with m_asyncPacketHandling = true, though this has not been seen on Linux.
  288. // Possibly some unexpected issue with fetching UDP data concurrently with multiple threads. Requires more investigation.
  289. // if (UsePools)
  290. // buf = Pool.GetObject();
  291. // else
  292. buf = new UDPPacketBuffer();
  293. if (IsRunningInbound)
  294. {
  295. try
  296. {
  297. // kick off an async read
  298. m_udpSocket.BeginReceiveFrom(
  299. //wrappedBuffer.Instance.Data,
  300. buf.Data,
  301. 0,
  302. UDPPacketBuffer.BUFFER_SIZE,
  303. SocketFlags.None,
  304. ref buf.RemoteEndPoint,
  305. AsyncEndReceive,
  306. //wrappedBuffer);
  307. buf);
  308. }
  309. catch (SocketException e)
  310. {
  311. if (e.SocketErrorCode == SocketError.ConnectionReset)
  312. {
  313. m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
  314. bool salvaged = false;
  315. while (!salvaged)
  316. {
  317. try
  318. {
  319. m_udpSocket.BeginReceiveFrom(
  320. //wrappedBuffer.Instance.Data,
  321. buf.Data,
  322. 0,
  323. UDPPacketBuffer.BUFFER_SIZE,
  324. SocketFlags.None,
  325. ref buf.RemoteEndPoint,
  326. AsyncEndReceive,
  327. //wrappedBuffer);
  328. buf);
  329. salvaged = true;
  330. }
  331. catch (SocketException) { }
  332. catch (ObjectDisposedException) { return; }
  333. }
  334. m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
  335. }
  336. }
  337. catch (ObjectDisposedException e)
  338. {
  339. m_log.Error(
  340. string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
  341. }
  342. catch (Exception e)
  343. {
  344. m_log.Error(
  345. string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
  346. }
  347. }
  348. }
  349. private void AsyncEndReceive(IAsyncResult iar)
  350. {
  351. // Asynchronous receive operations will complete here through the call
  352. // to AsyncBeginReceive
  353. if (IsRunningInbound)
  354. {
  355. UdpReceives++;
  356. try
  357. {
  358. // get the buffer that was created in AsyncBeginReceive
  359. // this is the received data
  360. UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
  361. int startTick = Util.EnvironmentTickCount();
  362. // get the length of data actually read from the socket, store it with the
  363. // buffer
  364. buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
  365. // call the abstract method PacketReceived(), passing the buffer that
  366. // has just been filled from the socket read.
  367. PacketReceived(buffer);
  368. // If more than one thread can be calling AsyncEndReceive() at once (e.g. if m_asyncPacketHandler)
  369. // then a particular stat may be inaccurate due to a race condition. We won't worry about this
  370. // since this should be rare and won't cause a runtime problem.
  371. if (m_currentReceiveTimeSamples >= s_receiveTimeSamples)
  372. {
  373. AverageReceiveTicksForLastSamplePeriod
  374. = (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples;
  375. m_receiveTicksInCurrentSamplePeriod = 0;
  376. m_currentReceiveTimeSamples = 0;
  377. }
  378. else
  379. {
  380. m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick);
  381. m_currentReceiveTimeSamples++;
  382. }
  383. }
  384. catch (SocketException se)
  385. {
  386. m_log.Error(
  387. string.Format(
  388. "[UDPBASE]: Error processing UDP end receive {0}, socket error code {1}. Exception ",
  389. UdpReceives, se.ErrorCode),
  390. se);
  391. }
  392. catch (ObjectDisposedException e)
  393. {
  394. m_log.Error(
  395. string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
  396. }
  397. catch (Exception e)
  398. {
  399. m_log.Error(
  400. string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
  401. }
  402. finally
  403. {
  404. // if (UsePools)
  405. // Pool.ReturnObject(buffer);
  406. AsyncBeginReceive();
  407. }
  408. }
  409. }
  410. public void AsyncBeginSend(UDPPacketBuffer buf)
  411. {
  412. // if (IsRunningOutbound)
  413. // {
  414. // This is strictly for debugging purposes to simulate dropped
  415. // packets when testing throttles & retransmission code
  416. // if (DropOutgoingPacket())
  417. // return;
  418. try
  419. {
  420. m_udpSocket.BeginSendTo(
  421. buf.Data,
  422. 0,
  423. buf.DataLength,
  424. SocketFlags.None,
  425. buf.RemoteEndPoint,
  426. AsyncEndSend,
  427. buf);
  428. }
  429. catch (SocketException) { }
  430. catch (ObjectDisposedException) { }
  431. // }
  432. }
  433. void AsyncEndSend(IAsyncResult result)
  434. {
  435. try
  436. {
  437. // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
  438. m_udpSocket.EndSendTo(result);
  439. UdpSends++;
  440. }
  441. catch (SocketException) { }
  442. catch (ObjectDisposedException) { }
  443. }
  444. public void SyncSend(UDPPacketBuffer buf)
  445. {
  446. try
  447. {
  448. m_udpSocket.SendTo(
  449. buf.Data,
  450. 0,
  451. buf.DataLength,
  452. SocketFlags.None,
  453. buf.RemoteEndPoint
  454. );
  455. UdpSends++;
  456. }
  457. catch (SocketException e)
  458. {
  459. m_log.Warn("[UDPBASE]: sync send SocketException {0} " + e.Message);
  460. }
  461. catch (ObjectDisposedException) { }
  462. }
  463. }
  464. }