ToHexString() public static method

Create a hex string from an array of bytes
public static ToHexString ( byte data ) : string
data byte
return string
Example #1
0
        /// <summary>
        /// Compute client public ephemeral value (A)
        /// </summary>
        public static byte[] ComputeClientEphemeral(byte[] clientPrivateEphemeral)         // a
        {
            // A= g^a (mod N)
            NetBigInteger a      = new NetBigInteger(NetUtility.ToHexString(clientPrivateEphemeral), 16);
            NetBigInteger retval = g.ModPow(a, N);

            return(retval.ToByteArrayUnsigned());
        }
Example #2
0
        /// <summary>
        /// Creates a verifier that the server can later use to authenticate users later on (v)
        /// </summary>
        public static byte[] ComputeServerVerifier(byte[] privateKey)
        {
            NetBigInteger x = new NetBigInteger(NetUtility.ToHexString(privateKey), 16);

            // Verifier (v) = g^x (mod N)
            var serverVerifier = g.ModPow(x, N);

            return(serverVerifier.ToByteArrayUnsigned());
        }
        private void InitializeNetwork()
        {
            lock (m_initializeLock)
            {
                m_configuration.Lock();

                if (m_status == NetPeerStatus.Running)
                {
                    return;
                }

                if (m_configuration.m_enableUPnP)
                {
                    m_upnp = new NetUPnP(this);
                }

                InitializePools();

                m_releasedIncomingMessages.Clear();
                m_unsentUnconnectedMessages.Clear();
                m_handshakes.Clear();

                // bind to socket
                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];
                MWCRandom.Instance.NextBytes(macBytes);

#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
                m_status = NetPeerStatus.Running;
            }
        }
Example #4
0
        /// <summary>
        /// Computer private key (x)
        /// </summary>
        public static byte[] ComputePrivateKey(string username, string password, byte[] salt)
        {
            byte[] tmp       = Encoding.UTF8.GetBytes(username + ":" + password);
            byte[] innerHash = NetUtility.ComputeSHAHash(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);

            // x   ie. H(salt || H(username || ":" || password))
            return(new NetBigInteger(NetUtility.ToHexString(NetUtility.ComputeSHAHash(total)), 16).ToByteArrayUnsigned());
        }
Example #5
0
        /// <summary>
        /// Compute server ephemeral value (B)
        /// </summary>
        public static byte[] ComputeServerEphemeral(byte[] serverPrivateEphemeral, byte[] verifier)         // b
        {
            var b = new NetBigInteger(NetUtility.ToHexString(serverPrivateEphemeral), 16);
            var v = new NetBigInteger(NetUtility.ToHexString(verifier), 16);

            // B = kv + g^b (mod N)
            var bb = g.ModPow(b, N);
            var kv = v.Multiply(k);
            var B  = (kv.Add(bb)).Mod(N);

            return(B.ToByteArrayUnsigned());
        }
Example #6
0
        public static byte[] ComputeServerSessionValue(byte[] clientPublicEphemeral, byte[] verifier, byte[] udata, byte[] serverPrivateEphemeral)
        {
            // S = (Av^u) ^ b (mod N)
            var A = new NetBigInteger(NetUtility.ToHexString(clientPublicEphemeral), 16);
            var v = new NetBigInteger(NetUtility.ToHexString(verifier), 16);
            var u = new NetBigInteger(NetUtility.ToHexString(udata), 16);
            var b = new NetBigInteger(NetUtility.ToHexString(serverPrivateEphemeral), 16);

            NetBigInteger retval = v.ModPow(u, N).Multiply(A).Mod(N).ModPow(b, N).Mod(N);

            return(retval.ToByteArrayUnsigned());
        }
Example #7
0
        /// <summary>
        /// Compute multiplier (k)
        /// </summary>
        private static NetBigInteger ComputeMultiplier()
        {
            string one = NetUtility.ToHexString(N.ToByteArrayUnsigned());
            string two = NetUtility.ToHexString(g.ToByteArrayUnsigned());

            string ccstr = one + two.PadLeft(one.Length, '0');
            var    cc    = NetUtility.HexToBytes(ccstr, stackalloc byte[ccstr.Length * 2]);

            var ccHashed = NetUtility.ComputeSHAHash(cc, stackalloc byte[NetUtility.SHAHashSize]);

            return(new NetBigInteger(NetUtility.ToHexString(ccHashed), 16));
        }
