예제 #1
0
 /// <summary>
 /// Raises an exception to the logger.
 /// </summary>
 /// <param name="e">The exception.</param>
 public static void RaiseException(Exception e)
 {
                 #if DEBUG
                 #if TRACE
     ErrorLogger.Log(StackTracing.GetCurrentMethod().Name, e);
                 #else
     ErrorLogger.Log(Messages.Errors.FATAL_ERROR_TITLE, e);
                 #endif
                 #else
     Message(e.ToString());
                 #endif
 }
예제 #2
0
        /// <summary>
        /// Sends a packet to the client.
        /// </summary>
        /// <param name="packet">The packet to send.</param>
        public void Send(byte[] packet)
        {
            if (Socket == null || packet == null)
            {
                return;
            }

            try
            {
                lock (Locks.NetworkLock)
                {
                    byte[] pbuffer = packet;
                    byte[] buffer  = packet;

                    if (Suffix != null)
                    {
                        Array.Resize(ref buffer, buffer.Length + Suffix.Length);
                        System.Buffer.BlockCopy(Suffix, 0, buffer, buffer.Length - Suffix.Length, Suffix.Length);
                        pbuffer = buffer;
                    }

                    if (Cryptography != null)
                    {
                        buffer = new byte[pbuffer.Length];
                        System.Buffer.BlockCopy(pbuffer, 0, buffer, 0, buffer.Length);
                        buffer = Cryptography.Encrypt(buffer);
                    }

                    if (Socket.Connected)
                    {
                        Socket.Send(buffer);
                    }
                }
            }
            catch (Exception e)
            {
                                #if DEBUG
                                #if TRACE
                ErrorLogger.Log(StackTracing.GetCurrentMethod().Name, e);
                                #else
                ErrorLogger.Log(Messages.Errors.FATAL_NETWORK_ERROR_TITLE, e);
                                #endif
                                #else
                Global.Message(e.ToString());
                                #endif

                Disconnect(Messages.Errors.FATAL_NETWORK_ERROR_TITLE);
            }
        }
예제 #3
0
        /// <summary>
        /// The callback for BeginAccept.
        /// </summary>
        /// <param name="asyncResult">The asynchronous result.</param>
        private void Handle_Accept(IAsyncResult asyncResult)
        {
            try
            {
                Client <T> client = Socket.EndAccept(asyncResult);
                if (client.Socket.Connected)
                {
                    client.ShouldHandleDisconnect = ShouldHandleDisconnect;
                    if (OnConnect != null)
                    {
                        client.OnDisconnect   = OnDisconnect;
                        client.ControllerCall = _controllerCall;

                        OnConnect.BeginInvoke(client, null, null);
                    }
                }

                Socket.BeginAccept(Handle_Accept, null);
            }
            catch (Exception e)
            {
                                #if DEBUG
                                #if TRACE
                ErrorLogger.Log(StackTracing.GetCurrentMethod().Name, e);
                                #else
                ErrorLogger.Log(Messages.Errors.FATAL_NETWORK_ERROR_TITLE, e);
                                #endif
                if (e is SocketException)
                {
                    Stop();
                }
                                #else
                if (e is SocketException)
                {
                    Stop();
                    Global.Message(Messages.Errors.FATAL_NETWORK_ERROR_MSG);
                }
                Global.Message(e.ToString());
                                #endif
            }
        }
예제 #4
0
        internal static void HandleException(Exception exception, ModLogger logger = null, LogType type = LogType.CRITICAL)
        {
            if (handledException != null)
            {
                return;
            }

            string message = $"{(!exception.Message.Matches(@"^(?:(?!Exception:).)*Exception:(?!.*Exception:).*$") ? exception.GetType().Name + ": " : string.Empty)}{ReplaceInnerIfPresent(exception.Message, exception.InnerException)}";

            if (!string.IsNullOrWhiteSpace(exception.StackTrace))
            {
                message += $"\n{StackTracing.ParseStackTrace(new StackTrace(exception, true)).TrimEnd('\n')}";
            }

            (logger ?? GuuCore.LOGGER)?.Log(type, message);

            File.Copy(UNITY_LOG_FILE, NEW_UNITY_LOG_FILE, true);

            if (type == LogType.CRITICAL)
            {
                handledException = exception;
                reportWindow.Open();
            }
        }
