1
0

OpenSimUDPBase.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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_log.DebugFormat(
  91. "[UDPBASE]: Binding UDP listener using internal IP address config {0}:{1}",
  92. ipep.Address, ipep.Port);
  93. m_udpSocket = new Socket(
  94. AddressFamily.InterNetwork,
  95. SocketType.Dgram,
  96. ProtocolType.Udp);
  97. try
  98. {
  99. // This udp socket flag is not supported under mono,
  100. // so we'll catch the exception and continue
  101. m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
  102. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set");
  103. }
  104. catch (SocketException)
  105. {
  106. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
  107. }
  108. if (recvBufferSize != 0)
  109. m_udpSocket.ReceiveBufferSize = recvBufferSize;
  110. m_udpSocket.Bind(ipep);
  111. // we're not shutting down, we're starting up
  112. m_shutdownFlag = false;
  113. // kick off an async receive. The Start() method will return, the
  114. // actual receives will occur asynchronously and will be caught in
  115. // AsyncEndRecieve().
  116. AsyncBeginReceive();
  117. }
  118. }
  119. /// <summary>
  120. /// Stops the UDP server
  121. /// </summary>
  122. public void Stop()
  123. {
  124. if (!m_shutdownFlag)
  125. {
  126. // wait indefinitely for a writer lock. Once this is called, the .NET runtime
  127. // will deny any more reader locks, in effect blocking all other send/receive
  128. // threads. Once we have the lock, we set shutdownFlag to inform the other
  129. // threads that the socket is closed.
  130. m_shutdownFlag = true;
  131. m_udpSocket.Close();
  132. }
  133. }
  134. private void AsyncBeginReceive()
  135. {
  136. // allocate a packet buffer
  137. //WrappedObject<UDPPacketBuffer> wrappedBuffer = Pool.CheckOut();
  138. UDPPacketBuffer buf = new UDPPacketBuffer();
  139. if (!m_shutdownFlag)
  140. {
  141. try
  142. {
  143. // kick off an async read
  144. m_udpSocket.BeginReceiveFrom(
  145. //wrappedBuffer.Instance.Data,
  146. buf.Data,
  147. 0,
  148. UDPPacketBuffer.BUFFER_SIZE,
  149. SocketFlags.None,
  150. ref buf.RemoteEndPoint,
  151. AsyncEndReceive,
  152. //wrappedBuffer);
  153. buf);
  154. }
  155. catch (SocketException e)
  156. {
  157. if (e.SocketErrorCode == SocketError.ConnectionReset)
  158. {
  159. m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
  160. bool salvaged = false;
  161. while (!salvaged)
  162. {
  163. try
  164. {
  165. m_udpSocket.BeginReceiveFrom(
  166. //wrappedBuffer.Instance.Data,
  167. buf.Data,
  168. 0,
  169. UDPPacketBuffer.BUFFER_SIZE,
  170. SocketFlags.None,
  171. ref buf.RemoteEndPoint,
  172. AsyncEndReceive,
  173. //wrappedBuffer);
  174. buf);
  175. salvaged = true;
  176. }
  177. catch (SocketException) { }
  178. catch (ObjectDisposedException) { return; }
  179. }
  180. m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
  181. }
  182. }
  183. catch (ObjectDisposedException) { }
  184. }
  185. }
  186. private void AsyncEndReceive(IAsyncResult iar)
  187. {
  188. // Asynchronous receive operations will complete here through the call
  189. // to AsyncBeginReceive
  190. if (!m_shutdownFlag)
  191. {
  192. // Asynchronous mode will start another receive before the
  193. // callback for this packet is even fired. Very parallel :-)
  194. if (m_asyncPacketHandling)
  195. AsyncBeginReceive();
  196. // get the buffer that was created in AsyncBeginReceive
  197. // this is the received data
  198. //WrappedObject<UDPPacketBuffer> wrappedBuffer = (WrappedObject<UDPPacketBuffer>)iar.AsyncState;
  199. //UDPPacketBuffer buffer = wrappedBuffer.Instance;
  200. UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
  201. try
  202. {
  203. // get the length of data actually read from the socket, store it with the
  204. // buffer
  205. buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
  206. // call the abstract method PacketReceived(), passing the buffer that
  207. // has just been filled from the socket read.
  208. PacketReceived(buffer);
  209. }
  210. catch (SocketException) { }
  211. catch (ObjectDisposedException) { }
  212. finally
  213. {
  214. //wrappedBuffer.Dispose();
  215. // Synchronous mode waits until the packet callback completes
  216. // before starting the receive to fetch another packet
  217. if (!m_asyncPacketHandling)
  218. AsyncBeginReceive();
  219. }
  220. }
  221. }
  222. public void AsyncBeginSend(UDPPacketBuffer buf)
  223. {
  224. if (!m_shutdownFlag)
  225. {
  226. try
  227. {
  228. m_udpSocket.BeginSendTo(
  229. buf.Data,
  230. 0,
  231. buf.DataLength,
  232. SocketFlags.None,
  233. buf.RemoteEndPoint,
  234. AsyncEndSend,
  235. buf);
  236. }
  237. catch (SocketException) { }
  238. catch (ObjectDisposedException) { }
  239. }
  240. }
  241. void AsyncEndSend(IAsyncResult result)
  242. {
  243. try
  244. {
  245. // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
  246. m_udpSocket.EndSendTo(result);
  247. }
  248. catch (SocketException) { }
  249. catch (ObjectDisposedException) { }
  250. }
  251. }
  252. }