OpenSimUDPBase.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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 virtual 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. // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment
  146. // we never want two regions to listen on the same port as they cannot demultiplex each other's messages,
  147. // leading to a confusing bug.
  148. // By default, Windows does not allow two sockets to bind to the same port.
  149. m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);
  150. if (recvBufferSize != 0)
  151. m_udpSocket.ReceiveBufferSize = recvBufferSize;
  152. m_udpSocket.Bind(ipep);
  153. IsRunningInbound = true;
  154. // kick off an async receive. The Start() method will return, the
  155. // actual receives will occur asynchronously and will be caught in
  156. // AsyncEndRecieve().
  157. AsyncBeginReceive();
  158. }
  159. }
  160. /// <summary>
  161. /// Start outbound UDP packet handling.
  162. /// </summary>
  163. public virtual void StartOutbound()
  164. {
  165. m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop");
  166. IsRunningOutbound = true;
  167. }
  168. public virtual void StopInbound()
  169. {
  170. if (IsRunningInbound)
  171. {
  172. m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop");
  173. IsRunningInbound = false;
  174. m_udpSocket.Close();
  175. }
  176. }
  177. public virtual void StopOutbound()
  178. {
  179. m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop");
  180. IsRunningOutbound = false;
  181. }
  182. public virtual bool EnablePools()
  183. {
  184. if (!UsePools)
  185. {
  186. Pool = new Pool<UDPPacketBuffer>(() => new UDPPacketBuffer(), 500);
  187. UsePools = true;
  188. return true;
  189. }
  190. return false;
  191. }
  192. public virtual bool DisablePools()
  193. {
  194. if (UsePools)
  195. {
  196. UsePools = false;
  197. // We won't null out the pool to avoid a race condition with code that may be in the middle of using it.
  198. return true;
  199. }
  200. return false;
  201. }
  202. private void AsyncBeginReceive()
  203. {
  204. UDPPacketBuffer buf;
  205. // FIXME: Disabled for now as this causes issues with reused packet objects interfering with each other
  206. // on Windows with m_asyncPacketHandling = true, though this has not been seen on Linux.
  207. // Possibly some unexpected issue with fetching UDP data concurrently with multiple threads. Requires more investigation.
  208. // if (UsePools)
  209. // buf = Pool.GetObject();
  210. // else
  211. buf = new UDPPacketBuffer();
  212. if (IsRunningInbound)
  213. {
  214. try
  215. {
  216. // kick off an async read
  217. m_udpSocket.BeginReceiveFrom(
  218. //wrappedBuffer.Instance.Data,
  219. buf.Data,
  220. 0,
  221. UDPPacketBuffer.BUFFER_SIZE,
  222. SocketFlags.None,
  223. ref buf.RemoteEndPoint,
  224. AsyncEndReceive,
  225. //wrappedBuffer);
  226. buf);
  227. }
  228. catch (SocketException e)
  229. {
  230. if (e.SocketErrorCode == SocketError.ConnectionReset)
  231. {
  232. m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
  233. bool salvaged = false;
  234. while (!salvaged)
  235. {
  236. try
  237. {
  238. m_udpSocket.BeginReceiveFrom(
  239. //wrappedBuffer.Instance.Data,
  240. buf.Data,
  241. 0,
  242. UDPPacketBuffer.BUFFER_SIZE,
  243. SocketFlags.None,
  244. ref buf.RemoteEndPoint,
  245. AsyncEndReceive,
  246. //wrappedBuffer);
  247. buf);
  248. salvaged = true;
  249. }
  250. catch (SocketException) { }
  251. catch (ObjectDisposedException) { return; }
  252. }
  253. m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
  254. }
  255. }
  256. catch (ObjectDisposedException e)
  257. {
  258. m_log.Error(
  259. string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
  260. }
  261. catch (Exception e)
  262. {
  263. m_log.Error(
  264. string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
  265. }
  266. }
  267. }
  268. private void AsyncEndReceive(IAsyncResult iar)
  269. {
  270. // Asynchronous receive operations will complete here through the call
  271. // to AsyncBeginReceive
  272. if (IsRunningInbound)
  273. {
  274. UdpReceives++;
  275. // Asynchronous mode will start another receive before the
  276. // callback for this packet is even fired. Very parallel :-)
  277. if (m_asyncPacketHandling)
  278. AsyncBeginReceive();
  279. try
  280. {
  281. // get the buffer that was created in AsyncBeginReceive
  282. // this is the received data
  283. UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
  284. int startTick = Util.EnvironmentTickCount();
  285. // get the length of data actually read from the socket, store it with the
  286. // buffer
  287. buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
  288. // call the abstract method PacketReceived(), passing the buffer that
  289. // has just been filled from the socket read.
  290. PacketReceived(buffer);
  291. // If more than one thread can be calling AsyncEndReceive() at once (e.g. if m_asyncPacketHandler)
  292. // then a particular stat may be inaccurate due to a race condition. We won't worry about this
  293. // since this should be rare and won't cause a runtime problem.
  294. if (m_currentReceiveTimeSamples >= s_receiveTimeSamples)
  295. {
  296. AverageReceiveTicksForLastSamplePeriod
  297. = (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples;
  298. m_receiveTicksInCurrentSamplePeriod = 0;
  299. m_currentReceiveTimeSamples = 0;
  300. }
  301. else
  302. {
  303. m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick);
  304. m_currentReceiveTimeSamples++;
  305. }
  306. }
  307. catch (SocketException se)
  308. {
  309. m_log.Error(
  310. string.Format(
  311. "[UDPBASE]: Error processing UDP end receive {0}, socket error code {1}. Exception ",
  312. UdpReceives, se.ErrorCode),
  313. se);
  314. }
  315. catch (ObjectDisposedException e)
  316. {
  317. m_log.Error(
  318. string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
  319. }
  320. catch (Exception e)
  321. {
  322. m_log.Error(
  323. string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
  324. }
  325. finally
  326. {
  327. // if (UsePools)
  328. // Pool.ReturnObject(buffer);
  329. // Synchronous mode waits until the packet callback completes
  330. // before starting the receive to fetch another packet
  331. if (!m_asyncPacketHandling)
  332. AsyncBeginReceive();
  333. }
  334. }
  335. }
  336. public void AsyncBeginSend(UDPPacketBuffer buf)
  337. {
  338. // if (IsRunningOutbound)
  339. // {
  340. try
  341. {
  342. m_udpSocket.BeginSendTo(
  343. buf.Data,
  344. 0,
  345. buf.DataLength,
  346. SocketFlags.None,
  347. buf.RemoteEndPoint,
  348. AsyncEndSend,
  349. buf);
  350. }
  351. catch (SocketException) { }
  352. catch (ObjectDisposedException) { }
  353. // }
  354. }
  355. void AsyncEndSend(IAsyncResult result)
  356. {
  357. try
  358. {
  359. // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
  360. m_udpSocket.EndSendTo(result);
  361. UdpSends++;
  362. }
  363. catch (SocketException) { }
  364. catch (ObjectDisposedException) { }
  365. }
  366. }
  367. }