OpenSimUDPBase.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. /// Number of UDP receives.
  70. /// </summary>
  71. public int UdpReceives { get; private set; }
  72. /// <summary>
  73. /// Number of UDP sends
  74. /// </summary>
  75. public int UdpSends { get; private set; }
  76. /// <summary>
  77. /// Number of receives over which to establish a receive time average.
  78. /// </summary>
  79. private readonly static int s_receiveTimeSamples = 500;
  80. /// <summary>
  81. /// Current number of samples taken to establish a receive time average.
  82. /// </summary>
  83. private int m_currentReceiveTimeSamples;
  84. /// <summary>
  85. /// Cumulative receive time for the sample so far.
  86. /// </summary>
  87. private int m_receiveTicksInCurrentSamplePeriod;
  88. /// <summary>
  89. /// The average time taken for each require receive in the last sample.
  90. /// </summary>
  91. public float AverageReceiveTicksForLastSamplePeriod { get; private set; }
  92. /// <summary>
  93. /// Default constructor
  94. /// </summary>
  95. /// <param name="bindAddress">Local IP address to bind the server to</param>
  96. /// <param name="port">Port to listening for incoming UDP packets on</param>
  97. /// /// <param name="usePool">Are we to use an object pool to get objects for handing inbound data?</param>
  98. public OpenSimUDPBase(IPAddress bindAddress, int port)
  99. {
  100. m_localBindAddress = bindAddress;
  101. m_udpPort = port;
  102. }
  103. /// <summary>
  104. /// Start inbound UDP packet handling.
  105. /// </summary>
  106. /// <param name="recvBufferSize">The size of the receive buffer for
  107. /// the UDP socket. This value is passed up to the operating system
  108. /// and used in the system networking stack. Use zero to leave this
  109. /// value as the default</param>
  110. /// <param name="asyncPacketHandling">Set this to true to start
  111. /// receiving more packets while current packet handler callbacks are
  112. /// still running. Setting this to false will complete each packet
  113. /// callback before the next packet is processed</param>
  114. /// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag
  115. /// on the socket to get newer versions of Windows to behave in a sane
  116. /// manner (not throwing an exception when the remote side resets the
  117. /// connection). This call is ignored on Mono where the flag is not
  118. /// necessary</remarks>
  119. public void StartInbound(int recvBufferSize, bool asyncPacketHandling)
  120. {
  121. m_asyncPacketHandling = asyncPacketHandling;
  122. if (!IsRunningInbound)
  123. {
  124. m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop");
  125. const int SIO_UDP_CONNRESET = -1744830452;
  126. IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort);
  127. m_log.DebugFormat(
  128. "[UDPBASE]: Binding UDP listener using internal IP address config {0}:{1}",
  129. ipep.Address, ipep.Port);
  130. m_udpSocket = new Socket(
  131. AddressFamily.InterNetwork,
  132. SocketType.Dgram,
  133. ProtocolType.Udp);
  134. try
  135. {
  136. // This udp socket flag is not supported under mono,
  137. // so we'll catch the exception and continue
  138. m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
  139. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set");
  140. }
  141. catch (SocketException)
  142. {
  143. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
  144. }
  145. if (recvBufferSize != 0)
  146. m_udpSocket.ReceiveBufferSize = recvBufferSize;
  147. m_udpSocket.Bind(ipep);
  148. IsRunningInbound = true;
  149. // kick off an async receive. The Start() method will return, the
  150. // actual receives will occur asynchronously and will be caught in
  151. // AsyncEndRecieve().
  152. AsyncBeginReceive();
  153. }
  154. }
  155. /// <summary>
  156. /// Start outbound UDP packet handling.
  157. /// </summary>
  158. public void StartOutbound()
  159. {
  160. m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop");
  161. IsRunningOutbound = true;
  162. }
  163. public void StopInbound()
  164. {
  165. if (IsRunningInbound)
  166. {
  167. m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop");
  168. IsRunningInbound = false;
  169. m_udpSocket.Close();
  170. }
  171. }
  172. public void StopOutbound()
  173. {
  174. m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop");
  175. IsRunningOutbound = false;
  176. }
  177. protected virtual bool EnablePools()
  178. {
  179. if (!UsePools)
  180. {
  181. Pool = new Pool<UDPPacketBuffer>(() => new UDPPacketBuffer(), 500);
  182. UsePools = true;
  183. return true;
  184. }
  185. return false;
  186. }
  187. protected virtual bool DisablePools()
  188. {
  189. if (UsePools)
  190. {
  191. UsePools = false;
  192. // We won't null out the pool to avoid a race condition with code that may be in the middle of using it.
  193. return true;
  194. }
  195. return false;
  196. }
  197. private void AsyncBeginReceive()
  198. {
  199. UDPPacketBuffer buf;
  200. // FIXME: Disabled for now as this causes issues with reused packet objects interfering with each other
  201. // on Windows with m_asyncPacketHandling = true, though this has not been seen on Linux.
  202. // Possibly some unexpected issue with fetching UDP data concurrently with multiple threads. Requires more investigation.
  203. // if (UsePools)
  204. // buf = Pool.GetObject();
  205. // else
  206. buf = new UDPPacketBuffer();
  207. if (IsRunningInbound)
  208. {
  209. try
  210. {
  211. // kick off an async read
  212. m_udpSocket.BeginReceiveFrom(
  213. //wrappedBuffer.Instance.Data,
  214. buf.Data,
  215. 0,
  216. UDPPacketBuffer.BUFFER_SIZE,
  217. SocketFlags.None,
  218. ref buf.RemoteEndPoint,
  219. AsyncEndReceive,
  220. //wrappedBuffer);
  221. buf);
  222. }
  223. catch (SocketException e)
  224. {
  225. if (e.SocketErrorCode == SocketError.ConnectionReset)
  226. {
  227. m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
  228. bool salvaged = false;
  229. while (!salvaged)
  230. {
  231. try
  232. {
  233. m_udpSocket.BeginReceiveFrom(
  234. //wrappedBuffer.Instance.Data,
  235. buf.Data,
  236. 0,
  237. UDPPacketBuffer.BUFFER_SIZE,
  238. SocketFlags.None,
  239. ref buf.RemoteEndPoint,
  240. AsyncEndReceive,
  241. //wrappedBuffer);
  242. buf);
  243. salvaged = true;
  244. }
  245. catch (SocketException) { }
  246. catch (ObjectDisposedException) { return; }
  247. }
  248. m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
  249. }
  250. }
  251. catch (ObjectDisposedException e)
  252. {
  253. m_log.Error(
  254. string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
  255. }
  256. catch (Exception e)
  257. {
  258. m_log.Error(
  259. string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
  260. }
  261. }
  262. }
  263. private void AsyncEndReceive(IAsyncResult iar)
  264. {
  265. // Asynchronous receive operations will complete here through the call
  266. // to AsyncBeginReceive
  267. if (IsRunningInbound)
  268. {
  269. UdpReceives++;
  270. // Asynchronous mode will start another receive before the
  271. // callback for this packet is even fired. Very parallel :-)
  272. if (m_asyncPacketHandling)
  273. AsyncBeginReceive();
  274. try
  275. {
  276. // get the buffer that was created in AsyncBeginReceive
  277. // this is the received data
  278. UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
  279. int startTick = Util.EnvironmentTickCount();
  280. // get the length of data actually read from the socket, store it with the
  281. // buffer
  282. buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
  283. // call the abstract method PacketReceived(), passing the buffer that
  284. // has just been filled from the socket read.
  285. PacketReceived(buffer);
  286. // If more than one thread can be calling AsyncEndReceive() at once (e.g. if m_asyncPacketHandler)
  287. // then a particular stat may be inaccurate due to a race condition. We won't worry about this
  288. // since this should be rare and won't cause a runtime problem.
  289. if (m_currentReceiveTimeSamples >= s_receiveTimeSamples)
  290. {
  291. AverageReceiveTicksForLastSamplePeriod
  292. = (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples;
  293. m_receiveTicksInCurrentSamplePeriod = 0;
  294. m_currentReceiveTimeSamples = 0;
  295. }
  296. else
  297. {
  298. m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick);
  299. m_currentReceiveTimeSamples++;
  300. }
  301. }
  302. catch (SocketException se)
  303. {
  304. m_log.Error(
  305. string.Format(
  306. "[UDPBASE]: Error processing UDP end receive {0}, socket error code {1}. Exception ",
  307. UdpReceives, se.ErrorCode),
  308. se);
  309. }
  310. catch (ObjectDisposedException e)
  311. {
  312. m_log.Error(
  313. string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
  314. }
  315. catch (Exception e)
  316. {
  317. m_log.Error(
  318. string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
  319. }
  320. finally
  321. {
  322. // if (UsePools)
  323. // Pool.ReturnObject(buffer);
  324. // Synchronous mode waits until the packet callback completes
  325. // before starting the receive to fetch another packet
  326. if (!m_asyncPacketHandling)
  327. AsyncBeginReceive();
  328. }
  329. }
  330. }
  331. public void AsyncBeginSend(UDPPacketBuffer buf)
  332. {
  333. // if (IsRunningOutbound)
  334. // {
  335. try
  336. {
  337. m_udpSocket.BeginSendTo(
  338. buf.Data,
  339. 0,
  340. buf.DataLength,
  341. SocketFlags.None,
  342. buf.RemoteEndPoint,
  343. AsyncEndSend,
  344. buf);
  345. }
  346. catch (SocketException) { }
  347. catch (ObjectDisposedException) { }
  348. // }
  349. }
  350. void AsyncEndSend(IAsyncResult result)
  351. {
  352. try
  353. {
  354. // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
  355. m_udpSocket.EndSendTo(result);
  356. UdpSends++;
  357. }
  358. catch (SocketException) { }
  359. catch (ObjectDisposedException) { }
  360. }
  361. }
  362. }