public void Init(System.Net.IPEndPoint inServerAddress, string inName, byte inWorldId)
    {
        base.Init(core.World.DefaultWorldCount);

        // client
        NetPeerConfiguration config = new NetPeerConfiguration("game", inServerAddress.AddressFamily);

#if DEBUG
        // 디버깅 환경에서 타임 아웃 처리 조정
        config.ConnectionTimeout = 300f;

        //if (Configuration.Instance.EnableLatencySimulation)
        //{
        //    config.SimulatedLoss = Configuration.Instance.SimulatedLoss;
        //    config.SimulatedRandomLatency = Configuration.Instance.SimulatedRandomLatency;
        //    config.SimulatedMinimumLatency = Configuration.Instance.SimulatedMinimumLatency;
        //    config.SimulatedDuplicatesChance = Configuration.Instance.SimulatedDuplicatesChance;
        //}
#endif

        //config.AutoFlushSendQueue = false;
        mNetPeer = new NetClient(config);
        mNetPeer.Start();
        mDeliveryNotificationManager = new core.DeliveryNotificationManager(true, false);
        mReplicationManagerClient    = new ReplicationManagerClient();

        algo = new NetXorEncryption(GetClient(), "AceTopSecret");

        mLastRoundTripTime     = 0.0f;
        mTimeOfLastInputPacket = 0f;


        mServerAddress       = inServerAddress;
        mState               = NetworkClientState.SayingHello;
        mTimeOfLastHello     = 0.0f;
        mTimeOfLastStartPlay = 0.0f;
        mName           = inName;
        mWorldId        = inWorldId;
        tryConnectCount = 0;

        mAvgRoundTripTime = new core.WeightedTimedMovingAverage(1.0f);

        NetOutgoingMessage hail = GetClient().CreateMessage("hail");
        GetClient().Connect(mServerAddress, hail);
        IsTcp     = false;
        IsUdpOk   = false;
        IsTrySend = true;

        respawn = false;

        // tcp
        SetConnector(inServerAddress);

        LinkedObject.Clear();
    }
예제 #2
0
        public NetworkClient()
        {
            this._config = new NetPeerConfiguration(NetworkSetting.AppIdentifier);
            //this._config.LocalAddress = IPAddress.Parse(NetworkSetting.IpAddress);

            this._config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);

            this._client = new NetClient(this._config);

            this._algo = new NetXtea(this._client, NetworkSetting.Encryptionkey);
        }
예제 #3
0
        /// <summary>
        /// Sends a message by serializing with ProtoBufs
        /// </summary>
        /// <param name="m">Message to be sent</param>
        /// <param name="conn">Connection to send across</param>
        /// <param name="alg">Optional encryption algorithm</param>
        public static void SendViaProto(ProtoMessage m, NetConnection conn, NetEncryption alg = null)
        {
            Contract.Requires(m != null && conn != null);
            NetOutgoingMessage msg = server.CreateMessage();
            MemoryStream       ms  = new MemoryStream();

            Serializer.SerializeWithLengthPrefix <ProtoMessage>(ms, m, PrefixStyle.Fixed32);
            msg.Write(ms.GetBuffer());
            if (alg != null)
            {
                msg.Encrypt(alg);
            }
            server.SendMessage(msg, conn, NetDeliveryMethod.ReliableOrdered);
            server.FlushSendQueue();
        }
예제 #4
0
        public NetworkServer()
        {
            this._config = new NetPeerConfiguration(NetworkSetting.AppIdentifier);
            this._config.LocalAddress = IPAddress.Parse(NetworkSetting.LocalIpAddress);
            this._config.Port         = NetworkSetting.Port;

            this._config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);
            this._config.EnableMessageType(NetIncomingMessageType.ConnectionApproval);

            this._server = new NetServer(this._config);
            // create the Synchronization Context
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
            this._server.RegisterReceivedCallback(new SendOrPostCallback(OnMessage));

            this._algo = new NetXtea(this._server, NetworkSetting.Encryptionkey);
        }
 /// <summary>
 /// Registers a NetEncryption with a given IPEndPoint.
 /// </summary>
 /// <param name="endPoint"></param>
 /// <param name="provider"></param>
 /// <returns>True if successful, false if IPEndPoint already has encryption and registration was ignored.</returns>
 public bool Register(IPEndPoint endPoint, NetEncryption provider)
 {
     if (endPoint == null)
     {
         throw new ArgumentNullException(nameof(endPoint));
     }
     if (provider == null)
     {
         throw new ArgumentNullException(nameof(provider));
     }
     if (_endPointMap.ContainsKey(endPoint))
     {
         return(false);
     }
     _endPointMap[endPoint] = provider;
     return(true);
 }
