OpenSimUDPBase.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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>Flag to process packets asynchronously or synchronously</summary>
  54. private bool m_asyncPacketHandling;
  55. /// <summary>
  56. /// Are we to use object pool(s) to reduce memory churn when receiving data?
  57. /// </summary>
  58. public bool UsePools { get; protected set; }
  59. /// <summary>
  60. /// Pool to use for handling data. May be null if UsePools = false;
  61. /// </summary>
  62. protected OpenSim.Framework.Pool<UDPPacketBuffer> Pool { get; private set; }
  63. /// <summary>Returns true if the server is currently listening for inbound packets, otherwise false</summary>
  64. public bool IsRunningInbound { get; private set; }
  65. /// <summary>Returns true if the server is currently sending outbound packets, otherwise false</summary>
  66. /// <remarks>If IsRunningOut = false, then any request to send a packet is simply dropped.</remarks>
  67. public bool IsRunningOutbound { get; private set; }
  68. /// <summary>
  69. /// Default constructor
  70. /// </summary>
  71. /// <param name="bindAddress">Local IP address to bind the server to</param>
  72. /// <param name="port">Port to listening for incoming UDP packets on</param>
  73. /// /// <param name="usePool">Are we to use an object pool to get objects for handing inbound data?</param>
  74. public OpenSimUDPBase(IPAddress bindAddress, int port)
  75. {
  76. m_localBindAddress = bindAddress;
  77. m_udpPort = port;
  78. }
  79. /// <summary>
  80. /// Start inbound UDP packet handling.
  81. /// </summary>
  82. /// <param name="recvBufferSize">The size of the receive buffer for
  83. /// the UDP socket. This value is passed up to the operating system
  84. /// and used in the system networking stack. Use zero to leave this
  85. /// value as the default</param>
  86. /// <param name="asyncPacketHandling">Set this to true to start
  87. /// receiving more packets while current packet handler callbacks are
  88. /// still running. Setting this to false will complete each packet
  89. /// callback before the next packet is processed</param>
  90. /// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag
  91. /// on the socket to get newer versions of Windows to behave in a sane
  92. /// manner (not throwing an exception when the remote side resets the
  93. /// connection). This call is ignored on Mono where the flag is not
  94. /// necessary</remarks>
  95. public void StartInbound(int recvBufferSize, bool asyncPacketHandling)
  96. {
  97. m_asyncPacketHandling = asyncPacketHandling;
  98. if (!IsRunningInbound)
  99. {
  100. const int SIO_UDP_CONNRESET = -1744830452;
  101. IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort);
  102. m_log.DebugFormat(
  103. "[UDPBASE]: Binding UDP listener using internal IP address config {0}:{1}",
  104. ipep.Address, ipep.Port);
  105. m_udpSocket = new Socket(
  106. AddressFamily.InterNetwork,
  107. SocketType.Dgram,
  108. ProtocolType.Udp);
  109. try
  110. {
  111. // This udp socket flag is not supported under mono,
  112. // so we'll catch the exception and continue
  113. m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
  114. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set");
  115. }
  116. catch (SocketException)
  117. {
  118. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
  119. }
  120. if (recvBufferSize != 0)
  121. m_udpSocket.ReceiveBufferSize = recvBufferSize;
  122. m_udpSocket.Bind(ipep);
  123. IsRunningInbound = true;
  124. // kick off an async receive. The Start() method will return, the
  125. // actual receives will occur asynchronously and will be caught in
  126. // AsyncEndRecieve().
  127. AsyncBeginReceive();
  128. }
  129. }
  130. /// <summary>
  131. /// Start outbound UDP packet handling.
  132. /// </summary>
  133. public void StartOutbound()
  134. {
  135. IsRunningOutbound = true;
  136. }
  137. public void StopInbound()
  138. {
  139. if (IsRunningInbound)
  140. {
  141. // wait indefinitely for a writer lock. Once this is called, the .NET runtime
  142. // will deny any more reader locks, in effect blocking all other send/receive
  143. // threads. Once we have the lock, we set IsRunningInbound = false to inform the other
  144. // threads that the socket is closed.
  145. IsRunningInbound = false;
  146. m_udpSocket.Close();
  147. }
  148. }
  149. public void StopOutbound()
  150. {
  151. IsRunningOutbound = false;
  152. }
  153. protected virtual bool EnablePools()
  154. {
  155. if (!UsePools)
  156. {
  157. Pool = new Pool<UDPPacketBuffer>(() => new UDPPacketBuffer(), 500);
  158. UsePools = true;
  159. return true;
  160. }
  161. return false;
  162. }
  163. protected virtual bool DisablePools()
  164. {
  165. if (UsePools)
  166. {
  167. UsePools = false;
  168. // We won't null out the pool to avoid a race condition with code that may be in the middle of using it.
  169. return true;
  170. }
  171. return false;
  172. }
  173. private void AsyncBeginReceive()
  174. {
  175. UDPPacketBuffer buf;
  176. if (UsePools)
  177. buf = Pool.GetObject();
  178. else
  179. buf = new UDPPacketBuffer();
  180. if (IsRunningInbound)
  181. {
  182. try
  183. {
  184. // kick off an async read
  185. m_udpSocket.BeginReceiveFrom(
  186. //wrappedBuffer.Instance.Data,
  187. buf.Data,
  188. 0,
  189. UDPPacketBuffer.BUFFER_SIZE,
  190. SocketFlags.None,
  191. ref buf.RemoteEndPoint,
  192. AsyncEndReceive,
  193. //wrappedBuffer);
  194. buf);
  195. }
  196. catch (SocketException e)
  197. {
  198. if (e.SocketErrorCode == SocketError.ConnectionReset)
  199. {
  200. m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
  201. bool salvaged = false;
  202. while (!salvaged)
  203. {
  204. try
  205. {
  206. m_udpSocket.BeginReceiveFrom(
  207. //wrappedBuffer.Instance.Data,
  208. buf.Data,
  209. 0,
  210. UDPPacketBuffer.BUFFER_SIZE,
  211. SocketFlags.None,
  212. ref buf.RemoteEndPoint,
  213. AsyncEndReceive,
  214. //wrappedBuffer);
  215. buf);
  216. salvaged = true;
  217. }
  218. catch (SocketException) { }
  219. catch (ObjectDisposedException) { return; }
  220. }
  221. m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
  222. }
  223. }
  224. catch (ObjectDisposedException) { }
  225. }
  226. }
  227. private void AsyncEndReceive(IAsyncResult iar)
  228. {
  229. // Asynchronous receive operations will complete here through the call
  230. // to AsyncBeginReceive
  231. if (IsRunningInbound)
  232. {
  233. // Asynchronous mode will start another receive before the
  234. // callback for this packet is even fired. Very parallel :-)
  235. if (m_asyncPacketHandling)
  236. AsyncBeginReceive();
  237. // get the buffer that was created in AsyncBeginReceive
  238. // this is the received data
  239. UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
  240. try
  241. {
  242. // get the length of data actually read from the socket, store it with the
  243. // buffer
  244. buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
  245. // call the abstract method PacketReceived(), passing the buffer that
  246. // has just been filled from the socket read.
  247. PacketReceived(buffer);
  248. }
  249. catch (SocketException) { }
  250. catch (ObjectDisposedException) { }
  251. finally
  252. {
  253. if (UsePools)
  254. Pool.ReturnObject(buffer);
  255. // Synchronous mode waits until the packet callback completes
  256. // before starting the receive to fetch another packet
  257. if (!m_asyncPacketHandling)
  258. AsyncBeginReceive();
  259. }
  260. }
  261. }
  262. public void AsyncBeginSend(UDPPacketBuffer buf)
  263. {
  264. if (IsRunningOutbound)
  265. {
  266. try
  267. {
  268. m_udpSocket.BeginSendTo(
  269. buf.Data,
  270. 0,
  271. buf.DataLength,
  272. SocketFlags.None,
  273. buf.RemoteEndPoint,
  274. AsyncEndSend,
  275. buf);
  276. }
  277. catch (SocketException) { }
  278. catch (ObjectDisposedException) { }
  279. }
  280. }
  281. void AsyncEndSend(IAsyncResult result)
  282. {
  283. try
  284. {
  285. // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
  286. m_udpSocket.EndSendTo(result);
  287. }
  288. catch (SocketException) { }
  289. catch (ObjectDisposedException) { }
  290. }
  291. }
  292. }