Example #8
0
        /// <summary>
        /// Compute multiplier (k)
        /// </summary>
        private static NetBigInteger ComputeMultiplier()
        {
            string one = NetUtility.ToHexString(N.ToByteArrayUnsigned());
            string two = NetUtility.ToHexString(g.ToByteArrayUnsigned());

            string ccstr = one + two.PadLeft(one.Length, '0');

            byte[] cc = NetUtility.ToByteArray(ccstr);

            var ccHashed = NetUtility.ComputeSHAHash(cc);

            return(new NetBigInteger(NetUtility.ToHexString(ccHashed), 16));
        }
        internal void SendConnectionEstablished()
        {
            NetOutgoingMessage om = m_peer.CreateMessage(0);

            om.m_messageType = NetMessageType.ConnectionEstablished;
            m_peer.SendLibrary(om, m_remoteEndpoint);

            InitializePing();
            if (m_status != NetConnectionStatus.Connected)
            {
                SetStatus(NetConnectionStatus.Connected, "Connected to " + NetUtility.ToHexString(m_remoteUniqueIdentifier));
            }
        }
Example #10
0
        /// <summary>
        /// Computer private key (x)
        /// </summary>
        public static byte[] ComputePrivateKey(string username, string password, byte[] salt)
        {
            var sha = GetHashAlgorithm();

            byte[] tmp       = Encoding.UTF8.GetBytes(username + ":" + password);
            byte[] innerHash = sha.ComputeHash(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);

            return(new NetBigInteger(NetUtility.ToHexString(sha.ComputeHash(total)), 16).ToByteArrayUnsigned());
        }
Example #11
0
        public static byte[] ComputeClientSessionValue(byte[] serverPublicEphemeral, byte[] xdata, byte[] udata, byte[] clientPrivateEphemeral)
        {
            // (B - kg^x) ^ (a + ux)   (mod N)
            var B = new NetBigInteger(NetUtility.ToHexString(serverPublicEphemeral), 16);
            var x = new NetBigInteger(NetUtility.ToHexString(xdata), 16);
            var u = new NetBigInteger(NetUtility.ToHexString(udata), 16);
            var a = new NetBigInteger(NetUtility.ToHexString(clientPrivateEphemeral), 16);

            var bx   = g.ModPow(x, N);
            var btmp = B.Add(N.Multiply(k)).Subtract(bx.Multiply(k)).Mod(N);

            return(btmp.ModPow(x.Multiply(u).Add(a), N).ToByteArrayUnsigned());
        }
Example #12
0
        /// <summary>
        /// Compute intermediate value (u)
        /// </summary>
        public static byte[] ComputeU(ReadOnlySpan <byte> clientPublicEphemeral, ReadOnlySpan <byte> serverPublicEphemeral)
        {
            // u = SHA-1(A || B)
            string one = NetUtility.ToHexString(clientPublicEphemeral);
            string two = NetUtility.ToHexString(serverPublicEphemeral);

            int    len   = 66;        //  Math.Max(one.Length, two.Length);
            string ccstr = one.PadLeft(len, '0') + two.PadLeft(len, '0');

            var cc = NetUtility.HexToBytes(ccstr, stackalloc byte[ccstr.Length * 2]);

            var ccHashed = NetUtility.ComputeSHAHash(cc, stackalloc byte[32]);

            return(new NetBigInteger(NetUtility.ToHexString(ccHashed), 16).ToByteArrayUnsigned());
        }
Example #13
0
        /// <summary>
        /// Compute intermediate value (u)
        /// </summary>
        public static byte[] ComputeU(byte[] clientPublicEphemeral, byte[] serverPublicEphemeral)
        {
            // u = SHA-1(A || B)
            string one = NetUtility.ToHexString(clientPublicEphemeral);
            string two = NetUtility.ToHexString(serverPublicEphemeral);

            int    len   = 66;        //  Math.Max(one.Length, two.Length);
            string ccstr = one.PadLeft(len, '0') + two.PadLeft(len, '0');

            byte[] cc = NetUtility.ToByteArray(ccstr);

            var ccHashed = NetUtility.ComputeSHAHash(cc);

            return(new NetBigInteger(NetUtility.ToHexString(ccHashed), 16).ToByteArrayUnsigned());
        }
        internal void SendConnectionEstablished()
        {
            NetOutgoingMessage om = m_peer.CreateMessage(4);

            om.m_messageType = NetMessageType.ConnectionEstablished;
            om.Write((float)NetTime.Now);
            m_peer.SendLibrary(om, m_remoteEndPoint);

            m_handshakeAttempts = 0;

            InitializePing();
            if (m_status != NetConnectionStatus.Connected)
            {
                SetStatus(NetConnectionStatus.Connected, "Connected to " + NetUtility.ToHexString(m_remoteUniqueIdentifier));
            }
        }