예제 #5
0
        /// <summary>
        /// The handler for the auth request packet.
        /// </summary>
        /// <param name="client">The client.</param>
        /// <param name="packet">The packet.</param>
        private static bool Handle(Models.Client.AuthClient client, Models.Packets.AuthRequestPacket packet)
        {
            client.Account  = packet.Account;
            client.Password = packet.Password;
            var server   = Repositories.Server.ServerList.GetServerInfo(packet.Server);
            var canLogin = server != null;
            var response = new Models.Packets.AuthResponsePacket();

            if (canLogin)
            {
                try
                {
                    var dbAccount = Accounts.GetAccountByUserNameAndPassword(client.Account, client.Password);
                    if (dbAccount == null)
                    {
                        response.Status = Enums.AuthenticationStatus.InvalidAccountIDOrPassword;
                    }
                    else
                    {
                        client.Authenticated = true;
                        if (dbAccount.Banned && dbAccount.BanDate.HasValue)
                        {
                            bool shouldUnban = false;
                            switch (dbAccount.BanRange)
                            {
                            case DbAccount.BanRangeType.OneDay:
                            {
                                shouldUnban = DateTime.Now >= dbAccount.BanDate.Value.AddDays(1);
                                break;
                            }

                            case DbAccount.BanRangeType.ThreeDays:
                            {
                                shouldUnban = DateTime.Now >= dbAccount.BanDate.Value.AddDays(3);
                                break;
                            }

                            case DbAccount.BanRangeType.OneWeek:
                            {
                                shouldUnban = DateTime.Now >= dbAccount.BanDate.Value.AddDays(7);
                                break;
                            }

                            case DbAccount.BanRangeType.OneMonth:
                            {
                                shouldUnban = DateTime.Now >= dbAccount.BanDate.Value.AddMonths(1);
                                break;
                            }

                            case DbAccount.BanRangeType.ThreeMonths:
                            {
                                shouldUnban = DateTime.Now >= dbAccount.BanDate.Value.AddMonths(3);
                                break;
                            }

                            case DbAccount.BanRangeType.SixMonths:
                            {
                                shouldUnban = DateTime.Now >= dbAccount.BanDate.Value.AddMonths(6);
                                break;
                            }

                            case DbAccount.BanRangeType.OneYear:
                            {
                                shouldUnban = DateTime.Now >= dbAccount.BanDate.Value.AddYears(1);
                                break;
                            }
                            }

                            canLogin = shouldUnban;
                            if (shouldUnban)
                            {
                                dbAccount.Banned = false;
                                dbAccount.Update();
                            }
                            else
                            {
                                response.Status = Enums.AuthenticationStatus.AccountBanned;
                            }
                        }

                        if (canLogin)
                        {
                            client.ClientId = Drivers.Repositories.Safe.IdentityGenerator.GetClientId();

                            response.ClientId  = client.ClientId;
                            response.IPAddress = server.IPAddress;
                            response.Port      = server.Port;
                            response.Status    = Enums.AuthenticationStatus.Ready;

                            if (string.IsNullOrWhiteSpace(dbAccount.FirstLoginIP))
                            {
                                dbAccount.FirstLoginIP   = client.ClientSocket.IPAddress;
                                dbAccount.FirstLoginDate = DateTime.Now;
                            }

                            dbAccount.LastServer    = server.Name;
                            dbAccount.LastIP        = client.ClientSocket.IPAddress;
                            dbAccount.LastAuthKey   = client.ClientId.ToString("X") + ";" + DateTime.Now.ToBinary();
                            dbAccount.LastLoginDate = DateTime.Now;
                            dbAccount.Update();

                            var dbPlayer = Players.GetPlayerByAccount(dbAccount);
                            if (dbPlayer == null)
                            {
                                dbPlayer = Players.Create(dbAccount);
                            }
                            dbPlayer.AuthKey = dbAccount.LastAuthKey;
                            dbPlayer.Update();
                        }
                    }
                }
                catch (Exception e)
                {
                    response.Reset();
                    response.Status = Enums.AuthenticationStatus.DatebaseError;

                                        #if DEBUG
                                        #if TRACE
                    ErrorLogger.Log(StackTracing.GetCurrentMethod().Name, e);
                                        #else
                    ErrorLogger.Log(Drivers.Messages.Errors.DB_ERROR, e);
                                        #endif
                                        #else
                    Global.Message(e.ToString());
                                        #endif
                }
            }

            client.ClientSocket.Send(response);
            return(false);
        }
