OpenSimUDPBase.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. namespace OpenMetaverse
  33. {
  34. /// <summary>
  35. /// Base UDP server
  36. /// </summary>
  37. public abstract class OpenSimUDPBase
  38. {
  39. private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  40. /// <summary>
  41. /// This method is called when an incoming packet is received
  42. /// </summary>
  43. /// <param name="buffer">Incoming packet buffer</param>
  44. protected abstract void PacketReceived(UDPPacketBuffer buffer);
  45. /// <summary>UDP port to bind to in server mode</summary>
  46. protected int m_udpPort;
  47. /// <summary>Local IP address to bind to in server mode</summary>
  48. protected IPAddress m_localBindAddress;
  49. /// <summary>UDP socket, used in either client or server mode</summary>
  50. private Socket m_udpSocket;
  51. /// <summary>Flag to process packets asynchronously or synchronously</summary>
  52. private bool m_asyncPacketHandling;
  53. /// <summary>The all important shutdown flag</summary>
  54. private volatile bool m_shutdownFlag = true;
  55. /// <summary>Returns true if the server is currently listening, otherwise false</summary>
  56. public bool IsRunning { get { return !m_shutdownFlag; } }
  57. /// <summary>
  58. /// Default constructor
  59. /// </summary>
  60. /// <param name="bindAddress">Local IP address to bind the server to</param>
  61. /// <param name="port">Port to listening for incoming UDP packets on</param>
  62. public OpenSimUDPBase(IPAddress bindAddress, int port)
  63. {
  64. m_localBindAddress = bindAddress;
  65. m_udpPort = port;
  66. }
  67. /// <summary>
  68. /// Start the UDP server
  69. /// </summary>
  70. /// <param name="recvBufferSize">The size of the receive buffer for
  71. /// the UDP socket. This value is passed up to the operating system
  72. /// and used in the system networking stack. Use zero to leave this
  73. /// value as the default</param>
  74. /// <param name="asyncPacketHandling">Set this to true to start
  75. /// receiving more packets while current packet handler callbacks are
  76. /// still running. Setting this to false will complete each packet
  77. /// callback before the next packet is processed</param>
  78. /// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag
  79. /// on the socket to get newer versions of Windows to behave in a sane
  80. /// manner (not throwing an exception when the remote side resets the
  81. /// connection). This call is ignored on Mono where the flag is not
  82. /// necessary</remarks>
  83. public void Start(int recvBufferSize, bool asyncPacketHandling)
  84. {
  85. m_asyncPacketHandling = asyncPacketHandling;
  86. if (m_shutdownFlag)
  87. {
  88. const int SIO_UDP_CONNRESET = -1744830452;
  89. IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort);
  90. m_udpSocket = new Socket(
  91. AddressFamily.InterNetwork,
  92. SocketType.Dgram,
  93. ProtocolType.Udp);
  94. try
  95. {
  96. // This udp socket flag is not supported under mono,
  97. // so we'll catch the exception and continue
  98. m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
  99. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set");
  100. }
  101. catch (SocketException)
  102. {
  103. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
  104. }
  105. if (recvBufferSize != 0)
  106. m_udpSocket.ReceiveBufferSize = recvBufferSize;
  107. m_udpSocket.Bind(ipep);
  108. // we're not shutting down, we're starting up
  109. m_shutdownFlag = false;
  110. // kick off an async receive. The Start() method will return, the
  111. // actual receives will occur asynchronously and will be caught in
  112. // AsyncEndRecieve().
  113. AsyncBeginReceive();
  114. }
  115. }
  116. /// <summary>
  117. /// Stops the UDP server
  118. /// </summary>
  119. public void Stop()
  120. {
  121. if (!m_shutdownFlag)
  122. {
  123. // wait indefinitely for a writer lock. Once this is called, the .NET runtime
  124. // will deny any more reader locks, in effect blocking all other send/receive
  125. // threads. Once we have the lock, we set shutdownFlag to inform the other
  126. // threads that the socket is closed.
  127. m_shutdownFlag = true;
  128. m_udpSocket.Close();
  129. }
  130. }
  131. private void AsyncBeginReceive()
  132. {
  133. // allocate a packet buffer
  134. //WrappedObject<UDPPacketBuffer> wrappedBuffer = Pool.CheckOut();
  135. UDPPacketBuffer buf = new UDPPacketBuffer();
  136. if (!m_shutdownFlag)
  137. {
  138. try
  139. {
  140. // kick off an async read
  141. m_udpSocket.BeginReceiveFrom(
  142. //wrappedBuffer.Instance.Data,
  143. buf.Data,
  144. 0,
  145. UDPPacketBuffer.BUFFER_SIZE,
  146. SocketFlags.None,
  147. ref buf.RemoteEndPoint,
  148. AsyncEndReceive,
  149. //wrappedBuffer);
  150. buf);
  151. }
  152. catch (SocketException e)
  153. {
  154. if (e.SocketErrorCode == SocketError.ConnectionReset)
  155. {
  156. m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
  157. bool salvaged = false;
  158. while (!salvaged)
  159. {
  160. try
  161. {
  162. m_udpSocket.BeginReceiveFrom(
  163. //wrappedBuffer.Instance.Data,
  164. buf.Data,
  165. 0,
  166. UDPPacketBuffer.BUFFER_SIZE,
  167. SocketFlags.None,
  168. ref buf.RemoteEndPoint,
  169. AsyncEndReceive,
  170. //wrappedBuffer);
  171. buf);
  172. salvaged = true;
  173. }
  174. catch (SocketException) { }
  175. catch (ObjectDisposedException) { return; }
  176. }
  177. m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
  178. }
  179. }
  180. catch (ObjectDisposedException) { }
  181. }
  182. }
  183. private void AsyncEndReceive(IAsyncResult iar)
  184. {
  185. // Asynchronous receive operations will complete here through the call
  186. // to AsyncBeginReceive
  187. if (!m_shutdownFlag)
  188. {
  189. // Asynchronous mode will start another receive before the
  190. // callback for this packet is even fired. Very parallel :-)
  191. if (m_asyncPacketHandling)
  192. AsyncBeginReceive();
  193. // get the buffer that was created in AsyncBeginReceive
  194. // this is the received data
  195. //WrappedObject<UDPPacketBuffer> wrappedBuffer = (WrappedObject<UDPPacketBuffer>)iar.AsyncState;
  196. //UDPPacketBuffer buffer = wrappedBuffer.Instance;
  197. UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
  198. try
  199. {
  200. // get the length of data actually read from the socket, store it with the
  201. // buffer
  202. buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
  203. // call the abstract method PacketReceived(), passing the buffer that
  204. // has just been filled from the socket read.
  205. PacketReceived(buffer);
  206. }
  207. catch (SocketException) { }
  208. catch (ObjectDisposedException) { }
  209. finally
  210. {
  211. //wrappedBuffer.Dispose();
  212. // Synchronous mode waits until the packet callback completes
  213. // before starting the receive to fetch another packet
  214. if (!m_asyncPacketHandling)
  215. AsyncBeginReceive();
  216. }
  217. }
  218. }
  219. public void AsyncBeginSend(UDPPacketBuffer buf)
  220. {
  221. if (!m_shutdownFlag)
  222. {
  223. try
  224. {
  225. m_udpSocket.BeginSendTo(
  226. buf.Data,
  227. 0,
  228. buf.DataLength,
  229. SocketFlags.None,
  230. buf.RemoteEndPoint,
  231. AsyncEndSend,
  232. buf);
  233. }
  234. catch (SocketException) { }
  235. catch (ObjectDisposedException) { }
  236. }
  237. }
  238. void AsyncEndSend(IAsyncResult result)
  239. {
  240. try
  241. {
  242. // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
  243. m_udpSocket.EndSendTo(result);
  244. }
  245. catch (SocketException) { }
  246. catch (ObjectDisposedException) { }
  247. }
  248. }
  249. }