OpenSimUDPBase.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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 log4net;
  31. using OpenSim.Framework;
  32. using OpenMetaverse;
  33. using OpenMetaverse.Packets;
  34. using System.Threading;
  35. using System.Threading.Tasks;
  36. namespace OpenSim.Region.ClientStack.LindenUDP
  37. {
  38. public readonly struct IncomingPacket(LLClientView client, Packet packet)
  39. {
  40. /// <summary>Client this packet came from</summary>
  41. public readonly LLClientView Client = client;
  42. /// <summary>Packet data that has been received</summary>
  43. public readonly Packet Packet = packet;
  44. }
  45. /// <summary>
  46. /// Base UDP server
  47. /// </summary>
  48. public abstract class OpenSimUDPBase
  49. {
  50. private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  51. /// <summary>
  52. /// This method is called when an incoming packet is received
  53. /// </summary>
  54. /// <param name="buffer">Incoming packet buffer</param>
  55. public abstract void PacketReceived(UDPPacketBuffer buffer);
  56. /// <summary>UDP port to bind to in server mode</summary>
  57. protected int m_udpPort;
  58. /// <summary>Local IP address to bind to in server mode</summary>
  59. protected IPAddress m_localBindAddress;
  60. /// <summary>UDP socket, used in either client or server mode</summary>
  61. private Socket m_udpSocket;
  62. public static Object m_udpBuffersPoolLock = new();
  63. public static UDPPacketBuffer[] m_udpBuffersPool = new UDPPacketBuffer[1000];
  64. public static int m_udpBuffersPoolPtr = -1;
  65. /// <summary>Returns true if the server is currently listening for inbound packets, otherwise false</summary>
  66. internal bool m_IsRunningInbound;
  67. public bool IsRunningInbound
  68. {
  69. get { return m_IsRunningInbound; }
  70. private set { m_IsRunningInbound = value; }
  71. }
  72. public CancellationTokenSource InboundCancellationSource = new();
  73. /// <summary>Returns true if the server is currently sending outbound packets, otherwise false</summary>
  74. /// <remarks>If IsRunningOut = false, then any request to send a packet is simply dropped.</remarks>
  75. internal bool m_IsRunningOutbound;
  76. public bool IsRunningOutbound
  77. {
  78. get { return m_IsRunningOutbound; }
  79. private set { m_IsRunningOutbound = value; }
  80. }
  81. /// <summary>
  82. /// Number of UDP receives.
  83. /// </summary>
  84. public int UdpReceives { get; private set; }
  85. /// <summary>
  86. /// Number of UDP sends
  87. /// </summary>
  88. public int UdpSends { get; private set; }
  89. /// <summary>
  90. /// Number of receives over which to establish a receive time average.
  91. /// </summary>
  92. private readonly static int s_receiveTimeSamples = 500;
  93. /// <summary>
  94. /// Current number of samples taken to establish a receive time average.
  95. /// </summary>
  96. private int m_currentReceiveTimeSamples;
  97. /// <summary>
  98. /// Cumulative receive time for the sample so far.
  99. /// </summary>
  100. private int m_receiveTicksInCurrentSamplePeriod;
  101. /// <summary>
  102. /// The average time taken for each require receive in the last sample.
  103. /// </summary>
  104. public float AverageReceiveTicksForLastSamplePeriod { get; private set; }
  105. public int Port
  106. {
  107. get { return m_udpPort; }
  108. }
  109. /// <summary>
  110. /// Default constructor
  111. /// </summary>
  112. /// <param name="bindAddress">Local IP address to bind the server to</param>
  113. /// <param name="port">Port to listening for incoming UDP packets on</param>
  114. /// /// <param name="usePool">Are we to use an object pool to get objects for handing inbound data?</param>
  115. public OpenSimUDPBase(IPAddress bindAddress, int port)
  116. {
  117. m_localBindAddress = bindAddress;
  118. m_udpPort = port;
  119. // for debugging purposes only, initializes the random number generator
  120. // used for simulating packet loss
  121. // m_dropRandomGenerator = new Random();
  122. }
  123. ~OpenSimUDPBase()
  124. {
  125. if(m_udpSocket is not null)
  126. try { m_udpSocket.Close(); } catch { }
  127. }
  128. public static UDPPacketBuffer GetNewUDPBuffer(IPEndPoint remoteEndpoint)
  129. {
  130. lock (m_udpBuffersPoolLock)
  131. {
  132. if (m_udpBuffersPoolPtr >= 0)
  133. {
  134. UDPPacketBuffer buf = m_udpBuffersPool[m_udpBuffersPoolPtr];
  135. m_udpBuffersPool[m_udpBuffersPoolPtr] = null;
  136. m_udpBuffersPoolPtr--;
  137. buf.RemoteEndPoint = remoteEndpoint;
  138. buf.DataLength = 0;
  139. return buf;
  140. }
  141. }
  142. return new UDPPacketBuffer(remoteEndpoint);
  143. }
  144. public static void FreeUDPBuffer(UDPPacketBuffer buf)
  145. {
  146. lock (m_udpBuffersPoolLock)
  147. {
  148. if(buf.DataLength < 0)
  149. return; // avoid duplicated free that may still happen
  150. if (m_udpBuffersPoolPtr < 999)
  151. {
  152. buf.RemoteEndPoint = null;
  153. buf.DataLength = -1;
  154. m_udpBuffersPoolPtr++;
  155. m_udpBuffersPool[m_udpBuffersPoolPtr] = buf;
  156. }
  157. }
  158. }
  159. /// <summary>
  160. /// Start inbound UDP packet handling.
  161. /// </summary>
  162. /// <param name="recvBufferSize">The size of the receive buffer for
  163. /// the UDP socket. This value is passed up to the operating system
  164. /// and used in the system networking stack. Use zero to leave this
  165. /// value as the default</param>
  166. public virtual void StartInbound(int recvBufferSize)
  167. {
  168. if (!m_IsRunningInbound)
  169. {
  170. m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop");
  171. const int SIO_UDP_CONNRESET = -1744830452;
  172. m_udpSocket = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  173. try
  174. {
  175. if (m_udpSocket.Ttl < 128)
  176. {
  177. m_udpSocket.Ttl = 128;
  178. }
  179. }
  180. catch (SocketException)
  181. {
  182. m_log.Debug("[UDPBASE]: Failed to increase default TTL");
  183. }
  184. try
  185. {
  186. m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
  187. }
  188. catch
  189. {
  190. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
  191. }
  192. // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment
  193. // we never want two regions to listen on the same port as they cannot demultiplex each other's messages,
  194. // leading to a confusing bug.
  195. // By default, Windows does not allow two sockets to bind to the same port.
  196. //
  197. // Unfortunately, this also causes a crashed sim to leave the socket in a state
  198. // where it appears to be in use but is really just hung from the old process
  199. // crashing rather than closing it. While this protects agains misconfiguration,
  200. // allowing crashed sims to be started up again right away, rather than having to
  201. // wait 2 minutes for the socket to clear is more valuable. Commented 12/13/2016
  202. // m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);
  203. if (recvBufferSize != 0)
  204. m_udpSocket.ReceiveBufferSize = recvBufferSize;
  205. IPEndPoint ipep = new(m_localBindAddress, m_udpPort);
  206. m_udpSocket.Bind(ipep);
  207. if (m_udpPort == 0)
  208. m_udpPort = ((IPEndPoint)m_udpSocket.LocalEndPoint).Port;
  209. m_IsRunningInbound = true;
  210. // kick start the receiver tasks dance.
  211. Task.Run(AsyncBeginReceive).ConfigureAwait(false);
  212. }
  213. }
  214. /// <summary>
  215. /// Start outbound UDP packet handling.
  216. /// </summary>
  217. public virtual void StartOutbound()
  218. {
  219. m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop");
  220. m_IsRunningOutbound = true;
  221. }
  222. public virtual void StopInbound()
  223. {
  224. if (m_IsRunningInbound)
  225. {
  226. m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop");
  227. m_IsRunningInbound = false;
  228. InboundCancellationSource.Cancel();
  229. m_udpSocket.Close();
  230. m_udpSocket = null;
  231. }
  232. }
  233. public virtual void StopOutbound()
  234. {
  235. m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop");
  236. m_IsRunningOutbound = false;
  237. }
  238. private async void AsyncBeginReceive()
  239. {
  240. SocketAddress workSktAddress = new(m_udpSocket.AddressFamily);
  241. while (m_IsRunningInbound)
  242. {
  243. UDPPacketBuffer buf = GetNewUDPBuffer(null); // we need a fresh one here, for now at least
  244. try
  245. {
  246. int nbytes =
  247. await m_udpSocket.ReceiveFromAsync(buf.Data.AsMemory(), SocketFlags.None, workSktAddress, InboundCancellationSource.Token).ConfigureAwait(false);
  248. if (!m_IsRunningInbound || InboundCancellationSource.IsCancellationRequested)
  249. {
  250. FreeUDPBuffer(buf);
  251. return;
  252. }
  253. if (nbytes > 0)
  254. {
  255. int startTick = Util.EnvironmentTickCount();
  256. buf.RemoteEndPoint = Util.GetEndPoint(workSktAddress);
  257. buf.DataLength = nbytes;
  258. UdpReceives++;
  259. PacketReceived(buf);
  260. if (m_currentReceiveTimeSamples >= s_receiveTimeSamples)
  261. {
  262. AverageReceiveTicksForLastSamplePeriod
  263. = (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples;
  264. m_receiveTicksInCurrentSamplePeriod = 0;
  265. m_currentReceiveTimeSamples = 0;
  266. }
  267. else
  268. {
  269. m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick);
  270. m_currentReceiveTimeSamples++;
  271. }
  272. }
  273. else
  274. FreeUDPBuffer(buf);
  275. }
  276. catch (OperationCanceledException)
  277. {
  278. }
  279. catch (Exception e)
  280. {
  281. m_log.Error($"[UDPBASE]: Error processing UDP receiveFrom. Exception ", e);
  282. }
  283. }
  284. }
  285. public void SyncSend(UDPPacketBuffer buf)
  286. {
  287. if(buf.RemoteEndPoint is null)
  288. return; // already expired
  289. try
  290. {
  291. m_udpSocket.SendTo(
  292. buf.Data,
  293. 0,
  294. buf.DataLength,
  295. SocketFlags.None,
  296. buf.RemoteEndPoint
  297. );
  298. UdpSends++;
  299. }
  300. catch (SocketException e)
  301. {
  302. m_log.WarnFormat("[UDPBASE]: sync send SocketException {0} {1}", buf.RemoteEndPoint, e.Message);
  303. }
  304. catch (ObjectDisposedException) { }
  305. }
  306. }
  307. }