Example #15
0
        /// <summary>
        /// Compute multiplier (k)
        /// </summary>
        private static BigInteger ComputeMultiplier()
        {
            string one = NetUtility.ToHexString(N.ToByteArray(isUnsigned: true));
            string two = NetUtility.ToHexString(g.ToByteArray(isUnsigned: true));

            string ccstr = one + two.PadLeft(one.Length, '0');

            byte[] cc = NetUtility.FromHexString(ccstr);

            using var algorithm = GetHashAlgorithm();
            var ccHashed = algorithm.ComputeHash(cc);

            Span <char> tmp = stackalloc char[1 + NetUtility.GetHexCharCount(ccHashed.Length)];

            tmp[0] = '0'; // ensure that the value is unsigned
            NetUtility.ToHexString(ccHashed, tmp[1..]);
        private void InitializeNetwork()
        {
            lock (m_initializeLock)
            {
                m_configuration.Lock();

                if (m_status == NetPeerStatus.Running)
                {
                    return;
                }

                InitializePools();

                m_releasedIncomingMessages.Clear();
                m_unsentUnconnectedMessages.Clear();
                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);

                IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint;
                LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound);
                m_listenPort = boundEp.Port;

                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);

#if IS_MAC_AVAILABLE
                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");
                }
#endif
                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_status = NetPeerStatus.Running;
            }
        }
        internal void ReceivedHandshake(NetMessageType tp, int ptr, int payloadLength)
        {
            m_peer.VerifyNetworkThread();

            byte[] hail;
            switch (tp)
            {
            case NetMessageType.Connect:
                if (m_status == NetConnectionStatus.None)
                {
                    // Whee! Server full has already been checked
                    bool ok = ValidateHandshakeData(ptr, payloadLength, out hail);
                    if (ok)
                    {
                        if (hail != null)
                        {
                            m_remoteHailMessage            = m_peer.CreateIncomingMessage(NetIncomingMessageType.Data, hail);
                            m_remoteHailMessage.LengthBits = (hail.Length * 8);
                        }
                        else
                        {
                            m_remoteHailMessage = null;
                        }

                        if (m_peerConfiguration.IsMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval))
                        {
                            // ok, let's not add connection just yet
                            NetIncomingMessage appMsg = m_peer.CreateIncomingMessage(NetIncomingMessageType.ConnectionApproval, (m_remoteHailMessage == null ? 0 : m_remoteHailMessage.LengthBytes));
                            appMsg.m_senderConnection = this;
                            appMsg.m_senderEndpoint   = this.m_remoteEndpoint;
                            if (m_remoteHailMessage != null)
                            {
                                appMsg.Write(m_remoteHailMessage.m_data, 0, m_remoteHailMessage.LengthBytes);
                            }
                            m_peer.ReleaseMessage(appMsg);
                            return;
                        }

                        SendConnectResponse(true);
                    }
                    return;
                }
                if (m_status == NetConnectionStatus.RespondedConnect)
                {
                    // our ConnectResponse must have been lost
                    SendConnectResponse(true);
                    return;
                }
                m_peer.LogDebug("Unhandled Connect: " + tp + ", status is " + m_status + " length: " + payloadLength);
                break;

            case NetMessageType.ConnectResponse:
                switch (m_status)
                {
                case NetConnectionStatus.InitiatedConnect:
                    // awesome
                    bool ok = ValidateHandshakeData(ptr, payloadLength, out hail);
                    if (ok)
                    {
                        if (hail != null)
                        {
                            m_remoteHailMessage            = m_peer.CreateIncomingMessage(NetIncomingMessageType.Data, hail);
                            m_remoteHailMessage.LengthBits = (hail.Length * 8);
                        }
                        else
                        {
                            m_remoteHailMessage = null;
                        }

                        m_peer.AcceptConnection(this);
                        SendConnectionEstablished();
                        return;
                    }
                    break;

                case NetConnectionStatus.RespondedConnect:
                    // hello, wtf?
                    break;

                case NetConnectionStatus.Disconnecting:
                case NetConnectionStatus.Disconnected:
                case NetConnectionStatus.None:
                    // wtf? anyway, bye!
                    break;

                case NetConnectionStatus.Connected:
                    // my ConnectionEstablished must have been lost, send another one
                    SendConnectionEstablished();
                    return;
                }
                break;

            case NetMessageType.ConnectionEstablished:
                switch (m_status)
                {
                case NetConnectionStatus.Connected:
                    // ok...
                    break;

                case NetConnectionStatus.Disconnected:
                case NetConnectionStatus.Disconnecting:
                case NetConnectionStatus.None:
                    // too bad, almost made it
                    break;

                case NetConnectionStatus.InitiatedConnect:
                    // weird, should have been ConnectResponse...
                    break;

                case NetConnectionStatus.RespondedConnect:
                    // awesome
                    m_peer.AcceptConnection(this);
                    InitializePing();
                    SetStatus(NetConnectionStatus.Connected, "Connected to " + NetUtility.ToHexString(m_remoteUniqueIdentifier));
                    return;
                }
                break;

            case NetMessageType.Disconnect:
                // ouch
                string reason = "Ouch";
                try
                {
                    NetIncomingMessage inc = m_peer.SetupReadHelperMessage(ptr, payloadLength);
                    reason = inc.ReadString();
                }
                catch
                {
                }
                SetStatus(NetConnectionStatus.Disconnected, reason);
                break;

            default:
                m_peer.LogDebug("Unhandled type during handshake: " + tp + " length: " + payloadLength);
                break;
            }
        }