예제 #6
0
        /// <summary>
        /// Asynchronous handler for the body receive.
        /// </summary>
        /// <param name="asyncResult">The asynchronous result.</param>
        private void Handle_ReceiveBody(IAsyncResult asyncResult)
        {
            try
            {
                SocketError socketError;
                int         received = Socket.EndReceive(asyncResult, out socketError);

                if (!Socket.Connected)
                {
                    Disconnect(Messages.Errors.CLIENT_DISCONNECTED);
                    return;
                }

                if (socketError != SocketError.Success)
                {
                    Disconnect(Messages.Errors.SOCKET_ERROR_RECEIVE_BODY);
                    return;
                }

                if (received == 0)
                {
                    Disconnect(Messages.Errors.SOCKET_DISCONNECTED);
                    return;
                }

                lock (Locks.NetworkLock)
                {
                    if (Cryptography != null)
                    {
                        _bodyBuffer = Cryptography.Decrypt(_bodyBuffer);
                    }
                }

                System.Buffer.BlockCopy(_bodyBuffer, 0, _finalBuffer, _headReceived + _bodyReceived, received);
                _bodyReceived += received;

                if (!KeyExchange && received < _bodyExpected)
                {
                    ReceiveBody(_bodyExpected - received, false);
                }
                else
                {
                    int copyLen = _finalBuffer.Length;
                    if (Suffix != null)
                    {
                        copyLen -= Suffix.Length;
                    }
                    byte[] buffer = new Byte[copyLen];
                    System.Buffer.BlockCopy(_finalBuffer, 0, buffer, 0, buffer.Length);

                    bool result = false;

                    if (KeyExchange)
                    {
                        result = (bool)ControllerCall.Invoke(null,
                                                             new object[]
                        {
                            this,
                            IdleState,
                            (ushort)0,
                            new SocketPacket(buffer, 0)
                        });
                    }
                    else
                    {
                        var socketPacket = new SocketPacket(buffer, 4);
                        PacketTrace.Add(socketPacket);

                        result = (bool)ControllerCall.Invoke(null,
                                                             new object[]
                        {
                            this,
                            IdleState,
                            _packetIdentifier,
                            socketPacket
                        });
                    }

                    if (result)
                    {
                        BeginReceive();
                    }
                    else
                    {
                        Disconnect("Failed to handle packet. Look packet trace.");
                    }
                }
            }
            catch (Exception e)
            {
                LastException = e;

                                #if DEBUG
                                #if TRACE
                ErrorLogger.Log(StackTracing.GetCurrentMethod().Name, e);
                                #else
                ErrorLogger.Log(Messages.Errors.FATAL_NETWORK_ERROR_TITLE, e);
                                #endif
                                #else
                Global.Message(e.ToString());
                                #endif

                Disconnect(Messages.Errors.FATAL_NETWORK_ERROR_TITLE);
            }
        }
예제 #7
0
        /// <summary>
        /// Asynchronous handler for the head receive.
        /// </summary>
        /// <param name="asyncResult">The asynchronous result.</param>
        private void Handle_ReceiveHead(IAsyncResult asyncResult)
        {
            try
            {
                SocketError socketError;
                int         received = Socket.EndReceive(asyncResult, out socketError);

                if (!Socket.Connected)
                {
                    Disconnect(Messages.Errors.CLIENT_DISCONNECTED);
                    return;
                }

                if (socketError != SocketError.Success)
                {
                    Disconnect(Messages.Errors.SOCKET_ERROR_RECEIVE_HEAD);
                    return;
                }

                if (received == 0)
                {
                    Disconnect(Messages.Errors.SOCKET_DISCONNECTED);
                    return;
                }

                lock (Drivers.Locks.NetworkLock)
                {
                    if (Cryptography != null)
                    {
                        _headBuffer = Cryptography.Decrypt(_headBuffer);
                    }
                }

                System.Buffer.BlockCopy(_headBuffer, 0, _finalBuffer, _headReceived, received);
                _headReceived += received;

                if (received < _headExpected)
                {
                    ReceiveHead(_headExpected - received, false);
                }
                else
                {
                    //int packetSize = (int)new NetworkPacket(_headBuffer).ReadUInt16();
                    int packetSize;
                    unsafe
                    {
                        fixed(byte *ptr = _headBuffer)
                        {
                            packetSize        = (int)(*(ushort *)(ptr + 0));
                            _packetIdentifier = (*(ushort *)(ptr + 2));
                        }
                    }

                    if (packetSize > NetworkInfo.BufferBodyMaxSize)
                    {
                        Disconnect(Messages.Errors.SOCKET_RECEIVE_TOO_BIG);
                        return;
                    }

                    if (Suffix != null)
                    {
                        packetSize += Suffix.Length;
                    }

                    Array.Resize(ref _finalBuffer, packetSize);
                    ReceiveBody(packetSize - _headReceived);
                }
            }
            catch (Exception e)
            {
                LastException = e;

                                #if DEBUG
                                #if TRACE
                ErrorLogger.Log(StackTracing.GetCurrentMethod().Name, e);
                                #else
                ErrorLogger.Log(Messages.Errors.FATAL_NETWORK_ERROR_TITLE, e);
                                #endif
                                #else
                Global.Message(e.ToString());
                                #endif

                Disconnect(Messages.Errors.FATAL_NETWORK_ERROR_TITLE);
            }
        }