1
0
mirror of https://github.com/lidgren/lidgren-network-gen3.git synced 2026-05-06 02:11:06 +09:00

Missing project added; various code cleanups

This commit is contained in:
lidgren
2010-05-14 17:12:26 +00:00
parent bf208b507a
commit 9577d4b4a6
31 changed files with 381 additions and 139 deletions

View File

@@ -3,7 +3,7 @@
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{FA245447-5F23-4AA1-BD5F-8D2DDF33CFBD}</ProjectGuid>
<OutputType>Library</OutputType>
@@ -33,17 +33,6 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="NetBigInteger.cs" />

View File

@@ -39,7 +39,7 @@ using System.Security.Cryptography;
namespace Lidgren.Network
{
public class BigInteger
public sealed class BigInteger
{
/// <summary>
/// The Length of this BigInteger
@@ -1271,7 +1271,7 @@ namespace Lidgren.Network
/// <summary>
/// Low level functions for the BigInteger
/// </summary>
private sealed class Kernel
private static class Kernel
{
/// <summary>
/// Adds two numbers with the same sign.

View File

@@ -1,11 +1,30 @@
using System;
/* Copyright (c) 2010 Michael Lidgren
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace Lidgren.Network
{
public sealed class NetBitVector
{
private int m_capacity;
private uint[] m_data;
private readonly int m_capacity;
private readonly uint[] m_data;
public int Capacity { get { return m_capacity; } }

View File

@@ -234,23 +234,8 @@ namespace Lidgren.Network
return returnValue;
}
[CLSCompliant(false)]
public static ulong ReadUInt64(byte[] fromBuffer, int numberOfBits, int readBitOffset)
{
throw new NotImplementedException("ReadUInt64 not implemented yet");
#if BIGENDIAN
// reorder bytes
return ((a & 0xff00000000000000L) >> 56) |
((a & 0x00ff000000000000L) >> 40) |
((a & 0x0000ff0000000000L) >> 24) |
((a & 0x000000ff00000000L) >> 8) |
((a & 0x00000000ff000000L) << 8) |
((a & 0x0000000000ff0000L) << 24) |
((a & 0x000000000000ff00L) << 40) |
((a & 0x00000000000000ffL) << 56);
#endif
}
//[CLSCompliant(false)]
//public static ulong ReadUInt64(byte[] fromBuffer, int numberOfBits, int readBitOffset)
[CLSCompliant(false)]
public static int WriteUInt32(uint source, int numberOfBits, byte[] destination, int destinationBitOffset)

View File

@@ -171,11 +171,11 @@ namespace Lidgren.Network
m_connectionInitiator = false;
}
private void HandleIncomingHandshake(NetMessageLibraryType ltp, int ptr, int payloadBitsLength)
private void HandleIncomingHandshake(NetMessageLibraryType libType, int ptr, int payloadBitsLength)
{
m_owner.VerifyNetworkThread();
switch (ltp)
switch (libType)
{
case NetMessageLibraryType.Connect:
if (m_status == NetConnectionStatus.Connecting)
@@ -219,7 +219,7 @@ namespace Lidgren.Network
return;
}
m_owner.LogWarning("NetConnection.HandleIncomingHandshake() passed " + ltp + ", but status is " + m_status);
m_owner.LogWarning("NetConnection.HandleIncomingHandshake() passed " + libType + ", but status is " + m_status);
break;
case NetMessageLibraryType.ConnectionEstablished:
if (!m_connectionInitiator && m_status == NetConnectionStatus.Connecting)
@@ -233,7 +233,7 @@ namespace Lidgren.Network
return;
}
m_owner.LogWarning("NetConnection.HandleIncomingHandshake() passed " + ltp + ", but initiator is " + m_connectionInitiator + " and status is " + m_status);
m_owner.LogWarning("NetConnection.HandleIncomingHandshake() passed " + libType + ", but initiator is " + m_connectionInitiator + " and status is " + m_status);
break;
case NetMessageLibraryType.Disconnect:
// extract bye message
@@ -244,7 +244,8 @@ namespace Lidgren.Network
break;
default:
// huh?
throw new NotImplementedException("Unhandled library type: " + ltp);
m_owner.LogWarning("Unhandled library type in " + this + ": " + libType);
break;
}
}
}

View File

@@ -28,15 +28,16 @@ namespace Lidgren.Network
private ushort[] m_nextSendSequenceNumber;
private ushort[] m_lastReceivedSequenced;
internal List<NetOutgoingMessage>[] m_storedMessages; // naïve! replace by something better?
internal NetBitVector m_storedMessagesNotEmpty;
// TODO: naïve! replace by something better?
internal readonly List<NetOutgoingMessage>[] m_storedMessages = new List<NetOutgoingMessage>[NetConstants.NumReliableChannels];
internal readonly NetBitVector m_storedMessagesNotEmpty = new NetBitVector(NetConstants.NumReliableChannels);
private ushort[] m_nextExpectedReliableSequence;
private List<NetIncomingMessage>[] m_withheldMessages;
internal Queue<int> m_acknowledgesToSend;
private readonly ushort[] m_nextExpectedReliableSequence = new ushort[NetConstants.NumReliableChannels];
private readonly List<NetIncomingMessage>[] m_withheldMessages = new List<NetIncomingMessage>[NetConstants.NetChannelsPerDeliveryMethod]; // only for ReliableOrdered
internal readonly Queue<int> m_acknowledgesToSend = new Queue<int>();
internal double m_nextForceAckTime;
private NetBitVector[] m_reliableReceived;
private readonly NetBitVector[] m_reliableReceived = new NetBitVector[NetConstants.NumSequenceNumbers];
public int GetStoredMessagesCount()
{
@@ -56,14 +57,6 @@ namespace Lidgren.Network
m_nextSendSequenceNumber = new ushort[num];
m_lastReceivedSequenced = new ushort[num];
m_nextForceAckTime = double.MaxValue;
m_storedMessages = new List<NetOutgoingMessage>[NetConstants.NumReliableChannels];
m_storedMessagesNotEmpty = new NetBitVector(NetConstants.NumReliableChannels);
m_reliableReceived = new NetBitVector[NetConstants.NumSequenceNumbers];
m_nextExpectedReliableSequence = new ushort[NetConstants.NumReliableChannels];
m_withheldMessages = new List<NetIncomingMessage>[NetConstants.NetChannelsPerDeliveryMethod]; // only for ReliableOrdered
m_acknowledgesToSend = new Queue<int>();
}
internal ushort GetSendSequenceNumber(NetMessageType mtp)

View File

@@ -28,8 +28,8 @@ namespace Lidgren.Network
[DebuggerDisplay("RemoteEndpoint={m_remoteEndpoint} Status={m_status}")]
public partial class NetConnection
{
private NetPeer m_owner;
internal IPEndPoint m_remoteEndpoint;
private readonly NetPeer m_owner;
internal readonly IPEndPoint m_remoteEndpoint;
internal double m_lastHeardFrom;
internal NetQueue<NetOutgoingMessage> m_unsentMessages;
internal NetConnectionStatus m_status;
@@ -523,7 +523,8 @@ namespace Lidgren.Network
HandleIncomingAcks(ptr, NetUtility.BytesToHoldBits(payloadLengthBits));
break;
default:
throw new NotImplementedException("Unhandled library type: " + libType);
m_owner.LogWarning("Unhandled library type in " + this + ": " + libType);
break;
}
return;
@@ -652,12 +653,6 @@ namespace Lidgren.Network
m_pendingDenialReason = reason;
}
internal void Dispose()
{
m_owner = null;
m_unsentMessages = null;
}
public override string ToString()
{
return "[NetConnection to " + m_remoteEndpoint + " Status: " + m_visibleStatus + "]";

View File

@@ -25,7 +25,7 @@ namespace Lidgren.Network
{
public sealed class NetConnectionStatistics
{
private NetConnection m_connection;
private readonly NetConnection m_connection;
internal int m_sentPackets;
internal int m_receivedPackets;

View File

@@ -1,28 +1,47 @@
using System;
using System.Collections.Generic;
/* Copyright (c) 2010 Michael Lidgren
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Security.Cryptography;
using System.Text;
namespace Lidgren.Network
{
public sealed class NetXTEA
public sealed class NetXtea
{
private const int m_blockSize = 8;
private const int m_keySize = 16;
private const int m_delta = unchecked((int)0x9E3779B9);
private const int m_dSum = unchecked((int)0xC6EF3720); // sum on decrypt
private byte[] m_keyBytes;
private int[] m_key;
private int m_rounds;
private readonly byte[] m_keyBytes;
private readonly int[] m_key;
private readonly int m_rounds;
public byte[] Key { get { return m_keyBytes; } }
/// <summary>
/// 16 byte key
/// </summary>
public NetXTEA(byte[] key, int rounds)
public NetXtea(byte[] key, int rounds)
{
if (key.Length < 16)
throw new NetException("Key too short!");
m_keyBytes = key;
m_key = new int[4];
m_key[0] = BitConverter.ToInt32(key, 0);
@@ -32,6 +51,14 @@ namespace Lidgren.Network
m_rounds = rounds;
}
/// <summary>
/// 16 byte key
/// </summary>
public NetXtea(byte[] key)
: this(key, 64)
{
}
public void EncryptBlock(
byte[] inBytes,
int inOff,
@@ -56,7 +83,7 @@ namespace Lidgren.Network
return;
}
public void DecryptBlock(
byte[] inBytes,
int inOff,
@@ -104,7 +131,7 @@ namespace Lidgren.Network
}
}
public static class NetSHA
public static class NetSha
{
// TODO: switch to SHA256
private static SHA1 m_sha;
@@ -131,7 +158,7 @@ namespace Lidgren.Network
string one = NetUtility.ToHexString(N.GetBytes());
string two = NetUtility.ToHexString(g.GetBytes());
byte[] cc = NetUtility.ToByteArray(one + two.PadLeft(one.Length, '0'));
return BigInteger.Modulus(new BigInteger(NetSHA.Hash(cc)), N);
return BigInteger.Modulus(new BigInteger(NetSha.Hash(cc)), N);
}
/// <summary>
@@ -140,13 +167,13 @@ namespace Lidgren.Network
public static byte[] ComputePasswordVerifier(string username, string password, byte[] salt)
{
byte[] tmp = Encoding.ASCII.GetBytes(username + ":" + password);
byte[] innerHash = NetSHA.Hash(tmp);
byte[] innerHash = NetSha.Hash(tmp);
byte[] total = new byte[innerHash.Length + salt.Length];
Buffer.BlockCopy(salt, 0, total, 0, salt.Length);
Buffer.BlockCopy(innerHash, 0, total, salt.Length, innerHash.Length);
byte[] x = NetSHA.Hash(total);
byte[] x = NetSha.Hash(total);
// Verifier (v) = g^x (mod N)
BigInteger xx = new BigInteger(x);
@@ -194,7 +221,7 @@ namespace Lidgren.Network
string two = NetUtility.ToHexString(B);
string compound = one + two.PadLeft(one.Length, '0');
byte[] cc = NetUtility.ToByteArray(compound);
return NetSHA.Hash(cc);
return NetSha.Hash(cc);
}
/*

View File

@@ -18,8 +18,8 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Runtime.Serialization;
using System.Diagnostics;
using System.Runtime.Serialization;
namespace Lidgren.Network
{

View File

@@ -2,7 +2,7 @@
namespace Lidgren.Network
{
public class NetFragmentationInfo
public sealed class NetFragmentationInfo
{
public int TotalFragmentCount;
public bool[] Received;

View File

@@ -568,7 +568,7 @@ namespace Lidgren.Network
{
if (j >= h)
{
if (list[j - h].Name.CompareTo(tmp.Name) > 0)
if (string.Compare(list[j - h].Name, tmp.Name, StringComparison.InvariantCulture) > 0)
{
list[j] = list[j - h];
j -= h;

View File

@@ -15,12 +15,10 @@ PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Diagnostics;
using System.Net;
namespace Lidgren.Network
{
@@ -62,6 +60,14 @@ namespace Lidgren.Network
get { return m_bitLength; }
}
/// <summary>
/// Returns the internal data buffer, don't modify
/// </summary>
public byte[] PeekDataBuffer()
{
return m_data;
}
/// <summary>
/// Gets the NetDeliveryMethod used by this message
/// </summary>
@@ -110,6 +116,20 @@ namespace Lidgren.Network
m_fragmentationInfo = null;
}
public void Decrypt(NetXtea tea)
{
// need blocks of 8 bytes
int blocks = m_bitLength / 64;
if (blocks * 64 != m_bitLength)
throw new NetException("Wrong message length for XTEA decrypt! Length is " + m_bitLength + " bits");
Console.WriteLine("DECRYPTING " + NetUtility.ToHexString(m_data));
byte[] result = new byte[m_data.Length];
tea.DecryptBlock(m_data, 0, result, 0);
m_data = result;
}
public override string ToString()
{
return String.Format("[NetIncomingMessage {0}, {1}|{2}, {3} bits]",

View File

@@ -161,6 +161,22 @@ namespace Lidgren.Network
return ptr;
}
public void Encrypt(NetXtea tea)
{
// need blocks of 8 bytes
WritePadBits();
int blocksNeeded = (m_bitLength + 63) / 64;
int missingBits = (blocksNeeded * 64) - m_bitLength;
int missingBytes = missingBits / 8;
for (int i = 0; i < missingBytes; i++)
Write((byte)0);
Console.WriteLine("ENCRYPTING " + NetUtility.ToHexString(m_data));
byte[] result = new byte[m_data.Length];
tea.EncryptBlock(m_data, 0, result, 0);
m_data = result;
}
public override string ToString()
{
StringBuilder bdr = new StringBuilder();

View File

@@ -10,7 +10,7 @@ namespace Lidgren.Network
/// </summary>
public void DiscoverLocalPeers(int serverPort)
{
NetOutgoingMessage om = CreateMessage();
NetOutgoingMessage om = CreateMessage(0);
SendUnconnectedLibraryMessage(om, NetMessageLibraryType.Discovery, new IPEndPoint(IPAddress.Broadcast, serverPort));
}
@@ -30,7 +30,7 @@ namespace Lidgren.Network
/// </summary>
public bool DiscoverKnownPeer(IPEndPoint endpoint)
{
NetOutgoingMessage om = CreateMessage();
NetOutgoingMessage om = CreateMessage(0);
SendUnconnectedLibraryMessage(om, NetMessageLibraryType.Discovery, endpoint);
return true;
}

View File

@@ -18,11 +18,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Net.NetworkInformation;
namespace Lidgren.Network
{
@@ -34,10 +32,10 @@ namespace Lidgren.Network
internal Socket m_socket;
internal byte[] m_macAddressBytes;
private int m_listenPort;
private AutoResetEvent m_messageReceivedEvent;
private readonly AutoResetEvent m_messageReceivedEvent = new AutoResetEvent(false);
private NetQueue<NetIncomingMessage> m_releasedIncomingMessages;
private NetQueue<NetOutgoingMessage> m_unsentUnconnectedMessage;
private readonly NetQueue<NetIncomingMessage> m_releasedIncomingMessages = new NetQueue<NetIncomingMessage>(16);
private readonly NetQueue<NetOutgoingMessage> m_unsentUnconnectedMessage = new NetQueue<NetOutgoingMessage>(4);
/// <summary>
/// Signalling event which can be waited on to determine when a message is queued for reading.
@@ -47,13 +45,6 @@ namespace Lidgren.Network
/// </summary>
public AutoResetEvent MessageReceivedEvent { get { return m_messageReceivedEvent; } }
private void InternalInitialize()
{
m_releasedIncomingMessages = new NetQueue<NetIncomingMessage>(16);
m_unsentUnconnectedMessage = new NetQueue<NetOutgoingMessage>(4);
m_messageReceivedEvent = new AutoResetEvent(false);
}
internal void ReleaseMessage(NetIncomingMessage msg)
{
NetException.Assert(msg.m_status != NetIncomingMessageReleaseStatus.ReleasedToApplication, "Message released to application twice!");
@@ -192,7 +183,6 @@ namespace Lidgren.Network
finally
{
m_socket = null;
m_messageReceivedEvent = null;
m_status = NetPeerStatus.NotRunning;
LogDebug("Shutdown complete");
}
@@ -562,7 +552,6 @@ namespace Lidgren.Network
m_connections.Remove(conn);
m_connectionLookup.Remove(conn.m_remoteEndpoint);
}
conn.Dispose();
}
private void HandleServerFull(IPEndPoint connecter)

View File

@@ -28,7 +28,7 @@ namespace Lidgren.Network
{
#if DEBUG
private List<DelayedPacket> m_delayedPackets = new List<DelayedPacket>();
private readonly List<DelayedPacket> m_delayedPackets = new List<DelayedPacket>();
private class DelayedPacket
{
@@ -117,6 +117,7 @@ namespace Lidgren.Network
LogError("Failed to send packet: " + ex);
}
}
#else
//
// Release - just send the packet straight away

View File

@@ -35,16 +35,16 @@ namespace Lidgren.Network
internal const int kMaxPacketHeaderSize = 5;
private NetPeerStatus m_status;
private object m_initializeLock = new object();
private readonly object m_initializeLock = new object();
internal long m_uniqueIdentifier;
internal NetPeerConfiguration m_configuration;
internal NetPeerStatistics m_statistics;
internal readonly NetPeerStatistics m_statistics;
private Thread m_networkThread;
private string m_shutdownReason;
internal List<NetConnection> m_connections;
private Dictionary<IPEndPoint, NetConnection> m_connectionLookup;
internal readonly List<NetConnection> m_connections;
private readonly Dictionary<IPEndPoint, NetConnection> m_connectionLookup;
/// <summary>
/// Gets the status of the NetPeer
@@ -98,12 +98,10 @@ namespace Lidgren.Network
{
m_status = NetPeerStatus.NotRunning;
m_configuration = configuration;
m_connections = new List<NetConnection>();
m_connectionLookup = new Dictionary<IPEndPoint, NetConnection>();
m_connections = new List<NetConnection>(m_configuration.MaximumConnections);
m_connectionLookup = new Dictionary<IPEndPoint, NetConnection>(m_configuration.MaximumConnections);
m_senderRemote = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
m_statistics = new NetPeerStatistics(this);
InternalInitialize();
}
/// <summary>

View File

@@ -208,36 +208,36 @@ namespace Lidgren.Network
/// <summary>
/// Enables receiving of the specified type of message
/// </summary>
public void EnableMessageType(NetIncomingMessageType tp)
public void EnableMessageType(NetIncomingMessageType type)
{
m_disabledTypes &= (~tp);
m_disabledTypes &= (~type);
}
/// <summary>
/// Disables receiving of the specified type of message
/// </summary>
public void DisableMessageType(NetIncomingMessageType tp)
public void DisableMessageType(NetIncomingMessageType type)
{
m_disabledTypes |= tp;
m_disabledTypes |= type;
}
/// <summary>
/// Enables or disables receiving of the specified type of message
/// </summary>
public void SetMessageTypeEnabled(NetIncomingMessageType tp, bool enabled)
public void SetMessageTypeEnabled(NetIncomingMessageType type, bool enabled)
{
if (enabled)
m_disabledTypes &= (~tp);
m_disabledTypes &= (~type);
else
m_disabledTypes |= tp;
m_disabledTypes |= type;
}
/// <summary>
/// Gets if receiving of the specified type of message is enabled
/// </summary>
public bool IsMessageTypeEnabled(NetIncomingMessageType tp)
public bool IsMessageTypeEnabled(NetIncomingMessageType type)
{
return !((m_disabledTypes & tp) == tp);
return !((m_disabledTypes & type) == type);
}
/// <summary>

View File

@@ -25,7 +25,7 @@ namespace Lidgren.Network
{
public sealed class NetPeerStatistics
{
private NetPeer m_peer;
private readonly NetPeer m_peer;
internal int m_sentPackets;
internal int m_receivedPackets;

View File

@@ -15,6 +15,7 @@ PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;

View File

@@ -1,4 +1,23 @@
using System;
/* Copyright (c) 2010 Michael Lidgren
Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Diagnostics;
namespace Lidgren.Network
@@ -24,7 +43,7 @@ namespace Lidgren.Network
// [7] item
//
private T[] m_items;
private object m_lock;
private readonly object m_lock;
private int m_size;
private int m_head;

View File

@@ -32,8 +32,8 @@ namespace Lidgren.Network
public static class NetTime
{
#if IS_STOPWATCH_AVAILABLE
private static long s_timeInitialized = Stopwatch.GetTimestamp();
private static double s_dInvFreq = 1.0 / (double)Stopwatch.Frequency;
private static readonly long s_timeInitialized = Stopwatch.GetTimestamp();
private static readonly double s_dInvFreq = 1.0 / (double)Stopwatch.Frequency;
/// <summary>
/// Get number of seconds since the application started

View File

@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.21022</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{BBE12F3E-098F-4C13-842F-A52B86E2611A}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MSServer</RootNamespace>
<AssemblyName>MSServer</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Xml.Linq">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data.DataSetExtensions">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\Lidgren.Network\Lidgren.Network.csproj">
<Project>{FA245447-5F23-4AA1-BD5F-8D2DDF33CFBD}</Project>
<Name>Lidgren.Network</Name>
</ProjectReference>
<ProjectReference Include="..\MSCommon\MSCommon.csproj">
<Project>{DCD2BE10-1B14-4C80-8BD6-77A8B1F43346}</Project>
<Name>MSCommon</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using Lidgren.Network;
using MSCommon;
using System.Net;
namespace MSServer
{
class Program
{
static void Main(string[] args)
{
IPEndPoint masterServerEndpoint = NetUtility.Resolve("localhost", CommonConstants.MasterServerPort);
NetPeerConfiguration config = new NetPeerConfiguration("game");
config.Port = 14242;
NetServer server = new NetServer(config);
server.Start();
Console.WriteLine("Server started; waiting 5 seconds...");
System.Threading.Thread.Sleep(5000);
// register with master server
NetOutgoingMessage regMsg = server.CreateMessage();
regMsg.Write((byte)MasterServerMessageType.RegisterHost);
IPAddress mask;
IPAddress adr = NetUtility.GetMyAddress(out mask);
regMsg.Write(new IPEndPoint(adr, 14242));
Console.WriteLine("Sending registration to master server");
server.SendUnconnectedMessage(regMsg, masterServerEndpoint);
Console.ReadKey();
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MSServer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("MSServer")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c265af7f-3dad-4edf-8ff7-44f03eb2c8e4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -1,15 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lidgren.Network;
namespace UnitTests
{
public static class EncryptionTests
{
public static void Run()
public static void Run(NetPeer peer)
{
//
// Test XTEA
//
NetXtea xtea = new NetXtea(NetSha.Hash(Encoding.ASCII.GetBytes("TopSecret")));
byte[] test = new byte[16];
NetRandom.Instance.NextBytes(test);
byte[] encrypted = new byte[test.Length];
xtea.EncryptBlock(test, 0, encrypted, 0);
byte[] decrypted = new byte[test.Length];
xtea.DecryptBlock(encrypted, 0, decrypted, 0);
// compare!
for (int i = 0; i < test.Length; i++)
if (test[i] != decrypted[i])
throw new NetException("XTEA fail!");
NetOutgoingMessage om = peer.CreateMessage();
om.Write("Hallon");
om.Write(42);
om.Write(5, 5);
om.Write(true);
om.Write("kokos");
Console.WriteLine("Pre encryption: " + NetUtility.ToHexString(om.PeekDataBuffer()));
om.Encrypt(xtea);
Console.WriteLine("Post encryption: " + NetUtility.ToHexString(om.PeekDataBuffer()));
// convert to incoming message
NetIncomingMessage im = Program.CreateIncomingMessage(om.PeekDataBuffer(), om.LengthBits);
Console.WriteLine("Pre decryption: " + NetUtility.ToHexString(im.PeekDataBuffer()));
im.Decrypt(xtea);
Console.WriteLine("Post decryption: " + NetUtility.ToHexString(im.PeekDataBuffer()));
if (im.ReadString() != "Hallon")
throw new NetException("fail");
if (im.ReadInt32() != 42)
throw new NetException("fail");
if (im.ReadInt32(5) != 5)
throw new NetException("fail");
if (im.ReadBoolean() != true)
throw new NetException("fail");
if (im.ReadString() != "kokos")
throw new NetException("fail");
byte[] salt = NetUtility.ToByteArray("e6fb7e23f001f3e6c081"); // s
byte[] verifier = NetSRP.ComputePasswordVerifier("user", "password", salt);

View File

@@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Lidgren.Network;
namespace UnitTests
@@ -26,11 +24,19 @@ namespace UnitTests
BitVectorTests.Run();
EncryptionTests.Run();
EncryptionTests.Run(peer);
peer.Shutdown("bye");
Console.ReadKey();
}
public static NetIncomingMessage CreateIncomingMessage(byte[] fromData, int bitLength)
{
NetIncomingMessage inc = (NetIncomingMessage)Activator.CreateInstance(typeof(NetIncomingMessage), true);
typeof(NetIncomingMessage).GetField("m_data", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(inc, fromData);
typeof(NetIncomingMessage).GetField("m_bitLength", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(inc, bitLength);
return inc;
}
}
}

View File

@@ -30,9 +30,7 @@ namespace UnitTests
byte[] data = msg.PeekDataBuffer();
NetIncomingMessage inc = (NetIncomingMessage)Activator.CreateInstance(typeof(NetIncomingMessage), true);
typeof(NetIncomingMessage).GetField("m_data", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(inc, data);
typeof(NetIncomingMessage).GetField("m_bitLength", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(inc, msg.LengthBits);
NetIncomingMessage inc = Program.CreateIncomingMessage(data, msg.LengthBits);
StringBuilder bdr = new StringBuilder();
@@ -82,9 +80,7 @@ namespace UnitTests
data = tmp.PeekDataBuffer();
inc = (NetIncomingMessage)Activator.CreateInstance(typeof(NetIncomingMessage), true);
typeof(NetIncomingMessage).GetField("m_data", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(inc, data);
typeof(NetIncomingMessage).GetField("m_bitLength", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(inc, tmp.LengthBits);
inc = Program.CreateIncomingMessage(data, tmp.LengthBits);
Test readTest = new Test();
inc.ReadAllFields(readTest);

View File

@@ -32,11 +32,6 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BitVectorTests.cs" />