Example #18
0
        private void InitializeNetwork()
        {
            lock (m_initializeLock)
            {
                m_configuration.Lock();

                if (m_status == NetPeerStatus.Running)
                {
                    return;
                }

                if (m_configuration.m_enableUPnP)
                {
                    m_upnp = new NetUPnP(this);
                }

                InitializePools();

                m_releasedIncomingMessages.Clear();
                m_unsentUnconnectedMessages.Clear();
                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;

                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);

#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
                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_status = NetPeerStatus.Running;
            }
        }
Example #19
0
        private void InitializeNetwork()
        {
            lock (m_initializeLock)
            {
                m_configuration.Lock();

                if (m_status == NetPeerStatus.Running)
                {
                    return;
                }

                if (m_configuration.m_enableUPnP)
                {
                    m_upnp = new NetUPnP(this);
                }

                InitializePools();

                m_releasedIncomingMessages.Clear();
                m_unsentUnconnectedMessages.Clear();
                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 PlatformSocket();
                m_socket.ReceiveBufferSize = m_configuration.ReceiveBufferSize;
                m_socket.SendBufferSize    = m_configuration.SendBufferSize;
                m_socket.Blocking          = false;
                m_socket.Bind(ep);
                m_socket.Setup();

                IPEndPoint boundEp = m_socket.LocalEndPoint as IPEndPoint;
                LogDebug("Socket bound to " + boundEp + ": " + m_socket.IsBound);
                m_listenPort = boundEp.Port;

                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);

#if IS_FULL_NET_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
                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);
#if WINDOWS_PHONE
                SHA1 s = new SHA1Managed();
                m_uniqueIdentifier = BitConverter.ToInt64(s.ComputeHash(combined), 0);
#else
                m_uniqueIdentifier = BitConverter.ToInt64(SHA1.Create().ComputeHash(combined), 0);
