v0.2.2: updated Lidgren, railgun shells can be bought, autorestart server, netstats, tutorial moloch spawning in a wall fix, misc error checks

This commit is contained in:
Regalis
2015-10-18 22:44:30 +03:00
parent aa3882a815
commit 0e5e86e363
85 changed files with 2763 additions and 1866 deletions
+179 -122
View File
@@ -1,8 +1,4 @@
#if !__ANDROID__ && !IOS
#define IS_MAC_AVAILABLE
#endif
using System;
using System;
using System.Net;
using System.Threading;
using System.Diagnostics;
@@ -10,6 +6,10 @@ using System.Security.Cryptography;
using System.Net.Sockets;
using System.Collections.Generic;
#if !__NOIPENDPOINT__
using NetEndPoint = System.Net.IPEndPoint;
#endif
namespace Lidgren.Network
{
public partial class NetPeer
@@ -24,13 +24,15 @@ namespace Lidgren.Network
private object m_initializeLock = new object();
private uint m_frameCounter;
private double m_lastHeartbeat;
private double m_lastSocketBind = float.MinValue;
private NetUPnP m_upnp;
internal bool m_needFlushSendQueue;
internal readonly NetPeerConfiguration m_configuration;
private readonly NetQueue<NetIncomingMessage> m_releasedIncomingMessages;
internal readonly NetQueue<NetTuple<IPEndPoint, NetOutgoingMessage>> m_unsentUnconnectedMessages;
internal readonly NetQueue<NetTuple<NetEndPoint, NetOutgoingMessage>> m_unsentUnconnectedMessages;
internal Dictionary<IPEndPoint, NetConnection> m_handshakes;
internal Dictionary<NetEndPoint, NetConnection> m_handshakes;
internal readonly NetPeerStatistics m_statistics;
internal long m_uniqueIdentifier;
@@ -47,13 +49,15 @@ namespace Lidgren.Network
/// <summary>
/// Call this to register a callback for when a new message arrives
/// </summary>
public void RegisterReceivedCallback(SendOrPostCallback callback)
public void RegisterReceivedCallback(SendOrPostCallback callback, SynchronizationContext syncContext = null)
{
if (SynchronizationContext.Current == null)
if (syncContext == null)
syncContext = SynchronizationContext.Current;
if (syncContext == null)
throw new NetException("Need a SynchronizationContext to register callback on correct thread!");
if (m_receiveCallbacks == null)
m_receiveCallbacks = new List<NetTuple<SynchronizationContext, SendOrPostCallback>>();
m_receiveCallbacks.Add(new NetTuple<SynchronizationContext, SendOrPostCallback>(SynchronizationContext.Current, callback));
m_receiveCallbacks.Add(new NetTuple<SynchronizationContext, SendOrPostCallback>(syncContext, callback));
}
/// <summary>
@@ -63,7 +67,17 @@ namespace Lidgren.Network
{
if (m_receiveCallbacks == null)
return;
m_receiveCallbacks.Remove(new NetTuple<SynchronizationContext, SendOrPostCallback>(SynchronizationContext.Current, callback));
// remove all callbacks regardless of sync context
RestartRemoveCallbacks:
for (int i = 0; i < m_receiveCallbacks.Count; i++)
{
if (m_receiveCallbacks[i].Item2.Equals(callback))
{
m_receiveCallbacks.RemoveAt(i);
goto RestartRemoveCallbacks;
}
}
if (m_receiveCallbacks.Count < 1)
m_receiveCallbacks = null;
}
@@ -86,10 +100,59 @@ namespace Lidgren.Network
if (m_receiveCallbacks != null)
{
foreach (var tuple in m_receiveCallbacks)
tuple.Item1.Post(tuple.Item2, this);
{
try
{
tuple.Item1.Post(tuple.Item2, this);
}
catch (Exception ex)
{
LogWarning("Receive callback exception:" + ex);
}
}
}
}
private void BindSocket(bool reBind)
{
double now = NetTime.Now;
if (now - m_lastSocketBind < 1.0)
{
LogDebug("Suppressed socket rebind; last bound " + (now - m_lastSocketBind) + " seconds ago");
return; // only allow rebind once every second
}
m_lastSocketBind = now;
if (m_socket == null)
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
if (reBind)
m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, (int)1);
m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize;
m_socket.SendBufferSize = m_configuration.SendBufferSize;
m_socket.Blocking = false;
var ep = (EndPoint)new NetEndPoint(m_configuration.LocalAddress, reBind ? m_listenPort : m_configuration.Port);
m_socket.Bind(ep);
try
{
const uint IOC_IN = 0x80000000;
const uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
m_socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
}
catch
{
// ignore; SIO_UDP_CONNRESET not supported on this platform
}
var boundEp = m_socket.LocalEndPoint as NetEndPoint;
LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound);
m_listenPort = boundEp.Port;
}
private void InitializeNetwork()
{
lock (m_initializeLock)
@@ -109,65 +172,21 @@ namespace Lidgren.Network
m_handshakes.Clear();
// bind to socket
IPEndPoint iep = null;
iep = new IPEndPoint(m_configuration.LocalAddress, m_configuration.Port);
EndPoint ep = (EndPoint)iep;
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize;
m_socket.SendBufferSize = m_configuration.SendBufferSize;
m_socket.Blocking = false;
m_socket.Bind(ep);
try
{
const uint IOC_IN = 0x80000000;
const uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
m_socket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
}
catch
{
// ignore; SIO_UDP_CONNRESET not supported on this platform
}
IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint;
LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound);
m_listenPort = boundEp.Port;
BindSocket(false);
m_receiveBuffer = new byte[m_configuration.ReceiveBufferSize];
m_sendBuffer = new byte[m_configuration.SendBufferSize];
m_readHelperMessage = new NetIncomingMessage(NetIncomingMessageType.Error);
m_readHelperMessage.m_data = m_receiveBuffer;
byte[] macBytes = new byte[8];
NetRandom.Instance.NextBytes(macBytes);
byte[] macBytes = NetUtility.GetMacAddressBytes();
#if IS_MAC_AVAILABLE
try
{
System.Net.NetworkInformation.PhysicalAddress pa = NetUtility.GetMacAddress();
if (pa != null)
{
macBytes = pa.GetAddressBytes();
LogVerbose("Mac address is " + NetUtility.ToHexString(macBytes));
}
else
{
LogWarning("Failed to get Mac address");
}
}
catch (NotSupportedException)
{
// not supported; lets just keep the random bytes set above
}
#endif
var boundEp = m_socket.LocalEndPoint as NetEndPoint;
byte[] epBytes = BitConverter.GetBytes(boundEp.GetHashCode());
byte[] combined = new byte[epBytes.Length + macBytes.Length];
Array.Copy(epBytes, 0, combined, 0, epBytes.Length);
Array.Copy(macBytes, 0, combined, epBytes.Length, macBytes.Length);
m_uniqueIdentifier = BitConverter.ToInt64(SHA1.Create().ComputeHash(combined), 0);
m_uniqueIdentifier = BitConverter.ToInt64(NetUtility.ComputeSHAHash(combined), 0);
m_status = NetPeerStatus.Running;
}
@@ -213,26 +232,26 @@ namespace Lidgren.Network
foreach (var conn in m_connections)
if (conn != null)
list.Add(conn);
lock (m_handshakes)
{
foreach (var hs in m_handshakes.Values)
if (hs != null)
list.Add(hs);
// shut down connections
foreach (NetConnection conn in list)
conn.Shutdown(m_shutdownReason);
}
}
lock (m_handshakes)
{
foreach (var hs in m_handshakes.Values)
if (hs != null && list.Contains(hs) == false)
list.Add(hs);
}
// shut down connections
foreach (NetConnection conn in list)
conn.Shutdown(m_shutdownReason);
FlushDelayedPackets();
// one final heartbeat, will send stuff and do disconnect
Heartbeat();
Thread.Sleep(10);
NetUtility.Sleep(10);
lock (m_initializeLock)
{
try
@@ -243,14 +262,19 @@ namespace Lidgren.Network
{
m_socket.Shutdown(SocketShutdown.Receive);
}
catch { }
m_socket.Close(2); // 2 seconds timeout
}
if (m_messageReceivedEvent != null)
{
m_messageReceivedEvent.Set();
m_messageReceivedEvent.Close();
m_messageReceivedEvent = null;
catch(Exception ex)
{
LogDebug("Socket.Shutdown exception: " + ex.ToString());
}
try
{
m_socket.Close(2); // 2 seconds timeout
}
catch (Exception ex)
{
LogDebug("Socket.Close exception: " + ex.ToString());
}
}
}
finally
@@ -258,8 +282,13 @@ namespace Lidgren.Network
m_socket = null;
m_status = NetPeerStatus.NotRunning;
LogDebug("Shutdown complete");
// wake up any threads waiting for server shutdown
if (m_messageReceivedEvent != null)
m_messageReceivedEvent.Set();
}
m_lastSocketBind = float.MinValue;
m_receiveBuffer = null;
m_sendBuffer = null;
m_unsentUnconnectedMessages.Clear();
@@ -275,10 +304,8 @@ namespace Lidgren.Network
{
VerifyNetworkThread();
double dnow = NetTime.Now;
float now = (float)dnow;
double delta = dnow - m_lastHeartbeat;
double now = NetTime.Now;
double delta = now - m_lastHeartbeat;
int maxCHBpS = 1250 - m_connections.Count;
if (maxCHBpS < 250)
@@ -286,7 +313,7 @@ namespace Lidgren.Network
if (delta > (1.0 / (double)maxCHBpS) || delta < 0.0) // max connection heartbeats/second max
{
m_frameCounter++;
m_lastHeartbeat = dnow;
m_lastHeartbeat = now;
// do handshake heartbeats
if ((m_frameCounter % 3) == 0)
@@ -320,44 +347,51 @@ namespace Lidgren.Network
#endif
// update m_executeFlushSendQueue
if (m_configuration.m_autoFlushSendQueue)
if (m_configuration.m_autoFlushSendQueue && m_needFlushSendQueue == true)
{
m_executeFlushSendQueue = true;
m_needFlushSendQueue = false; // a race condition to this variable will simply result in a single superfluous call to FlushSendQueue()
}
// do connection heartbeats
lock (m_connections)
{
foreach (NetConnection conn in m_connections)
for (int i = m_connections.Count - 1; i >= 0; i--)
{
var conn = m_connections[i];
conn.Heartbeat(now, m_frameCounter);
if (conn.m_status == NetConnectionStatus.Disconnected)
{
//
// remove connection
//
m_connections.Remove(conn);
m_connections.RemoveAt(i);
m_connectionLookup.Remove(conn.RemoteEndPoint);
break; // can't continue iteration here
}
}
}
m_executeFlushSendQueue = false;
// send unsent unconnected messages
NetTuple<IPEndPoint, NetOutgoingMessage> unsent;
NetTuple<NetEndPoint, NetOutgoingMessage> unsent;
while (m_unsentUnconnectedMessages.TryDequeue(out unsent))
{
NetOutgoingMessage om = unsent.Item2;
bool connReset;
int len = om.Encode(m_sendBuffer, 0, 0);
SendPacket(len, unsent.Item1, 1, out connReset);
Interlocked.Decrement(ref om.m_recyclingCount);
if (om.m_recyclingCount <= 0)
Recycle(om);
bool connReset;
SendPacket(len, unsent.Item1, 1, out connReset);
}
}
if (m_upnp != null)
m_upnp.CheckForDiscoveryTimeout();
//
// read from socket
//
@@ -371,8 +405,7 @@ namespace Lidgren.Network
// return;
// update now
dnow = NetTime.Now;
now = (float)dnow;
now = NetTime.Now;
do
{
@@ -383,17 +416,24 @@ namespace Lidgren.Network
}
catch (SocketException sx)
{
if (sx.SocketErrorCode == SocketError.ConnectionReset)
switch (sx.SocketErrorCode)
{
// connection reset by peer, aka connection forcibly closed aka "ICMP port unreachable"
// we should shut down the connection; but m_senderRemote seemingly cannot be trusted, so which connection should we shut down?!
// So, what to do?
LogWarning("ConnectionReset");
return;
}
case SocketError.ConnectionReset:
// connection reset by peer, aka connection forcibly closed aka "ICMP port unreachable"
// we should shut down the connection; but m_senderRemote seemingly cannot be trusted, so which connection should we shut down?!
// So, what to do?
LogWarning("ConnectionReset");
return;
LogWarning(sx.ToString());
return;
case SocketError.NotConnected:
// socket is unbound; try to rebind it (happens on mobile when process goes to sleep)
BindSocket(true);
return;
default:
LogWarning("Socket exception: " + sx.ToString());
return;
}
}
if (bytesReceived < NetConstants.HeaderByteSize)
@@ -401,23 +441,29 @@ namespace Lidgren.Network
//LogVerbose("Received " + bytesReceived + " bytes");
IPEndPoint ipsender = (IPEndPoint)m_senderRemote;
var ipsender = (NetEndPoint)m_senderRemote;
if (m_upnp != null && now < m_upnp.m_discoveryResponseDeadline)
if (m_upnp != null && now < m_upnp.m_discoveryResponseDeadline && bytesReceived > 32)
{
// is this an UPnP response?
try
string resp = System.Text.Encoding.UTF8.GetString(m_receiveBuffer, 0, bytesReceived);
if (resp.Contains("upnp:rootdevice") || resp.Contains("UPnP/1.0"))
{
string resp = System.Text.Encoding.ASCII.GetString(m_receiveBuffer, 0, bytesReceived);
if (resp.Contains("upnp:rootdevice") || resp.Contains("UPnP/1.0"))
try
{
resp = resp.Substring(resp.ToLower().IndexOf("location:") + 9);
resp = resp.Substring(0, resp.IndexOf("\r")).Trim();
m_upnp.ExtractServiceUrl(resp);
return;
}
catch (Exception ex)
{
LogDebug("Failed to parse UPnP response: " + ex.ToString());
// don't try to parse this packet further
return;
}
}
catch { }
}
NetConnection sender = null;
@@ -427,6 +473,7 @@ namespace Lidgren.Network
// parse packet into messages
//
int numMessages = 0;
int numFragments = 0;
int ptr = 0;
while ((bytesReceived - ptr) >= NetConstants.HeaderByteSize)
{
@@ -446,6 +493,9 @@ namespace Lidgren.Network
bool isFragment = ((low & 1) == 1);
ushort sequenceNumber = (ushort)((low >> 1) | (((int)high) << 7));
if (isFragment)
numFragments++;
ushort payloadBitLength = (ushort)(m_receiveBuffer[ptr++] | (m_receiveBuffer[ptr++] << 8));
int payloadByteLength = NetUtility.BytesToHoldBits(payloadBitLength);
@@ -455,16 +505,20 @@ namespace Lidgren.Network
return;
}
if (tp >= NetMessageType.Unused1 && tp <= NetMessageType.Unused29)
{
ThrowOrLog("Unexpected NetMessageType: " + tp);
return;
}
try
{
NetException.Assert(tp < NetMessageType.Unused1 || tp > NetMessageType.Unused29);
if (tp >= NetMessageType.LibraryError)
{
if (sender != null)
sender.ReceivedLibraryMessage(tp, ptr, payloadByteLength);
else
ReceivedUnconnectedLibraryMessage(dnow, ipsender, tp, ptr, payloadByteLength);
ReceivedUnconnectedLibraryMessage(now, ipsender, tp, ptr, payloadByteLength);
}
else
{
@@ -473,12 +527,13 @@ namespace Lidgren.Network
NetIncomingMessage msg = CreateIncomingMessage(NetIncomingMessageType.Data, payloadByteLength);
msg.m_isFragment = isFragment;
msg.m_receiveTime = dnow;
msg.m_receiveTime = now;
msg.m_sequenceNumber = sequenceNumber;
msg.m_receivedMessageType = tp;
msg.m_senderConnection = sender;
msg.m_senderEndPoint = ipsender;
msg.m_bitLength = payloadBitLength;
Buffer.BlockCopy(m_receiveBuffer, ptr, msg.m_data, 0, payloadByteLength);
if (sender != null)
{
@@ -510,9 +565,9 @@ namespace Lidgren.Network
ptr += payloadByteLength;
}
m_statistics.PacketReceived(bytesReceived, numMessages);
m_statistics.PacketReceived(bytesReceived, numMessages, numFragments);
if (sender != null)
sender.m_statistics.PacketReceived(bytesReceived, numMessages);
sender.m_statistics.PacketReceived(bytesReceived, numMessages, numFragments);
} while (m_socket.Available > 0);
}
@@ -525,7 +580,7 @@ namespace Lidgren.Network
m_executeFlushSendQueue = true;
}
internal void HandleIncomingDiscoveryRequest(double now, IPEndPoint senderEndPoint, int ptr, int payloadByteLength)
internal void HandleIncomingDiscoveryRequest(double now, NetEndPoint senderEndPoint, int ptr, int payloadByteLength)
{
if (m_configuration.IsMessageTypeEnabled(NetIncomingMessageType.DiscoveryRequest))
{
@@ -539,7 +594,7 @@ namespace Lidgren.Network
}
}
internal void HandleIncomingDiscoveryResponse(double now, IPEndPoint senderEndPoint, int ptr, int payloadByteLength)
internal void HandleIncomingDiscoveryResponse(double now, NetEndPoint senderEndPoint, int ptr, int payloadByteLength)
{
if (m_configuration.IsMessageTypeEnabled(NetIncomingMessageType.DiscoveryResponse))
{
@@ -553,7 +608,7 @@ namespace Lidgren.Network
}
}
private void ReceivedUnconnectedLibraryMessage(double now, IPEndPoint senderEndPoint, NetMessageType tp, int ptr, int payloadByteLength)
private void ReceivedUnconnectedLibraryMessage(double now, NetEndPoint senderEndPoint, NetMessageType tp, int ptr, int payloadByteLength)
{
NetConnection shake;
if (m_handshakes.TryGetValue(senderEndPoint, out shake))
@@ -574,10 +629,12 @@ namespace Lidgren.Network
HandleIncomingDiscoveryResponse(now, senderEndPoint, ptr, payloadByteLength);
return;
case NetMessageType.NatIntroduction:
HandleNatIntroduction(ptr);
if (m_configuration.IsMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess))
HandleNatIntroduction(ptr);
return;
case NetMessageType.NatPunchMessage:
HandleNatPunch(ptr, senderEndPoint);
if (m_configuration.IsMessageTypeEnabled(NetIncomingMessageType.NatIntroductionSuccess))
HandleNatPunch(ptr, senderEndPoint);
return;
case NetMessageType.ConnectResponse:
@@ -688,4 +745,4 @@ namespace Lidgren.Network
return m_readHelperMessage;
}
}
}
}