예제 #6
0
        /// <summary>
        /// Sends a message by serializing with ProtoBufs
        /// </summary>
        /// <param name="m">Message to be sent</param>
        /// <param name="conn">Connection to send across</param>
        /// <param name="alg">Optional encryption algorithm</param>
        public static void SendViaProto(ProtoMessage m, NetConnection conn, NetEncryption alg = null)
        {
            Contract.Requires(m != null && conn != null);
            NetOutgoingMessage msg = server.CreateMessage();
            MemoryStream       ms  = new MemoryStream();

            Serializer.SerializeWithLengthPrefix <ProtoMessage>(ms, m, PrefixStyle.Fixed32);
            msg.Write(ms.GetBuffer());
            if (alg != null)
            {
                msg.Encrypt(alg);
            }
            server.SendMessage(msg, conn, NetDeliveryMethod.ReliableOrdered);
            server.FlushSendQueue();

            Globals_Server.logEvent(""
                                    + " Sending to: " + clientConnections[conn].username
                                    + " | ActionType = " + m.ActionType.ToString()
                                    + " | ResponseType = " + m.ResponseType.ToString()
                                    + " | " + conn.RemoteEndPoint.ToString()
                                    );
        }
        void Init(uint16_t inPort, byte worldCount, float ConnectionTimeout)
        {
            base.Init(worldCount);
            mNewNetworkId = new ushort[worldCount];
            mNewPlayerId  = new int[worldCount];
            for (byte i = 0; i < worldCount; ++i)
            {
                ResetNewNetworkId(i);
                mNewPlayerId[i] = 1;
            }

            NetPeerConfiguration config = new NetPeerConfiguration("game");

            config.MaximumConnections = 1000;
            config.Port = inPort;
            config.ConnectionTimeout = ConnectionTimeout;
            mNetPeer = new NetServer(config);
            mNetPeer.Start();

            algo = new NetXorEncryption(GetServer(), "AceTopSecret");

            // tcp
            SetListener(inPort);
        }
 /// <summary>
 /// Decrypt a message
 /// </summary>
 /// <param name="encryption">The encryption algorithm used to encrypt the message</param>
 /// <returns>true on success</returns>
 public bool Decrypt(NetEncryption encryption)
 {
     return(encryption.Decrypt(this));
 }
예제 #9
0
        public bool ValidateCertificateAndCreateKey(ProtoLogIn login, out byte[] key)
        {
            if (login == null || login.certificate == null)
            {
                key = null;
                return(false);
            }
            else
            {
                try
                {
                    // Get certificate
                    X509Certificate2         cert = new X509Certificate2(login.certificate);
                    RSACryptoServiceProvider rsa  = (RSACryptoServiceProvider)cert.PublicKey.Key;
#if DEBUG
                    if (this.key != null)
                    {
                        if (this.key.Length == 0)
                        {
                            alg = new NetAESEncryption(client);
                        }
                        else
                        {
                            alg = new NetAESEncryption(client,
                                                       this.key, 0, this.key.Length);
                        }
                        key = rsa.Encrypt(this.key, false);
                    }
                    else
                    {
                        // If no key, do not use an encryption algorithm
                        alg = null;
                        key = null;
                    }
#else
                    // Create a new symmetric key
                    TripleDES des = TripleDESCryptoServiceProvider.Create();
                    des.GenerateKey();
                    // Encrypt key with server's public key
                    this.key = des.Key;
                    key      = rsa.Encrypt(des.Key, false);
                    // Initialise the algoitm
                    alg = new NetAESEncryption(client, des.Key, 0, des.Key.Length);
                    Console.WriteLine("CLIENT: my unencrypted key:");
                    foreach (var bite in des.Key)
                    {
                        Console.Write(bite.ToString());
                    }
#endif
                    // Validate certificate
                    if (!cert.Verify())
                    {
                        X509Chain CertificateChain = new X509Chain();
                        //If you do not provide revokation information, use the following line.
                        CertificateChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                        bool IsCertificateChainValid = CertificateChain.Build(cert);
                        if (!IsCertificateChainValid)
                        {
                            for (int i = 0; i < CertificateChain.ChainStatus.Length; i++)
                            {
                            }
                            // TODO change to false after testing
                            return(true);
                        }
                    }
                    // temporary certificate validation fix
                    return(true);
                    //return cert.Verify();
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("A problem occurred when parsing certificate from bytes: \n" + "type: " + e.GetType().FullName + "\n " + ", source: " + e.Source + "\n message: " + e.Message);
                    key = null;
                    return(false);
                }
            }
        }
        public static void TestEncryption(NetEncryption algo, bool printName = true)
        {
            NetOutgoingMessage om = algo.Peer.CreateMessage();

            om.Write("Hallon");
            om.Write(42);
            om.Write(5, 5);
            om.Write(true);
            om.Write("kokos");

            int unencLen = om.BitLength;

            if (!om.Encrypt(algo))
            {
                throw new LidgrenException("failed to encrypt");
            }

            // convert to incoming message
            NetIncomingMessage im = Program.CreateIncomingMessage(
                om.GetBuffer().AsSpan(0, om.ByteLength).ToArray(), om.BitLength);

            if (im.GetBuffer().Length == 0)
            {
                throw new LidgrenException("bad im!");
            }

            if (!im.Decrypt(algo))
            {
                throw new LidgrenException("failed to decrypt");
            }

            if (im.GetBuffer().Length == 0 || im.BitLength != unencLen)
            {
                throw new LidgrenException("Length fail");
            }

            var str = im.ReadString();

            if (str != "Hallon")
            {
                throw new LidgrenException("fail");
            }
            if (im.ReadInt32() != 42)
            {
                throw new LidgrenException("fail");
            }
            if (im.ReadInt32(5) != 5)
            {
                throw new LidgrenException("fail");
            }
            if (im.ReadBool() != true)
            {
                throw new LidgrenException("fail");
            }
            if (im.ReadString() != "kokos")
            {
                throw new LidgrenException("fail");
            }

            if (printName)
            {
                Console.WriteLine(" - " + algo.GetType().Name + " OK");
            }
        }