#endif

                m_status = NetPeerStatus.Running;
            }
        }
        internal void ReceivedHandshake(double now, NetMessageType tp, int ptr, int payloadLength)
        {
            byte[] hail;
            switch (tp)
            {
            case NetMessageType.Connect:
                if (m_status == NetConnectionStatus.ReceivedInitiation)
                {
                    // Whee! Server full has already been checked
                    bool ok = ValidateHandshakeData(ptr, payloadLength, out hail);
                    if (ok)
                    {
                        if (hail != null)
                        {
                            m_remoteHailMessage            = m_peer.CreateIncomingMessage(NetIncomingMessageType.Data, hail);
                            m_remoteHailMessage.LengthBits = (hail.Length * 8);
                        }
                        else
                        {
                            m_remoteHailMessage = null;
                        }

                        if (m_peerConfiguration.IsMessageTypeEnabled(NetIncomingMessageType.ConnectionApproval))
                        {
                            // ok, let's not add connection just yet
                            NetIncomingMessage appMsg = m_peer.CreateIncomingMessage(NetIncomingMessageType.ConnectionApproval, (m_remoteHailMessage == null ? 0 : m_remoteHailMessage.LengthBytes));
                            appMsg.m_receiveTime      = now;
                            appMsg.m_senderConnection = this;
                            appMsg.m_senderEndPoint   = this.m_remoteEndPoint;
                            if (m_remoteHailMessage != null)
                            {
                                appMsg.Write(m_remoteHailMessage.m_data, 0, m_remoteHailMessage.LengthBytes);
                            }
                            SetStatus(NetConnectionStatus.RespondedAwaitingApproval, "Awaiting approval");
                            m_peer.ReleaseMessage(appMsg);
                            return;
                        }

                        SendConnectResponse((float)now, true);
                    }
                    return;
                }
                if (m_status == NetConnectionStatus.RespondedAwaitingApproval)
                {
                    m_peer.LogWarning("Ignoring multiple Connect() most likely due to a delayed Approval");
                    return;
                }
                if (m_status == NetConnectionStatus.RespondedConnect)
                {
                    // our ConnectResponse must have been lost
                    SendConnectResponse((float)now, true);
                    return;
                }
                m_peer.LogDebug("Unhandled Connect: " + tp + ", status is " + m_status + " length: " + payloadLength);
                break;

            case NetMessageType.ConnectResponse:
                HandleConnectResponse(now, tp, ptr, payloadLength);
                break;

            case NetMessageType.ConnectionEstablished:
                switch (m_status)
                {
                case NetConnectionStatus.Connected:
                    // ok...
                    break;

                case NetConnectionStatus.Disconnected:
                case NetConnectionStatus.Disconnecting:
                case NetConnectionStatus.None:
                    // too bad, almost made it
                    break;

                case NetConnectionStatus.ReceivedInitiation:
                    // uh, a little premature... ignore
                    break;

                case NetConnectionStatus.InitiatedConnect:
                    // weird, should have been RespondedConnect...
                    break;

                case NetConnectionStatus.RespondedConnect:
                    // awesome

                    NetIncomingMessage msg = m_peer.SetupReadHelperMessage(ptr, payloadLength);
                    InitializeRemoteTimeOffset(msg.ReadSingle());

                    m_peer.AcceptConnection(this);
                    InitializePing();
                    SetStatus(NetConnectionStatus.Connected, "Connected to " + NetUtility.ToHexString(m_remoteUniqueIdentifier));
                    return;
                }
                break;

            case NetMessageType.Disconnect:
                // ouch
                string reason = "Ouch";
                try
                {
                    NetIncomingMessage inc = m_peer.SetupReadHelperMessage(ptr, payloadLength);
                    reason = inc.ReadString();
                }
                catch
                {
                }
                ExecuteDisconnect(reason, false);
                break;

            case NetMessageType.Discovery:
                m_peer.HandleIncomingDiscoveryRequest(now, m_remoteEndPoint, ptr, payloadLength);
                return;

            case NetMessageType.DiscoveryResponse:
                m_peer.HandleIncomingDiscoveryResponse(now, m_remoteEndPoint, ptr, payloadLength);
                return;

            case NetMessageType.Ping:
                // silently ignore
                return;

            default:
                m_peer.LogDebug("Unhandled type during handshake: " + tp + " length: " + payloadLength);
                break;
            }
        }
Example #21
0
        private void InitializeNetwork()
        {
            lock (m_initializeLock)
            {
                m_configuration.Lock();

                if (m_status == NetPeerStatus.Running)
                {
                    return;
                }

                if (m_configuration.m_enableUPnP)
                {
                    m_upnp = new NetUPnP(this);
                }

                InitializePools();

                m_releasedIncomingMessages.Clear();
                m_unsentUnconnectedMessages.Clear();
                m_handshakes.Clear();

                // bind to socket
                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];
                MWCRandom.Instance.NextBytes(macBytes);

#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
                IPEndPoint boundEp  = m_socket.LocalEndPoint as IPEndPoint;
                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(NetUtility.CreateSHA1Hash(combined), 0);

                m_status = NetPeerStatus.Running;
            }
        }