1
0

OpenSimUDPBase.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. #region PacketDropDebugging
  93. /// <summary>
  94. /// For debugging purposes only... random number generator for dropping
  95. /// outbound packets.
  96. /// </summary>
  97. private Random m_dropRandomGenerator;
  98. /// <summary>
  99. /// For debugging purposes only... parameters for a simplified
  100. /// model of packet loss with bursts, overall drop rate should
  101. /// be roughly 1 - m_dropLengthProbability / (m_dropProbabiliy + m_dropLengthProbability)
  102. /// which is about 1% for parameters 0.0015 and 0.15
  103. /// </summary>
  104. private double m_dropProbability = 0.0030;
  105. private double m_dropLengthProbability = 0.15;
  106. private bool m_dropState = false;
  107. /// <summary>
  108. /// For debugging purposes only... parameters to control the time
  109. /// duration over which packet loss bursts can occur, if no packets
  110. /// have been sent for m_dropResetTicks milliseconds, then reset the
  111. /// state of the packet dropper to its default.
  112. /// </summary>
  113. private int m_dropLastTick = 0;
  114. private int m_dropResetTicks = 500;
  115. /// <summary>
  116. /// Debugging code used to simulate dropped packets with bursts
  117. /// </summary>
  118. private bool DropOutgoingPacket()
  119. {
  120. double rnum = m_dropRandomGenerator.NextDouble();
  121. // if the connection has been idle for awhile (more than m_dropResetTicks) then
  122. // reset the state to the default state, don't continue a burst
  123. int curtick = Util.EnvironmentTickCount();
  124. if (Util.EnvironmentTickCountSubtract(curtick, m_dropLastTick) > m_dropResetTicks)
  125. m_dropState = false;
  126. m_dropLastTick = curtick;
  127. // if we are dropping packets, then the probability of dropping
  128. // this packet is the probability that we stay in the burst
  129. if (m_dropState)
  130. {
  131. m_dropState = (rnum < (1.0 - m_dropLengthProbability)) ? true : false;
  132. }
  133. else
  134. {
  135. m_dropState = (rnum < m_dropProbability) ? true : false;
  136. }
  137. return m_dropState;
  138. }
  139. #endregion PacketDropDebugging
  140. /// <summary>
  141. /// Default constructor
  142. /// </summary>
  143. /// <param name="bindAddress">Local IP address to bind the server to</param>
  144. /// <param name="port">Port to listening for incoming UDP packets on</param>
  145. /// /// <param name="usePool">Are we to use an object pool to get objects for handing inbound data?</param>
  146. public OpenSimUDPBase(IPAddress bindAddress, int port)
  147. {
  148. m_localBindAddress = bindAddress;
  149. m_udpPort = port;
  150. // for debugging purposes only, initializes the random number generator
  151. // used for simulating packet loss
  152. // m_dropRandomGenerator = new Random();
  153. }
  154. /// <summary>
  155. /// Start inbound UDP packet handling.
  156. /// </summary>
  157. /// <param name="recvBufferSize">The size of the receive buffer for
  158. /// the UDP socket. This value is passed up to the operating system
  159. /// and used in the system networking stack. Use zero to leave this
  160. /// value as the default</param>
  161. /// <param name="asyncPacketHandling">Set this to true to start
  162. /// receiving more packets while current packet handler callbacks are
  163. /// still running. Setting this to false will complete each packet
  164. /// callback before the next packet is processed</param>
  165. /// <remarks>This method will attempt to set the SIO_UDP_CONNRESET flag
  166. /// on the socket to get newer versions of Windows to behave in a sane
  167. /// manner (not throwing an exception when the remote side resets the
  168. /// connection). This call is ignored on Mono where the flag is not
  169. /// necessary</remarks>
  170. public virtual void StartInbound(int recvBufferSize, bool asyncPacketHandling)
  171. {
  172. m_asyncPacketHandling = asyncPacketHandling;
  173. if (!IsRunningInbound)
  174. {
  175. m_log.DebugFormat("[UDPBASE]: Starting inbound UDP loop");
  176. const int SIO_UDP_CONNRESET = -1744830452;
  177. IPEndPoint ipep = new IPEndPoint(m_localBindAddress, m_udpPort);
  178. m_log.DebugFormat(
  179. "[UDPBASE]: Binding UDP listener using internal IP address config {0}:{1}",
  180. ipep.Address, ipep.Port);
  181. m_udpSocket = new Socket(
  182. AddressFamily.InterNetwork,
  183. SocketType.Dgram,
  184. ProtocolType.Udp);
  185. try
  186. {
  187. // This udp socket flag is not supported under mono,
  188. // so we'll catch the exception and continue
  189. m_udpSocket.IOControl(SIO_UDP_CONNRESET, new byte[] { 0 }, null);
  190. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag set");
  191. }
  192. catch (SocketException)
  193. {
  194. m_log.Debug("[UDPBASE]: SIO_UDP_CONNRESET flag not supported on this platform, ignoring");
  195. }
  196. // On at least Mono 3.2.8, multiple UDP sockets can bind to the same port by default. At the moment
  197. // we never want two regions to listen on the same port as they cannot demultiplex each other's messages,
  198. // leading to a confusing bug.
  199. // By default, Windows does not allow two sockets to bind to the same port.
  200. m_udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false);
  201. if (recvBufferSize != 0)
  202. m_udpSocket.ReceiveBufferSize = recvBufferSize;
  203. m_udpSocket.Bind(ipep);
  204. IsRunningInbound = true;
  205. // kick off an async receive. The Start() method will return, the
  206. // actual receives will occur asynchronously and will be caught in
  207. // AsyncEndRecieve().
  208. AsyncBeginReceive();
  209. }
  210. }
  211. /// <summary>
  212. /// Start outbound UDP packet handling.
  213. /// </summary>
  214. public virtual void StartOutbound()
  215. {
  216. m_log.DebugFormat("[UDPBASE]: Starting outbound UDP loop");
  217. IsRunningOutbound = true;
  218. }
  219. public virtual void StopInbound()
  220. {
  221. if (IsRunningInbound)
  222. {
  223. m_log.DebugFormat("[UDPBASE]: Stopping inbound UDP loop");
  224. IsRunningInbound = false;
  225. m_udpSocket.Close();
  226. }
  227. }
  228. public virtual void StopOutbound()
  229. {
  230. m_log.DebugFormat("[UDPBASE]: Stopping outbound UDP loop");
  231. IsRunningOutbound = false;
  232. }
  233. public virtual bool EnablePools()
  234. {
  235. if (!UsePools)
  236. {
  237. Pool = new Pool<UDPPacketBuffer>(() => new UDPPacketBuffer(), 500);
  238. UsePools = true;
  239. return true;
  240. }
  241. return false;
  242. }
  243. public virtual bool DisablePools()
  244. {
  245. if (UsePools)
  246. {
  247. UsePools = false;
  248. // We won't null out the pool to avoid a race condition with code that may be in the middle of using it.
  249. return true;
  250. }
  251. return false;
  252. }
  253. private void AsyncBeginReceive()
  254. {
  255. UDPPacketBuffer buf;
  256. // FIXME: Disabled for now as this causes issues with reused packet objects interfering with each other
  257. // on Windows with m_asyncPacketHandling = true, though this has not been seen on Linux.
  258. // Possibly some unexpected issue with fetching UDP data concurrently with multiple threads. Requires more investigation.
  259. // if (UsePools)
  260. // buf = Pool.GetObject();
  261. // else
  262. buf = new UDPPacketBuffer();
  263. if (IsRunningInbound)
  264. {
  265. try
  266. {
  267. // kick off an async read
  268. m_udpSocket.BeginReceiveFrom(
  269. //wrappedBuffer.Instance.Data,
  270. buf.Data,
  271. 0,
  272. UDPPacketBuffer.BUFFER_SIZE,
  273. SocketFlags.None,
  274. ref buf.RemoteEndPoint,
  275. AsyncEndReceive,
  276. //wrappedBuffer);
  277. buf);
  278. }
  279. catch (SocketException e)
  280. {
  281. if (e.SocketErrorCode == SocketError.ConnectionReset)
  282. {
  283. m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
  284. bool salvaged = false;
  285. while (!salvaged)
  286. {
  287. try
  288. {
  289. m_udpSocket.BeginReceiveFrom(
  290. //wrappedBuffer.Instance.Data,
  291. buf.Data,
  292. 0,
  293. UDPPacketBuffer.BUFFER_SIZE,
  294. SocketFlags.None,
  295. ref buf.RemoteEndPoint,
  296. AsyncEndReceive,
  297. //wrappedBuffer);
  298. buf);
  299. salvaged = true;
  300. }
  301. catch (SocketException) { }
  302. catch (ObjectDisposedException) { return; }
  303. }
  304. m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
  305. }
  306. }
  307. catch (ObjectDisposedException e)
  308. {
  309. m_log.Error(
  310. string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
  311. }
  312. catch (Exception e)
  313. {
  314. m_log.Error(
  315. string.Format("[UDPBASE]: Error processing UDP begin receive {0}. Exception ", UdpReceives), e);
  316. }
  317. }
  318. }
  319. private void AsyncEndReceive(IAsyncResult iar)
  320. {
  321. // Asynchronous receive operations will complete here through the call
  322. // to AsyncBeginReceive
  323. if (IsRunningInbound)
  324. {
  325. UdpReceives++;
  326. // Asynchronous mode will start another receive before the
  327. // callback for this packet is even fired. Very parallel :-)
  328. if (m_asyncPacketHandling)
  329. AsyncBeginReceive();
  330. try
  331. {
  332. // get the buffer that was created in AsyncBeginReceive
  333. // this is the received data
  334. UDPPacketBuffer buffer = (UDPPacketBuffer)iar.AsyncState;
  335. int startTick = Util.EnvironmentTickCount();
  336. // get the length of data actually read from the socket, store it with the
  337. // buffer
  338. buffer.DataLength = m_udpSocket.EndReceiveFrom(iar, ref buffer.RemoteEndPoint);
  339. // call the abstract method PacketReceived(), passing the buffer that
  340. // has just been filled from the socket read.
  341. PacketReceived(buffer);
  342. // If more than one thread can be calling AsyncEndReceive() at once (e.g. if m_asyncPacketHandler)
  343. // then a particular stat may be inaccurate due to a race condition. We won't worry about this
  344. // since this should be rare and won't cause a runtime problem.
  345. if (m_currentReceiveTimeSamples >= s_receiveTimeSamples)
  346. {
  347. AverageReceiveTicksForLastSamplePeriod
  348. = (float)m_receiveTicksInCurrentSamplePeriod / s_receiveTimeSamples;
  349. m_receiveTicksInCurrentSamplePeriod = 0;
  350. m_currentReceiveTimeSamples = 0;
  351. }
  352. else
  353. {
  354. m_receiveTicksInCurrentSamplePeriod += Util.EnvironmentTickCountSubtract(startTick);
  355. m_currentReceiveTimeSamples++;
  356. }
  357. }
  358. catch (SocketException se)
  359. {
  360. m_log.Error(
  361. string.Format(
  362. "[UDPBASE]: Error processing UDP end receive {0}, socket error code {1}. Exception ",
  363. UdpReceives, se.ErrorCode),
  364. se);
  365. }
  366. catch (ObjectDisposedException e)
  367. {
  368. m_log.Error(
  369. string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
  370. }
  371. catch (Exception e)
  372. {
  373. m_log.Error(
  374. string.Format("[UDPBASE]: Error processing UDP end receive {0}. Exception ", UdpReceives), e);
  375. }
  376. finally
  377. {
  378. // if (UsePools)
  379. // Pool.ReturnObject(buffer);
  380. // Synchronous mode waits until the packet callback completes
  381. // before starting the receive to fetch another packet
  382. if (!m_asyncPacketHandling)
  383. AsyncBeginReceive();
  384. }
  385. }
  386. }
  387. public void AsyncBeginSend(UDPPacketBuffer buf)
  388. {
  389. // if (IsRunningOutbound)
  390. // {
  391. // This is strictly for debugging purposes to simulate dropped
  392. // packets when testing throttles & retransmission code
  393. // if (DropOutgoingPacket())
  394. // return;
  395. try
  396. {
  397. m_udpSocket.BeginSendTo(
  398. buf.Data,
  399. 0,
  400. buf.DataLength,
  401. SocketFlags.None,
  402. buf.RemoteEndPoint,
  403. AsyncEndSend,
  404. buf);
  405. }
  406. catch (SocketException) { }
  407. catch (ObjectDisposedException) { }
  408. // }
  409. }
  410. void AsyncEndSend(IAsyncResult result)
  411. {
  412. try
  413. {
  414. // UDPPacketBuffer buf = (UDPPacketBuffer)result.AsyncState;
  415. m_udpSocket.EndSendTo(result);
  416. UdpSends++;
  417. }
  418. catch (SocketException) { }
  419. catch (ObjectDisposedException) { }
  420. }
  421. }
  422. }