From 9577d4b4a618e8989596941bdae59a5a9f6def91 Mon Sep 17 00:00:00 2001 From: lidgren Date: Fri, 14 May 2010 17:12:26 +0000 Subject: [PATCH] Missing project added; various code cleanups --- Lidgren.Network/Lidgren.Network.csproj | 13 +--- Lidgren.Network/NetBigInteger.cs | 4 +- Lidgren.Network/NetBitVector.cs | 25 ++++++- Lidgren.Network/NetBitWriter.cs | 19 +---- Lidgren.Network/NetConnection.Handshake.cs | 11 +-- Lidgren.Network/NetConnection.Reliability.cs | 21 ++---- Lidgren.Network/NetConnection.cs | 13 +--- Lidgren.Network/NetConnectionStatistics.cs | 2 +- Lidgren.Network/NetEncryption.cs | 53 ++++++++++---- Lidgren.Network/NetException.cs | 2 +- Lidgren.Network/NetFragmentationInfo.cs | 2 +- Lidgren.Network/NetIncomingMessage.Read.cs | 2 +- Lidgren.Network/NetIncomingMessage.cs | 26 ++++++- Lidgren.Network/NetOutgoingMessage.cs | 16 ++++ Lidgren.Network/NetPeer.Discovery.cs | 4 +- Lidgren.Network/NetPeer.Internal.cs | 17 +---- Lidgren.Network/NetPeer.LatencySimulation.cs | 3 +- Lidgren.Network/NetPeer.cs | 14 ++-- Lidgren.Network/NetPeerConfiguration.cs | 18 ++--- Lidgren.Network/NetPeerStatistics.cs | 2 +- Lidgren.Network/NetPeerStatus.cs | 1 + Lidgren.Network/NetQueue.cs | 23 +++++- Lidgren.Network/NetTime.cs | 4 +- .../MSServer/MSServer.csproj | 69 ++++++++++++++++++ .../MasterServerSample/MSServer/Program.cs | 38 ++++++++++ .../MSServer/Properties/AssemblyInfo.cs | 36 +++++++++ .../MasterServerSample/MasterServerSample.suo | Bin 52224 -> 52224 bytes UnitTests/EncryptionTests.cs | 55 +++++++++++++- UnitTests/Program.cs | 14 +++- UnitTests/ReadWriteTests.cs | 8 +- UnitTests/UnitTests.csproj | 5 -- 31 files changed, 381 insertions(+), 139 deletions(-) create mode 100644 Samples/MasterServerSample/MSServer/MSServer.csproj create mode 100644 Samples/MasterServerSample/MSServer/Program.cs create mode 100644 Samples/MasterServerSample/MSServer/Properties/AssemblyInfo.cs diff --git a/Lidgren.Network/Lidgren.Network.csproj b/Lidgren.Network/Lidgren.Network.csproj index 4b0713a..4edeaf1 100644 --- a/Lidgren.Network/Lidgren.Network.csproj +++ b/Lidgren.Network/Lidgren.Network.csproj @@ -3,7 +3,7 @@ Debug AnyCPU - 9.0.30729 + 9.0.21022 2.0 {FA245447-5F23-4AA1-BD5F-8D2DDF33CFBD} Library @@ -33,17 +33,6 @@ - - 3.5 - - - 3.5 - - - 3.5 - - - diff --git a/Lidgren.Network/NetBigInteger.cs b/Lidgren.Network/NetBigInteger.cs index 1b0bdd0..65f57b5 100644 --- a/Lidgren.Network/NetBigInteger.cs +++ b/Lidgren.Network/NetBigInteger.cs @@ -39,7 +39,7 @@ using System.Security.Cryptography; namespace Lidgren.Network { - public class BigInteger + public sealed class BigInteger { /// /// The Length of this BigInteger @@ -1271,7 +1271,7 @@ namespace Lidgren.Network /// /// Low level functions for the BigInteger /// - private sealed class Kernel + private static class Kernel { /// /// Adds two numbers with the same sign. diff --git a/Lidgren.Network/NetBitVector.cs b/Lidgren.Network/NetBitVector.cs index 4deb60a..d10efd5 100644 --- a/Lidgren.Network/NetBitVector.cs +++ b/Lidgren.Network/NetBitVector.cs @@ -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; } } diff --git a/Lidgren.Network/NetBitWriter.cs b/Lidgren.Network/NetBitWriter.cs index 2209b33..e8bbac9 100644 --- a/Lidgren.Network/NetBitWriter.cs +++ b/Lidgren.Network/NetBitWriter.cs @@ -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) diff --git a/Lidgren.Network/NetConnection.Handshake.cs b/Lidgren.Network/NetConnection.Handshake.cs index d9d7adc..2199f57 100644 --- a/Lidgren.Network/NetConnection.Handshake.cs +++ b/Lidgren.Network/NetConnection.Handshake.cs @@ -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; } } } diff --git a/Lidgren.Network/NetConnection.Reliability.cs b/Lidgren.Network/NetConnection.Reliability.cs index 4a57867..36d90fc 100644 --- a/Lidgren.Network/NetConnection.Reliability.cs +++ b/Lidgren.Network/NetConnection.Reliability.cs @@ -28,15 +28,16 @@ namespace Lidgren.Network private ushort[] m_nextSendSequenceNumber; private ushort[] m_lastReceivedSequenced; - internal List[] m_storedMessages; // naïve! replace by something better? - internal NetBitVector m_storedMessagesNotEmpty; + // TODO: naïve! replace by something better? + internal readonly List[] m_storedMessages = new List[NetConstants.NumReliableChannels]; + internal readonly NetBitVector m_storedMessagesNotEmpty = new NetBitVector(NetConstants.NumReliableChannels); - private ushort[] m_nextExpectedReliableSequence; - private List[] m_withheldMessages; - internal Queue m_acknowledgesToSend; + private readonly ushort[] m_nextExpectedReliableSequence = new ushort[NetConstants.NumReliableChannels]; + private readonly List[] m_withheldMessages = new List[NetConstants.NetChannelsPerDeliveryMethod]; // only for ReliableOrdered + internal readonly Queue m_acknowledgesToSend = new Queue(); 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[NetConstants.NumReliableChannels]; - m_storedMessagesNotEmpty = new NetBitVector(NetConstants.NumReliableChannels); - - m_reliableReceived = new NetBitVector[NetConstants.NumSequenceNumbers]; - m_nextExpectedReliableSequence = new ushort[NetConstants.NumReliableChannels]; - m_withheldMessages = new List[NetConstants.NetChannelsPerDeliveryMethod]; // only for ReliableOrdered - m_acknowledgesToSend = new Queue(); } internal ushort GetSendSequenceNumber(NetMessageType mtp) diff --git a/Lidgren.Network/NetConnection.cs b/Lidgren.Network/NetConnection.cs index 9c743d3..ab013fc 100644 --- a/Lidgren.Network/NetConnection.cs +++ b/Lidgren.Network/NetConnection.cs @@ -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 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 + "]"; diff --git a/Lidgren.Network/NetConnectionStatistics.cs b/Lidgren.Network/NetConnectionStatistics.cs index 092e62c..83f74c9 100644 --- a/Lidgren.Network/NetConnectionStatistics.cs +++ b/Lidgren.Network/NetConnectionStatistics.cs @@ -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; diff --git a/Lidgren.Network/NetEncryption.cs b/Lidgren.Network/NetEncryption.cs index be25340..3fd7a73 100644 --- a/Lidgren.Network/NetEncryption.cs +++ b/Lidgren.Network/NetEncryption.cs @@ -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; } } /// /// 16 byte key /// - 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; } + /// + /// 16 byte key + /// + 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); } /// @@ -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); } /* diff --git a/Lidgren.Network/NetException.cs b/Lidgren.Network/NetException.cs index 3cfc6ef..13e9d41 100644 --- a/Lidgren.Network/NetException.cs +++ b/Lidgren.Network/NetException.cs @@ -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 { diff --git a/Lidgren.Network/NetFragmentationInfo.cs b/Lidgren.Network/NetFragmentationInfo.cs index b073885..afd4e7d 100644 --- a/Lidgren.Network/NetFragmentationInfo.cs +++ b/Lidgren.Network/NetFragmentationInfo.cs @@ -2,7 +2,7 @@ namespace Lidgren.Network { - public class NetFragmentationInfo + public sealed class NetFragmentationInfo { public int TotalFragmentCount; public bool[] Received; diff --git a/Lidgren.Network/NetIncomingMessage.Read.cs b/Lidgren.Network/NetIncomingMessage.Read.cs index bc7a0de..aa56443 100644 --- a/Lidgren.Network/NetIncomingMessage.Read.cs +++ b/Lidgren.Network/NetIncomingMessage.Read.cs @@ -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; diff --git a/Lidgren.Network/NetIncomingMessage.cs b/Lidgren.Network/NetIncomingMessage.cs index 1611d13..ca7ab1d 100644 --- a/Lidgren.Network/NetIncomingMessage.cs +++ b/Lidgren.Network/NetIncomingMessage.cs @@ -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; } } + /// + /// Returns the internal data buffer, don't modify + /// + public byte[] PeekDataBuffer() + { + return m_data; + } + /// /// Gets the NetDeliveryMethod used by this message /// @@ -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]", diff --git a/Lidgren.Network/NetOutgoingMessage.cs b/Lidgren.Network/NetOutgoingMessage.cs index 01ca175..4a70a14 100644 --- a/Lidgren.Network/NetOutgoingMessage.cs +++ b/Lidgren.Network/NetOutgoingMessage.cs @@ -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(); diff --git a/Lidgren.Network/NetPeer.Discovery.cs b/Lidgren.Network/NetPeer.Discovery.cs index b788209..3b80a2d 100644 --- a/Lidgren.Network/NetPeer.Discovery.cs +++ b/Lidgren.Network/NetPeer.Discovery.cs @@ -10,7 +10,7 @@ namespace Lidgren.Network /// 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 /// public bool DiscoverKnownPeer(IPEndPoint endpoint) { - NetOutgoingMessage om = CreateMessage(); + NetOutgoingMessage om = CreateMessage(0); SendUnconnectedLibraryMessage(om, NetMessageLibraryType.Discovery, endpoint); return true; } diff --git a/Lidgren.Network/NetPeer.Internal.cs b/Lidgren.Network/NetPeer.Internal.cs index 357297f..d6ab3df 100644 --- a/Lidgren.Network/NetPeer.Internal.cs +++ b/Lidgren.Network/NetPeer.Internal.cs @@ -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 m_releasedIncomingMessages; - private NetQueue m_unsentUnconnectedMessage; + private readonly NetQueue m_releasedIncomingMessages = new NetQueue(16); + private readonly NetQueue m_unsentUnconnectedMessage = new NetQueue(4); /// /// Signalling event which can be waited on to determine when a message is queued for reading. @@ -47,13 +45,6 @@ namespace Lidgren.Network /// public AutoResetEvent MessageReceivedEvent { get { return m_messageReceivedEvent; } } - private void InternalInitialize() - { - m_releasedIncomingMessages = new NetQueue(16); - m_unsentUnconnectedMessage = new NetQueue(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) diff --git a/Lidgren.Network/NetPeer.LatencySimulation.cs b/Lidgren.Network/NetPeer.LatencySimulation.cs index 60f2824..0514fe7 100644 --- a/Lidgren.Network/NetPeer.LatencySimulation.cs +++ b/Lidgren.Network/NetPeer.LatencySimulation.cs @@ -28,7 +28,7 @@ namespace Lidgren.Network { #if DEBUG - private List m_delayedPackets = new List(); + private readonly List m_delayedPackets = new List(); private class DelayedPacket { @@ -117,6 +117,7 @@ namespace Lidgren.Network LogError("Failed to send packet: " + ex); } } + #else // // Release - just send the packet straight away diff --git a/Lidgren.Network/NetPeer.cs b/Lidgren.Network/NetPeer.cs index 98b0b89..7a719ec 100644 --- a/Lidgren.Network/NetPeer.cs +++ b/Lidgren.Network/NetPeer.cs @@ -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 m_connections; - private Dictionary m_connectionLookup; + internal readonly List m_connections; + private readonly Dictionary m_connectionLookup; /// /// Gets the status of the NetPeer @@ -98,12 +98,10 @@ namespace Lidgren.Network { m_status = NetPeerStatus.NotRunning; m_configuration = configuration; - m_connections = new List(); - m_connectionLookup = new Dictionary(); + m_connections = new List(m_configuration.MaximumConnections); + m_connectionLookup = new Dictionary(m_configuration.MaximumConnections); m_senderRemote = (EndPoint)new IPEndPoint(IPAddress.Any, 0); m_statistics = new NetPeerStatistics(this); - - InternalInitialize(); } /// diff --git a/Lidgren.Network/NetPeerConfiguration.cs b/Lidgren.Network/NetPeerConfiguration.cs index 0fa3607..ba099c8 100644 --- a/Lidgren.Network/NetPeerConfiguration.cs +++ b/Lidgren.Network/NetPeerConfiguration.cs @@ -208,36 +208,36 @@ namespace Lidgren.Network /// /// Enables receiving of the specified type of message /// - public void EnableMessageType(NetIncomingMessageType tp) + public void EnableMessageType(NetIncomingMessageType type) { - m_disabledTypes &= (~tp); + m_disabledTypes &= (~type); } /// /// Disables receiving of the specified type of message /// - public void DisableMessageType(NetIncomingMessageType tp) + public void DisableMessageType(NetIncomingMessageType type) { - m_disabledTypes |= tp; + m_disabledTypes |= type; } /// /// Enables or disables receiving of the specified type of message /// - 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; } /// /// Gets if receiving of the specified type of message is enabled /// - public bool IsMessageTypeEnabled(NetIncomingMessageType tp) + public bool IsMessageTypeEnabled(NetIncomingMessageType type) { - return !((m_disabledTypes & tp) == tp); + return !((m_disabledTypes & type) == type); } /// diff --git a/Lidgren.Network/NetPeerStatistics.cs b/Lidgren.Network/NetPeerStatistics.cs index efdad46..f569480 100644 --- a/Lidgren.Network/NetPeerStatistics.cs +++ b/Lidgren.Network/NetPeerStatistics.cs @@ -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; diff --git a/Lidgren.Network/NetPeerStatus.cs b/Lidgren.Network/NetPeerStatus.cs index bd711aa..5243005 100644 --- a/Lidgren.Network/NetPeerStatus.cs +++ b/Lidgren.Network/NetPeerStatus.cs @@ -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; diff --git a/Lidgren.Network/NetQueue.cs b/Lidgren.Network/NetQueue.cs index 6344672..295ec5a 100644 --- a/Lidgren.Network/NetQueue.cs +++ b/Lidgren.Network/NetQueue.cs @@ -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; diff --git a/Lidgren.Network/NetTime.cs b/Lidgren.Network/NetTime.cs index bd217ac..4fd78fb 100644 --- a/Lidgren.Network/NetTime.cs +++ b/Lidgren.Network/NetTime.cs @@ -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; /// /// Get number of seconds since the application started diff --git a/Samples/MasterServerSample/MSServer/MSServer.csproj b/Samples/MasterServerSample/MSServer/MSServer.csproj new file mode 100644 index 0000000..4a4c4f3 --- /dev/null +++ b/Samples/MasterServerSample/MSServer/MSServer.csproj @@ -0,0 +1,69 @@ + + + + Debug + AnyCPU + 9.0.21022 + 2.0 + {BBE12F3E-098F-4C13-842F-A52B86E2611A} + Exe + Properties + MSServer + MSServer + v3.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + 3.5 + + + 3.5 + + + 3.5 + + + + + + + + + + + {FA245447-5F23-4AA1-BD5F-8D2DDF33CFBD} + Lidgren.Network + + + {DCD2BE10-1B14-4C80-8BD6-77A8B1F43346} + MSCommon + + + + + \ No newline at end of file diff --git a/Samples/MasterServerSample/MSServer/Program.cs b/Samples/MasterServerSample/MSServer/Program.cs new file mode 100644 index 0000000..bbe9727 --- /dev/null +++ b/Samples/MasterServerSample/MSServer/Program.cs @@ -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(); + } + } +} diff --git a/Samples/MasterServerSample/MSServer/Properties/AssemblyInfo.cs b/Samples/MasterServerSample/MSServer/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..9061f54 --- /dev/null +++ b/Samples/MasterServerSample/MSServer/Properties/AssemblyInfo.cs @@ -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")] diff --git a/Samples/MasterServerSample/MasterServerSample.suo b/Samples/MasterServerSample/MasterServerSample.suo index 9e31e21f8689f17406a5f106268ea2700ce5fdbd..75f0250a9b3a1b565774e07969a12f2add6df292 100644 GIT binary patch delta 910 zcma)4OK1~O6rDGpG@Z=UG)-#ru^szS8>3Ayf)T8hR*0fZ)hr4s2qIkwrN|WGXE7VW zrQ}Kp62XkCRz>LpX}XXwfzpLFW2m@QS7N~*18&6nUKU{jR(oNX_wG6O-t*3TdY;qs z-17n}j4%u{2u1e15Fx8$7;#sTOUDbw%^&z0UlXJa5xyIBW4WX@!V5aNwl4!~%Q38VRFRBmi%uu31xT?-iUTSuGYJCmO>kEgDtrR8 z;J6efK#LQ!gBA+aCDlf!Q>=YM8*fL96S zQk`J7`r&9?!J1NSmC<(6w8z<4i&_%(LTO6w{ROLwllWcC&-XnLUb7-~L}eL7STqh@ zT&MEtpJoEg53vtyq) z_?E80rSx5Fo)~r;nYeM5#naEG5T3d{x^3tGwb$+y(UuN5J8K}MLMq=!Z=G3vob-MD z{bd6YQ(R;pA|H=u@*WDUphmn7le%^5uZ@&yu-L}nVUln3C}$tZXSCJ+ZjqX(?X8_-?ww$LX_ y0zUMP=FGHvKUp^}RWsH46SYlMMneSI*MwF`mU82cEVe5uPm8d&BC!h@9sL1zf+gkv delta 896 zcma)4OK1~e5Z-?ub(8FtHtkmPpjlHz8>8Kn7R>lx+a&Z51Lj`zh3BgF#o4q{B*%rjlTx?23TCqw?qVBw?P{ z!1Pqfo<@Dsn<3pW;TsdT+j5}kTjsKAJJbSUXjeO^Nk-wVLxIDZin>~H$c=6TwiwVu zRcRXq)D7UipD>p zPp2_`tG{LEv;THmyHg-r8f$vmAY=-nxh{`HyIFkH=l=fd+Zv&3h*E!yY7i%KE*?C^ zZg`mY%Ny5H%g=C~o3G894)5M`vgAJ8i27j8Xz^~&#;?X_1ulm#!s3fj%oHWz->F%g zdHtLSAzDO$@wwfQzL133tDWG_yXmPFi~y`2JpV#pm6qu%_2Q56ab6}plybmEL;an^!l#8Gq{Ng>W4{6Cf*qRx diff --git a/UnitTests/EncryptionTests.cs b/UnitTests/EncryptionTests.cs index 5333511..952e68f 100644 --- a/UnitTests/EncryptionTests.cs +++ b/UnitTests/EncryptionTests.cs @@ -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); diff --git a/UnitTests/Program.cs b/UnitTests/Program.cs index a2cd0c1..84b7595 100644 --- a/UnitTests/Program.cs +++ b/UnitTests/Program.cs @@ -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; + } } } diff --git a/UnitTests/ReadWriteTests.cs b/UnitTests/ReadWriteTests.cs index dd02824..12e18df 100644 --- a/UnitTests/ReadWriteTests.cs +++ b/UnitTests/ReadWriteTests.cs @@ -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); diff --git a/UnitTests/UnitTests.csproj b/UnitTests/UnitTests.csproj index cd8032d..79afe54 100644 --- a/UnitTests/UnitTests.csproj +++ b/UnitTests/UnitTests.csproj @@ -32,11 +32,6 @@ - - 3.5 - - -