コード例 #1
0
        protected override void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                sbyte target = GetSByte(0);
                if (target >= 0 && target <= Core.Constants.maxChannelsCount)
                {
                    if (Enum.IsDefined(typeof(ChannelType), target))
                    {
                        u.SetChannel((ChannelType)target);
                        u.Send(new Packets.ChangeChannel(u.Channel));

                        var result = Managers.ChannelManager.Instance.Get(u.Channel).Rooms.Select(n => n.Value)
                                     .Where(n => n.ID >= (uint)(8 * u.RoomListPage) && n.ID < (uint)(8 * (u.RoomListPage + 1))).OrderBy(n => n.ID);

                        u.Send(new Packets.RoomList(u.RoomListPage, new ArrayList(result.ToArray())));
                    }
                    else
                    {
                        u.Disconnect(); // Channel is not defined?
                    }
                }
                else
                {
                    u.Disconnect(); // Channel is out of range.
                }
            }
            else
            {
                u.Disconnect(); // Unauthorized user.
            }
        }
コード例 #2
0
ファイル: NewNickName.cs プロジェクト: R3DIANCE/WCPStandard
        protected override async void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                string newName = GetString(0);

                if (newName.Length > 3 && Utils.isAlphaNumeric(newName)) //legal nickname. TODO: add reserved/allowed shit
                {
                    bool dbNameIsTaken = await DBIsNameTaken(newName);

                    if (!dbNameIsTaken)
                    {
                        u.UpdateDisplayname(newName);
                        u.Send(new Packets.ServerList(u));
                        u.Disconnect();

                        // Update the DB
                        DBUpdateDisplayName(u.ID, newName);
                    }
                    else
                    {
                        u.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.NicknameTaken));
                    }
                }
                else
                {
                    u.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.IlligalNickname));
                }
            }
            else
            {
                u.Disconnect();
            }
        }
コード例 #3
0
        protected override void Process(Entities.User u)
        {
            uint   userId       = GetuInt(0);
            string username     = GetString(2);
            string displayname  = GetString(3);
            uint   sessionId    = GetuInt(4); // Login session Id
            byte   _accessLevel = GetByte(7);

            if (userId > 0 && username.Length > 2 && displayname.Length > 2 && sessionId > 0)
            {
                if (Managers.UserManager.Instance.Add(sessionId, u))
                {
                    Program.AuthServer.Send(new Packets.Internal.PlayerAuthorization(sessionId, userId, username, _accessLevel));
                }
                else
                {
                    u.Send(new Packets.Authorization(Packets.Authorization.ErrorCodes.NormalProcedure));
                    u.Disconnect();
                }
            }
            else
            {
                u.Send(new Packets.Authorization(Packets.Authorization.ErrorCodes.NormalProcedure));
                u.Disconnect();
            }
        }
コード例 #4
0
        public bool AddSpectator(Entities.User u)
        {
            int _maxSpectators = 5; //TODO, CONFIG

            if (Spectators.Count <= _maxSpectators)
            {
                for (byte i = 0; i < _maxSpectators; i++)
                {
                    if (!Spectators.ContainsKey(i))
                    {
                        //Add spectator
                        u.SetRoomSpectator(this, i);
                        Spectators.TryAdd(i, u);

                        ArrayList RegularPlayers    = new ArrayList();
                        ArrayList CurrentSpectators = new ArrayList();

                        foreach (Entities.Player Player in this.Players.Values)
                        {
                            RegularPlayers.Add(Player);
                        }

                        foreach (Entities.User Spectator in Spectators.Values)
                        {
                            CurrentSpectators.Add(Spectator);
                        }

                        //Room info for the spectator
                        u.Send(new Packets.RoomSpectate(u, this).BuildEncrypted());

                        //regular players in the room
                        u.Send(new Packets.RoomPlayers(RegularPlayers));

                        //spectators in the room
                        u.Send(new Packets.RoomSpectators(CurrentSpectators));

                        //update for room players
                        if (Players.Count > 0)
                        {
                            Send((new Packets.RoomSpectators(new ArrayList()
                            {
                                u
                            }).BuildEncrypted()));
                        }

                        return(true);
                    }
                }
            }

            return(false);
        }
コード例 #5
0
        protected override void Process(Entities.User u)
        {
            int versionID = GetInt(1);

            //    string macAddress = GetString(2);

            if (versionID == 3) //TODO: is this usable?
            {
                u.Send(new Packets.ServerTime());
            }
            else
            {
                u.Send(new Packets.ServerTime(Packets.ServerTime.ErrorCodes.DifferentClientVersion));
            }
        }
コード例 #6
0
        protected override void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                string nickname = GetString(0);
                if (nickname.Length >= 3 && Core.Constants.isAlphaNumeric(nickname))
                {
                    if (nickname.Length <= 16)
                    {
                        try {
                            MySqlDataReader reader = Databases.Auth.Select(
                                new string[] { "id" },
                                "users",
                                new Dictionary <string, object>()
                            {
                                { "displayname", nickname }
                            });

                            if (!reader.HasRows)   // TODO: is the nickname allowed?
                            {
                                reader.Close();
                                Databases.Auth.Query(string.Concat("UPDATE users SET `displayname` ='", nickname, "' WHERE id=", u.ID, ";"));
                                u.UpdateDisplayname(nickname);
                                u.Send(new Packets.ServerList(u));
                                u.Disconnect();
                            }
                            else
                            {
                                reader.Close();
                                u.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.NicknameTaken));
                            }
                        } catch { u.Disconnect(); }
                    }
                    else
                    {
                        u.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.NewNickname));
                    }
                }
                else
                {
                    u.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.NewNickname));
                }
            }
            else
            {
                u.Disconnect(); // Not authorized, cheating!
            }
        }
コード例 #7
0
 protected override void Process(Entities.User u)
 {
     if (u.Authorized)
     {
         if (u.Room != null)
         {
             if (u.Room.State == Enums.RoomState.Playing)
             {
                 u.Send(new Packets.Scoreboard(u.Room)); // Send scoreboard :)
             }
             else
             {
                 //u.Disconnect(); // Sending packets in lobby? Cheating! - IGNORE
             }
         }
         else
         {
             //u.Disconnect(); // Player is not in a room, cheating? - IGNORE
         }
     }
     else
     {
         u.Disconnect(); // Player not authorized - cheating?
     }
 }
コード例 #8
0
        protected override void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                if (u.Room == null)
                {
                    Objects.Channel channel = Managers.ChannelManager.Instance.Get(u.Channel);

                    uint   roomId       = GetuInt(1);
                    string roomPassword = GetString(2);

                    if (channel.Rooms.ContainsKey(roomId))
                    {
                        Entities.Room r = null;
                        if (channel.Rooms.TryGetValue(roomId, out r))
                        {
                            if (!r.AddSpectator(u))
                            {
                                u.Send(new Packets.RoomSpectate(Packets.RoomSpectate.ErrorCodes.MaxSpectators));
                            }
                        }
                    }
                }
            }
            else
            {
                u.Disconnect();
            }
        }
コード例 #9
0
        protected override void Process(Entities.User u)
        {
            if (!u.Authorized)
            {
                return;
            }

            u.Send(new Packets.LeaveServer());
            ServerLogger.Instance.Append(ServerLogger.AlertLevel.Information, String.Concat("Player ", u.Displayname, " logged OFF"));
        }
コード例 #10
0
        protected override void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                string _inputCode = GetString(0);
                //let´s check if any coupon matches the input
                if (Managers.CouponManager.Instance.isValidCouponCode(_inputCode))
                {
                    Objects.Coupon Coupon = Managers.CouponManager.Instance.getCoupon(_inputCode);

                    if (Coupon.Uses > 0)
                    {
                        u.Money += Coupon.DinarReward;

                        byte _usesLeft = Coupon.Uses;
                        _usesLeft--;

                        Managers.CouponManager.Instance.UpdateCouponUses(Coupon.Index, _usesLeft);

                        Databases.Game.AsyncQuery("UPDATE coupons SET uses=" + _usesLeft + "  WHERE id=" + Coupon.Index + "; UPDATE user_details SET money=" + u.Money + " WHERE id=" + u.ID + ";");
                        ServerLogger.Instance.Append(String.Concat("Player ", u.Displayname, " used coupon ", _inputCode));
                        u.Send(new Packets.Coupon(0, u.Money));
                    }
                    else //already registered :(
                    {
                        u.Send(new Packets.Coupon(-1, 0));
                    }
                }
                else
                {//throw here invalid code
                }
            }
            else
            {
                u.Disconnect();
            }
        }
コード例 #11
0
        protected override void Process(Entities.User u)
        {
            int    versionId = GetInt(1);
            string MACAdress = GetString(2);

            if (versionId == 3)                                                         //valid version... TODO: Useable?
            {
                if (MACAdress.Length == 12 && Core.Constants.isAlphaNumeric(MACAdress)) //Valid MAC address
                {
                    MACAdress = String.Concat("'", MACAdress, "'");
                    string aQuery = String.Concat("SELECT macaddress FROM macaddress_blacklist WHERE macaddress = ", MACAdress, ";");

                    MySqlCommand    cmd    = new MySqlCommand(aQuery, Databases.Game.connection);
                    MySqlDataReader Reader = cmd.ExecuteReader();

                    if (Reader.HasRows)                                                                    //banned HW
                    {
                        u.Send(new Packets.Authorization(Packets.Authorization.ErrorCodes.NotAccessible)); //should change client string to be "Mac banned"
                    }
                    else
                    {
                        u.Send(new Packets.ServerTime());
                    }

                    Reader.Close();
                }

                else
                {
                    u.Send(new Packets.Authorization(Packets.Authorization.ErrorCodes.NormalProcedure));
                }
            }
            else
            {
                u.Send(new Packets.ServerTime(Packets.ServerTime.ErrorCodes.DiffrentClientVersion));
            }
        }
コード例 #12
0
        protected override void Process(Entities.User u)
        {
            if (!u.Authorized)
            {
                return;
            }

            ArrayList List = new ArrayList();

            foreach (Entities.User user in Managers.UserManager.Instance.Sessions.Values)
            {
                List.Add(user);
            }

            u.UserListPage = GetByte(0);
            u.Send(new Packets.UserList(u.UserListPage, List));
        }
コード例 #13
0
        protected override void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                if (u.Room == null)
                {
                    sbyte direction   = (sbyte)(GetSByte(0) - GetSByte(2));
                    bool  waitingOnly = GetBool(1);

                    if (direction == -1)
                    {
                        if (u.RoomListPage > 0)
                        {
                            u.RoomListPage = (byte)(u.RoomListPage - 1);
                        }
                        else
                        {
                            u.RoomListPage = 0;
                        }
                    }
                    else if (direction == 1 && u.RoomListPage < byte.MaxValue)
                    {
                        u.RoomListPage += 1;
                    }

                    var result = Managers.ChannelManager.Instance.Get(u.Channel).Rooms.Select(n => n.Value);

                    if (waitingOnly)
                    {
                        result = result.Where(n => n.State == Enums.RoomState.Waiting).OrderByDescending(n => n.ID).Take(8).OrderBy(n => n.ID);
                    }
                    else
                    {
                        result = result.Where(n => n.ID >= (uint)(8 * u.RoomListPage) && n.ID < (uint)(8 * (u.RoomListPage + 1))).OrderBy(n => n.ID);
                    }

                    u.Send(new Packets.RoomList(u.RoomListPage, new ArrayList(result.ToArray())));
                }
            }
            else
            {
                u.Disconnect(); // Unauthorized user.
            }
        }
コード例 #14
0
        protected override void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                if (u.Room != null)
                {
                    Entities.Room r = u.Room;
                    r.Remove(u);

                    if (r != null && r.Players.Count > 0)
                    {
                        // SEND THE ROOM UPDATE TO THE LOBBY //
                        byte roomPage   = (byte)Math.Floor((decimal)(r.ID / 8));
                        var  targetList = Managers.ChannelManager.Instance.Get(r.Channel).Users.Select(n => n.Value).Where(n => n.RoomListPage == roomPage && n.Room == null);
                        if (targetList.Count() > 0)
                        {
                            byte[] outBuffer = new Packets.RoomUpdate(r, false).BuildEncrypted();
                            foreach (Entities.User usr in targetList)
                            {
                                usr.Send(outBuffer);
                            }
                        }
                    }
                    //this player needs an update of the userlist
                    ArrayList UserList = new ArrayList();
                    foreach (Entities.User User in Managers.UserManager.Instance.Sessions.Values)
                    {
                        UserList.Add(User);
                    }

                    u.UserListPage = 0;
                    u.Send(new Packets.UserList(0, UserList));
                }
            }
            else
            {
                u.Disconnect();
            }
        }
コード例 #15
0
        protected override void Process(Networking.ServerClient s)
        {
            ushort errorCode = GetUShort(0);

            if (Enum.IsDefined(typeof(PlayerAuthorizationErrorCodes), errorCode))
            {
                PlayerAuthorizationErrorCodes enumErrorCode = (PlayerAuthorizationErrorCodes)errorCode;
                uint targetId = GetuInt(1);

                switch (enumErrorCode)
                {
                // A new player logs in.
                case PlayerAuthorizationErrorCodes.Login: {
                    Entities.User u = Managers.UserManager.Instance.Get(targetId);
                    if (u != null)
                    {
                        uint   userId       = GetuInt(2);
                        string username     = GetString(3);
                        string displayname  = GetString(4);
                        byte   _accessLevel = GetByte(5);
                        u.OnAuthorize(userId, username, displayname, _accessLevel);
                    }
                    break;
                }

                // Update the information of a player.
                case PlayerAuthorizationErrorCodes.Update: {
                    break;
                }

                // A player logs out of the server.
                case PlayerAuthorizationErrorCodes.Logout: {
                    break;
                }

                case PlayerAuthorizationErrorCodes.InvalidSession: {
                    Entities.User u = Managers.UserManager.Instance.Get(targetId);
                    if (u != null)
                    {
                        if (!u.Authorized)
                        {
                            u.Send(new Packets.Authorization(Packets.Authorization.ErrorCodes.NormalProcedure));
                        }
                        u.Disconnect();
                    }
                    break;
                }

                case PlayerAuthorizationErrorCodes.IvalidMatch: {
                    Entities.User u = Managers.UserManager.Instance.Get(targetId);
                    if (u != null)
                    {
                        u.Send(new Packets.Authorization(Packets.Authorization.ErrorCodes.NormalProcedure));
                        u.Disconnect();
                    }
                    break;
                }

                case PlayerAuthorizationErrorCodes.SessionAlreadyActivated: {
                    Entities.User u = Managers.UserManager.Instance.Get(targetId);
                    if (u != null)
                    {
                        u.Send(new Packets.Authorization(Packets.Authorization.ErrorCodes.NormalProcedure));
                        u.Disconnect();
                    }
                    break;
                }

                default: {
                    // Unused.
                    break;
                }
                }
            }
            else
            {
                Log.Instance.WriteLine(string.Concat("Unknown PlayerAuthorization error: ", errorCode));
            }
        }
コード例 #16
0
ファイル: PlayerLogin.cs プロジェクト: R3DIANCE/WCPStandard
        protected async override void Process(Entities.User user)
        {
            List <object> userData = new List <object>();

            string inputUserName = GetString(2);
            string inputPassword = GetString(3);

            bool isSettingNewNickName = false;

            //valid UserName?
            if (inputUserName.Length >= 3 && Core.Utils.isAlphaNumeric(inputUserName))
            {
                //is password long enough?
                if (inputPassword.Length >= 3)
                {
                    using (Core.Databases.Database Db = new Core.Databases.Database(Config.AUTH_CONNECTION))
                    {
                        userData = await Db.AsyncGetRowFromTable(
                            new string[] { "ID", "username", "displayname", "password", "salt", "rights" },
                            "users", new Dictionary <string, object>() { { "username", inputUserName } });
                    }


                    //Does the username exists?
                    if (userData.Count > 0 && userData != null)
                    {
                        //The  user does exist:  retrieve data
                        uint   id             = Convert.ToUInt32(userData[0]);
                        string dbUserName     = inputUserName;
                        string displayname    = userData[2].ToString();
                        string dbPassword     = userData[3].ToString();
                        string dbPasswordSalt = userData[4].ToString();

                        GameConstants.Rights dbRights;

                        try { dbRights = (GameConstants.Rights)Convert.ToByte(userData[5]); }
                        catch
                        { Log.Error("User " + dbUserName + " rights could not be parsed. Blocking user.");
                          dbRights = GameConstants.Rights.Blocked; }

                        //We hash password typed  by the player and check it against  the one stored in the DB
                        string hashedPassword = Core.Utils.CreateSHAHash(String.Concat(inputPassword, dbPasswordSalt));

                        //CHECK!! Proceed
                        if (hashedPassword == dbPassword.ToLower())
                        {
                            var IsOnline = Managers.SessionManager.Instance.Sessions.Select(n => n.Value).Where(n => n.ID == id && n.IsActivated && !n.IsEnded).Count();

                            //Check to see if the same account is already logged in
                            //TODO: Improve this. What if a GameServer does not update this?
                            if (IsOnline == 0)
                            {
                                //TODO: Add ban time? Delegate it to game servers?
                                //TODO: Add gameserver blacklisting
                                if (dbRights == GameConstants.Rights.Blocked)
                                {
                                    user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.Banned));
                                }
                                else
                                {
                                    //Authenticate player
                                    user.OnAuthorize(id, dbUserName, displayname);

                                    //check if the player has a NickName
                                    if (user.DisplayName.Length > 0)
                                    {
                                        user.Send(new Packets.ServerList(user));
                                    }

                                    else
                                    {
                                        if (Config.ENABLENICKCHANGE)     //can they set their nickname ingame ???
                                        {
                                            isSettingNewNickName = true;
                                            user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.NewNickname));
                                        }
                                        else
                                        {
                                            user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.IlligalNickname));
                                        }
                                    }
                                }
                            }
                            else
                            {
                                user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.AlreadyLoggedIn));
                            }
                        }
                        else
                        {
                            user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.WrongPW));
                        }
                    }
                    else
                    {
                        user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.WrongUser));
                    }
                }
                else
                {
                    user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.EnterPasswordError));
                }
            }
            else
            {
                user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.EnterIDError));
            }


            //people who successfully logged on can be safely disconnected...
            //the client will show the server list and they will be redirected by the client.
            //keep the socket for those who are setting up nickname
            if (!isSettingNewNickName)
            {
                user.Disconnect();
            }
        }
コード例 #17
0
        protected override void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                if (u.Room != null)
                {
                    u.Disconnect();
                }

                bool isRoomValid = true;
                // READING OUT THE ROOM DATA //
                string name           = GetString(0);
                bool   hasPassword    = (GetByte(1) > 0);
                string password       = GetString(2);
                byte   playerCount    = GetByte(3);
                byte   mapId          = GetByte(4);        // Ignore this from the client, we will use it server side.
                byte   unknown1       = GetByte(5);        // Unknown?
                byte   unknown2       = GetByte(6);        // Unknown?
                byte   type           = GetByte(7);        // type?
                byte   levelLimit     = GetByte(8);        // level limit
                bool   friendlyFire   = (GetByte(9) > 0);  // premium only?
                bool   enableVoteKick = (GetByte(10) > 0); // vote kick

                // VALIDATE ROOM NAME //
                if (name.Length == 0 || name.Length > 25)   // Name Length
                {
                    if (name.Length != 27)
                    {
                        isRoomValid = false;
                    }
                }

                // VALIDATE ROOM PASSWORD //
                if (hasPassword && (password.Length == 0 || password == "NULL"))   // Password Length
                {
                    isRoomValid = false;
                }

                // VALIDATE MAXIMUM PLAYERS //
                byte highestIndex = 0;
                switch (u.Channel)
                {
                case Enums.ChannelType.CQC: {
                    highestIndex = 1;
                    break;
                }

                case Enums.ChannelType.Urban_Ops: {
                    highestIndex = 3;
                    break;
                }

                case Enums.ChannelType.Battle_Group: {
                    highestIndex = 4;
                    break;
                }

                default: {
                    highestIndex = 1;
                    break;
                }
                }

                if (playerCount > highestIndex)
                {
                    isRoomValid = false;
                }

                if (levelLimit < 0 || levelLimit > 5)
                {
                    isRoomValid = false;
                }

                if (!SuitableLevel(levelLimit, Core.LevelCalculator.GetLevelforExp(u.XP)))
                {
                    isRoomValid = false;
                }

                // VALIDATE PREMIUM SETTING //
                //        if (u.Premium == Enums.Premium.Free2Play && premiumOnly) {
                //           isRoomValid = false;
                //     }
                //DARKRAPTOR: PREMIUM ONLY REPLACED FOR FRIENDLYFIRE

                if (!u.Inventory.Itemlist.Contains("CC02") && !enableVoteKick)
                {
                    isRoomValid = false;
                }


                if (isRoomValid)
                {
                    // FETCH OPEN ID //
                    Objects.Channel channel    = Managers.ChannelManager.Instance.Get(u.Channel);
                    int             openRoomId = channel.GetOpenRoomID();

                    if (openRoomId >= 0)
                    {
                        Entities.Room room = new Entities.Room(u, (uint)openRoomId, name, hasPassword, password, playerCount, type, levelLimit, friendlyFire, enableVoteKick, false);
                        if (room != null)
                        {
                            // ROOM CREATED SUCCESSFULLY //
                            Managers.ChannelManager.Instance.Get(room.Channel).Add(room);

                            u.Send(new Packets.RoomCreation(room));

                            // SEND THE ROOM UPDATE TO THE LOBBY //
                            byte roomPage   = (byte)Math.Floor((decimal)(room.ID / 8));
                            var  targetList = Managers.ChannelManager.Instance.Get(room.Channel).Users.Select(n => n.Value).Where(n => n.RoomListPage == roomPage && n.Room == null);
                            if (targetList.Count() > 0)
                            {
                                byte[] outBuffer = new Packets.RoomUpdate(room, false).BuildEncrypted();
                                foreach (Entities.User usr in targetList)
                                {
                                    usr.Send(outBuffer);
                                }
                            }
                            ServerLogger.Instance.Append(ServerLogger.AlertLevel.Information, String.Concat("Player ", u.Displayname, " created a room"));
                        }
                        else
                        {
                            channel.ForceFreeSlot(openRoomId); // Force the room slot open again.
                            u.Send(new Packets.RoomCreation(Enums.RoomCreationErrors.GenericError));
                        }
                    }
                    else
                    {
                        u.Send(new Packets.RoomCreation(Enums.RoomCreationErrors.MaxiumRoomsExceeded));
                    }
                }
                else
                {
                    u.Send(new Packets.RoomCreation(Enums.RoomCreationErrors.GenericError));
                }
            }
            else
            {
                u.Disconnect();
            }
        }
コード例 #18
0
        protected override void Process(Entities.User u)
        {
            ushort actionType = GetUShort(0);

            if (actionType >= (ushort)Enums.ItemAction.BuyItem && actionType <= (ushort)Enums.ItemAction.UseItem)
            {
                if (actionType == (ushort)Enums.ItemAction.BuyItem)
                {
                    string itemCode = GetString(1).ToUpper();

                    if (itemCode.Length == 4)
                    {
                        if (Managers.ItemManager.Instance.Items.ContainsKey(itemCode))
                        {
                            ItemData item = Managers.ItemManager.Instance.Items[itemCode];
                            if (item != null)
                            {
                                uint dbId = GetuInt(2);
                                //if (item.dbId == dbId) {
                                byte length = GetByte(4);
                                if (length < 4)
                                {
                                    if (item.Shop.IsBuyable)
                                    {
                                        if (u.Inventory.Items.Count < Objects.Inventory.Inventory.MAX_ITEMS)
                                        {
                                            if (!item.Shop.RequiresPremium || (item.Shop.RequiresPremium && (byte)u.Premium > (byte)Enums.Premium.Free2Play))
                                            {
                                                if (item.Shop.RequiredLevel <= Core.LevelCalculator.GetLevelforExp(u.XP))
                                                {
                                                    int price = item.Shop.Cost[length];
                                                    if (price >= 0)
                                                    {
                                                        int moneyCalc = (int)u.Money - price;
                                                        if (moneyCalc >= 0)
                                                        {
                                                            var invItem = (Objects.Inventory.Item)null;
                                                            try {
                                                                invItem = u.Inventory.Items.Select(n => n.Value).Where(n => n.ItemCode == item.Code).First();
                                                            } catch { invItem = null; }

                                                            uint utcTime    = (uint)DateTime.Now.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
                                                            uint itemLength = (uint)(86400 * days[length]);
                                                            u.Money = (uint)moneyCalc;

                                                            if (invItem != null)   // Has item in inventory.

                                                            //check for a possible retail
                                                            {
                                                                if (u.Inventory.Retails.Contains(item.Code.ToUpper()))
                                                                {
                                                                    u.Send(new Packets.Itemshop(Packets.Itemshop.ErrorCodes.CannotBeBougth));
                                                                }
                                                                else
                                                                {
                                                                    // Extend & insert into db :)
                                                                    Databases.Game.AsyncQuery(string.Concat("INSERT INTO user_inventory (`id`, `owner`, `code`, `startdate`, `length`, `price`, `expired`, `deleted`) VALUES (NULL, '", u.ID, "', '", item.Code.ToUpper(), "', '", utcTime, "', '", itemLength, "', '", price, "', '0', '0'); UPDATE user_details SET money='", u.Money, "' WHERE id = ", u.ID, ";"));
                                                                    invItem.ExpireDate = invItem.ExpireDate.AddSeconds(itemLength);
                                                                    u.Inventory.Rebuild();
                                                                    u.Send(new Packets.Itemshop(u));
                                                                }
                                                            }
                                                            else     // No item in invetory
                                                            // Insert & fetch id
                                                            {
                                                                uint itemdbId = 0;
                                                                MySql.Data.MySqlClient.MySqlCommand cmd;

                                                                try {
                                                                    cmd = new MySql.Data.MySqlClient.MySqlCommand(string.Concat("INSERT INTO user_inventory (`id`, `owner`, `code`, `startdate`, `length`, `price`, `expired`, `deleted`) VALUES (NULL, '", u.ID, "', '", item.Code.ToUpper(), "', '", utcTime, "', '", itemLength, "', '", price, "', '0', '0');"), Databases.Game.connection);
                                                                    cmd.ExecuteNonQueryAsync();
                                                                    itemdbId = (uint)cmd.LastInsertedId;
                                                                } catch { itemdbId = 0; }

                                                                if (itemdbId > 0)
                                                                {
                                                                    Databases.Game.AsyncQuery(string.Concat("UPDATE user_details SET money='", u.Money, "' WHERE id = ", u.ID, ";"));
                                                                    u.Inventory.Add(new Objects.Inventory.Item(-1, itemdbId, item.Code, (utcTime + itemLength)));
                                                                    u.Inventory.Rebuild();
                                                                    u.Send(new Packets.Itemshop(u));
                                                                }
                                                                else
                                                                {
                                                                    u.Send(new Packets.Itemshop(Packets.Itemshop.ErrorCodes.CannotBeBougth));
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            u.Send(new Packets.Itemshop(Packets.Itemshop.ErrorCodes.NotEnoughDinar));
                                                        }
                                                    }
                                                    else
                                                    {
                                                        u.Disconnect(); // Item can't be bought for this period. - Cheating?
                                                    }
                                                }
                                                else
                                                {
                                                    u.Send(new Packets.Itemshop(Packets.Itemshop.ErrorCodes.LevelRequirement));
                                                }
                                            }
                                            else
                                            {
                                                u.Send(new Packets.Itemshop(Packets.Itemshop.ErrorCodes.PremiumOnly));
                                            }
                                        }
                                        else
                                        {
                                            u.Send(new Packets.Itemshop(Packets.Itemshop.ErrorCodes.InventoryFull));     // Inventory is full.
                                        }
                                    }
                                    else
                                    {
                                        u.Send(new Packets.Itemshop(Packets.Itemshop.ErrorCodes.CannotBeBougth));     // Buying an item that isn't for sale? - Cheating?
                                    }
                                }
                                else
                                {
                                    u.Disconnect();     // Cheating?
                                }
                            }
                            else
                            {
                                u.Disconnect();     // Invalid id for the item - Cheating?
                            }
                        }
                        else
                        {
                            u.Disconnect();     // Server error.
                        }
                    }
                    else
                    {
                        u.Disconnect();     // Code doesn't exist - Cheating?
                    }
                }
                else
                {
                    u.Disconnect();     // Wrong Code - Cheating?
                }
            }
            else if (actionType == (ushort)Enums.ItemAction.UseItem)
            {
                u.Send(new Packets.Itemshop(Packets.Itemshop.ErrorCodes.InvalidItem));
            }
            else
            {
                u.Send(new Packets.Itemshop(Packets.Itemshop.ErrorCodes.InvalidItem));
            }

            /*} else {
             *  u.Disconnect(); // Invalid Action type - Cheating?
             * }*/
        }
コード例 #19
0
        public bool Add(Entities.User u)
        {
            if (Players.Count < MaximumPlayers)
            {
                lock (_playerLock) {
                    Team targetTeam     = Team.Derbaran;
                    byte startScanIndex = 0;
                    byte endScanIndex   = (byte)(MaximumPlayers / 2);

                    var debTeam = Players.Select(n => n.Value).Where(n => n.Team == Team.Derbaran).Count();
                    var niuTeam = Players.Select(n => n.Value).Where(n => n.Team == Team.NIU).Count();

                    if (debTeam > niuTeam)
                    {
                        targetTeam     = Team.NIU;
                        startScanIndex = (byte)(MaximumPlayers / 2);
                        endScanIndex   = MaximumPlayers;
                    }

                    for (byte i = startScanIndex; i < endScanIndex; i++)
                    {
                        if (!Players.ContainsKey(i))
                        {
                            Player plr = new Player(i, u, targetTeam);

                            // Send Room //
                            if (Players.Count > 0)
                            {
                                Send((new Packets.RoomPlayers(new ArrayList()
                                {
                                    plr
                                }).BuildEncrypted()));
                            }
                            else
                            {
                                Master = i;
                            }

                            // Add Player
                            Players.TryAdd(i, plr);
                            u.SetRoom(this, i);

                            // Send Join Packet //
                            u.Send(new Packets.RoomJoin(i, this));
                            u.Send(new Packets.RoomPlayers(new ArrayList(Players.Select(n => n.Value).Where(n => n.Id != i).ToArray())));

                            // Send to all spectators: TODO //

                            // SEND THE ROOM UPDATE TO THE LOBBY //
                            byte roomPage   = (byte)Math.Floor((decimal)(this.ID / 8));
                            var  targetList = Managers.ChannelManager.Instance.Get(this.Channel).Users.Select(n => n.Value).Where(n => n.RoomListPage == roomPage && n.Room == null);
                            if (targetList.Count() > 0)
                            {
                                byte[] outBuffer = new Packets.RoomUpdate(this, true).BuildEncrypted();
                                foreach (Entities.User usr in targetList)
                                {
                                    usr.Send(outBuffer);
                                }
                            }

                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
コード例 #20
0
        public void Remove(Entities.User u)
        {
            if (u.Room != null)
            {
                if (u.Room.ID == this.ID)
                {
                    lock (this.RoomLock) {
                        Player p;
                        byte   oldSlot = 0;

                        lock (_playerLock) {
                            if (Players.ContainsKey(u.RoomSlot))
                            {
                                Players.TryRemove(u.RoomSlot, out p);

                                if (p != null)
                                {
                                    oldSlot = u.RoomSlot;
                                    p.User.SetRoom(null, 0);
                                }
                                else
                                {
                                    u.SetRoom(null, 0);
                                }

                                if (Players.Count > 0)
                                {
                                    // Asign new master //
                                    if (u.RoomSlot == Master)
                                    {
                                        // Remove the suppermaster buff :)
                                        this.Supermaster = false;

                                        // Calculate the priority level.
                                        int[] priority = new int[MaximumPlayers];
                                        for (byte i = 0; i < MaximumPlayers; i++)
                                        {
                                            if (Players.ContainsKey(i))
                                            {
                                                if (Players[i] != null)
                                                {
                                                    priority[i] = 1 + (int)Players[i].User.Premium;
                                                }
                                                else
                                                {
                                                    priority[i] = 0; // no priority.
                                                }
                                            }
                                            else
                                            {
                                                priority[i] = 0; // no priority.
                                            }
                                        }

                                        // Find the new master.
                                        sbyte newMaster   = -1;
                                        int   masterPrior = 0;
                                        for (byte j = 0; j < MaximumPlayers; j++)
                                        {
                                            if (priority[j] > masterPrior) // A player with higher piority has been found.
                                            {
                                                newMaster   = (sbyte)j;    // set the master slot
                                                masterPrior = priority[j]; // store the piority.
                                            }
                                        }

                                        // We have found a new master!
                                        if (newMaster >= 0)
                                        {
                                            Master = (byte)newMaster;
                                        }
                                        else
                                        {
                                            Destory();
                                        }
                                    }
                                }
                                else
                                {
                                    Destory();
                                }

                                byte[] pBuffer = new Packets.RoomLeave(u, oldSlot, this).BuildEncrypted();
                                if (Players.Count > 0)
                                {
                                    Send(pBuffer);
                                }

                                u.Send(pBuffer);
                            }
                        }
                    }
                }
            }
        }
コード例 #21
0
        public override void Handle(ServerClient sender, InPacket packetReader)
        {
            ushort errorCode = packetReader.ReadUshort();

            if (Enum.IsDefined(typeof(PlayerAuthorizationErrorCodes), errorCode))
            {
                PlayerAuthorizationErrorCodes enumErrorCode = (PlayerAuthorizationErrorCodes)errorCode;
                uint targetId = packetReader.ReadUint();

                switch (enumErrorCode)
                {
                // A new player logs in.
                case PlayerAuthorizationErrorCodes.Login:
                {
                    Entities.User u = Managers.UserManager.Instance.Get(targetId);
                    if (u != null)
                    {
                        uint   userId      = packetReader.ReadUint();
                        string username    = packetReader.ReadString();
                        string displayname = packetReader.ReadString();
                        u.OnAuthorize(userId, username, displayname);
                    }
                    break;
                }

                // Update the information of a player.
                case PlayerAuthorizationErrorCodes.Update:
                {
                    break;
                }

                // A player logs out of the server.
                case PlayerAuthorizationErrorCodes.Logout:
                {
                    break;
                }

                case PlayerAuthorizationErrorCodes.InvalidSession:
                {
                    Entities.User u = Managers.UserManager.Instance.Get(targetId);
                    if (u != null)
                    {
                        if (!u.Authenticated)
                        {
                            u.Send(new Packets.Authorization(Packets.Authorization.ErrorCodes.NormalProcedure));
                        }
                        u.Disconnect();
                    }
                    break;
                }

                case PlayerAuthorizationErrorCodes.IvalidMatch:
                {
                    Entities.User u = Managers.UserManager.Instance.Get(targetId);
                    if (u != null)
                    {
                        u.Send(new Packets.Authorization(Packets.Authorization.ErrorCodes.NormalProcedure));
                        u.Disconnect();
                    }
                    break;
                }

                case PlayerAuthorizationErrorCodes.SessionAlreadyActivated:
                {
                    Entities.User u = Managers.UserManager.Instance.Get(targetId);
                    if (u != null)
                    {
                        u.Send(new Packets.Authorization(Packets.Authorization.ErrorCodes.NormalProcedure));
                        u.Disconnect();
                    }
                    break;
                }

                default:
                {
                    // Unused.
                    break;
                }
                }
            }
            else
            {
                Log.Instance.WriteLine(string.Concat("Unknown PlayerAuthorization error: ", errorCode));
            }
        }
コード例 #22
0
 public void SayToPlayer(string _message, Entities.User User)
 {
     User.Send(GetWhisperPacket(User, MessageTranslator(_message)));
 }
コード例 #23
0
        protected override void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                if (u.Room != null && u.Room.State == Enums.RoomState.Waiting)
                {
                    Entities.Room Room = u.Room;

                    if (Room.Players.Count < Room.MaximumPlayers)
                    {
                        List <Entities.User> ValidUsers = new List <Entities.User>();

                        foreach (Entities.User User in Managers.UserManager.Instance.Sessions.Values)
                        {
                            if (User.Room == null && User.Channel == u.Channel)
                            {
                                ValidUsers.Add(User);
                            }
                        }
                        string _target  = GetString(0);
                        string _message = GetString(1);


                        if (_target == "NULL") //send invitation to random user
                        {
                            Random Random = new Random();

                            if (ValidUsers.Count < 1)
                            {
                                u.Send(new Packets.RoomInvite(Enums.RoomInviteErrors.GenericError));
                            }
                            else
                            {
                                Entities.User Target = ValidUsers[Random.Next(0, ValidUsers.Count)];
                                u.Send(new Packets.RoomInvite(Enums.RoomInviteErrors.Invited));
                                Target.Send(new Packets.RoomInvite(u, _message));
                            }
                        }
                        else
                        {
                            try
                            {
                                foreach (Entities.User pTarget in Managers.UserManager.Instance.Sessions.Values)
                                {
                                    if (pTarget.Displayname == _target)
                                    {
                                        if (pTarget.Room != null)
                                        {
                                            u.Send(new Packets.RoomInvite(Enums.RoomInviteErrors.InRoom));
                                        }

                                        if (pTarget.Room == null && pTarget.Channel == u.Channel)
                                        {
                                            pTarget.Send(new Packets.RoomInvite(u, _message));
                                        }
                                    }
                                }
                            }
                            catch
                            {
                                u.Send(new Packets.RoomInvite(Enums.RoomInviteErrors.GenericError));
                            }
                        }
                    }
                    else
                    {
                        Cristina.Core.Cristina.Chat.SayToPlayer("You cannot invite a player because the room is full", u);
                    }
                }
                else
                {
                    u.Disconnect();
                }
            }
            else
            {
                u.Disconnect();
            }
        }
コード例 #24
0
        protected override void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                byte type = GetByte(0);

                if (System.Enum.IsDefined(typeof(ChatType), type))
                {
                    Enums.ChatType chatType     = (ChatType)type;
                    uint           nowTimeStamp = (uint)DateTime.Now.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
                    string         message      = GetString(3);
                    string         realMessage  = message.Split(new string[] { ">>" + Convert.ToChar(0x1D).ToString() }, StringSplitOptions.None)[1].Replace(Convert.ToChar(0x1D), Convert.ToChar(0x20));

                    if (IsCommand(realMessage))
                    {
                        //removes /cris header
                        realMessage = realMessage.Remove(0, 6);

                        //get the command and the Arguments
                        string[] FullCommand = realMessage.Split(' ');

                        //TODO: PARSE FOR TARGET
                        Objects.Command Command = Managers.CommandManager.Instance.GetCommand(FullCommand[0]);
                        if (Command != null)
                        {
                            //get the arguments...
                            string[] Arguments = new string[FullCommand.Length - 1];
                            Array.Copy(FullCommand, 1, Arguments, 0, (FullCommand.Length - 1));

                            if (Arguments.Length < 32)
                            {
                                Command.SetArguments(Arguments);
                                Command.Process(u);
                            }
                        }
                        else
                        {
                            //      string  _notFound = Cristina.Core.Cristina.Localization.GetLocMessageFrom("UNKNOWN_COMMAND");
                            Cristina.Core.Cristina.Chat.SayToPlayer("El comando no existe", u);
                        }
                    }
                    else
                    {
                        string targetName = GetString(2);
                        int    targetId   = GetInt(1);
                        if (realMessage.Length <= 60)
                        {
                            realMessage = realMessage.Trim();
                            switch (chatType)
                            {
                            case ChatType.Lobby_ToChannel:
                            {
                                if (u.Room == null)
                                {
                                    Databases.Game.AsyncInsert("chat_public_lobby", new System.Collections.Generic.Dictionary <string, object>()
                                        {
                                            { "server", Config.SERVER_ID }, { "channel_id", (byte)u.Channel }, { "sender_id", u.ID }, { "target_all", 0 }, { "message", realMessage }, { "timestamp", nowTimeStamp }
                                        });
                                    Core.Networking.OutPacket p = new Packets.Chat(u, Enums.ChatType.Lobby_ToChannel, message, targetId, targetName);
                                    Managers.ChannelManager.Instance.SendLobby(u.Channel, p.BuildEncrypted());
                                }
                                else
                                {
                                    u.Disconnect();         // Sending lobby messages when in a room?
                                }
                                break;
                            }

                            case ChatType.Lobby_ToAll:
                            {
                                if (u.Room == null)
                                {
                                    Databases.Game.AsyncInsert("chat_public_lobby", new System.Collections.Generic.Dictionary <string, object>()
                                        {
                                            { "server", Config.SERVER_ID }, { "channel_id", (byte)u.Channel }, { "sender_id", u.ID }, { "target_all", 1 }, { "message", realMessage }, { "timestamp", nowTimeStamp }
                                        });
                                    Core.Networking.OutPacket p = new Packets.Chat(u, chatType, message, targetId, targetName);
                                    Managers.ChannelManager.Instance.SendAllLobbies(p.BuildEncrypted());
                                }
                                else
                                {
                                    u.Disconnect();         // Sending lobby messages when in a room?
                                }
                                break;
                            }

                            case ChatType.Room_ToAll:
                            {
                                if (u.Room != null)
                                {
                                    if (u.Room.State == RoomState.Waiting && u.RoomSlot == u.Room.Master)
                                    {
                                        if (u.Room.Supermaster)
                                        {
                                            targetId = 998;
                                        }
                                    }
                                    Databases.Game.AsyncInsert("chat_public_room", new System.Collections.Generic.Dictionary <string, object>()
                                        {
                                            { "server", Config.SERVER_ID }, { "channel_id", (byte)u.Channel }, { "sender_id", u.ID }, { "room_id", u.Room.ID }, { "team_side", (byte)u.Room.Players[u.RoomSlot].Team }, { "target_all", 1 }, { "message", realMessage }, { "timestamp", nowTimeStamp }
                                        });
                                    Core.Networking.OutPacket p = new Packets.Chat(u, chatType, message, targetId, targetName);
                                    u.Room.Send(p.BuildEncrypted());
                                }
                                else
                                {
                                    u.Disconnect();
                                }
                                break;
                            }

                            case ChatType.Room_ToTeam:
                            {
                                if (u.Room != null)
                                {
                                    if (u.Room.Mode != Mode.Free_For_All && u.Room.State == RoomState.Playing)
                                    {
                                        Databases.Game.AsyncInsert("chat_public_room", new System.Collections.Generic.Dictionary <string, object>()
                                            {
                                                { "server", Config.SERVER_ID }, { "channel_id", (byte)u.Channel }, { "sender_id", u.ID }, { "room_id", u.Room.ID }, { "team_side", (byte)u.Room.Players[u.RoomSlot].Team }, { "target_all", 0 }, { "message", realMessage }, { "timestamp", nowTimeStamp }
                                            });
                                        Core.Networking.OutPacket p = new Packets.Chat(u, chatType, message, targetId, targetName);
                                        byte[] buffer = p.BuildEncrypted();
                                        u.Room.Players.Values.Where(n => n.Team == u.Room.Players[u.RoomSlot].Team).ToList().ForEach(n => n.Send(buffer));
                                    }
                                    else
                                    {
                                        u.Disconnect();         // NO team CHAT IN FFA or in the lobby.
                                    }
                                }
                                break;
                            }

                            case ChatType.Clan:
                            {
                                if (u.ClanId != -1)
                                {
                                    Databases.Game.AsyncInsert("chat_private_clan", new System.Collections.Generic.Dictionary <string, object>()
                                        {
                                            { "server", Config.SERVER_ID }, { "clan_id", (byte)u.ClanId }, { "sender_id", u.ID }, { "message", realMessage }, { "timestamp", nowTimeStamp }
                                        });

                                    Core.Networking.OutPacket p = new Packets.Chat(u, chatType, message, targetId, targetName);
                                    foreach (Entities.User User in Managers.UserManager.Instance.Sessions.Values)
                                    {
                                        User.Send(p.BuildEncrypted());
                                    }
                                }
                                break;
                            }

                            case ChatType.Whisper:
                            {
                                Entities.User Target = Managers.UserManager.Instance.GetUser(targetName);

                                //fixes the lack of space between nick and "message sent" or "doesn´t exist" error code
                                targetName = targetName + Convert.ToChar(0x1D);
                                if (Target != null)
                                {
                                    u.Send(new Packets.Chat(u, chatType, message, targetId, targetName));         //in this case targetId equals -1, that is "message sent"
                                    Target.Send(new Packets.Chat(u, chatType, message, (int)Target.SessionID, Target.Displayname).BuildEncrypted());
                                }
                                else
                                {
                                    u.Send(new Packets.Chat(95040, targetName).BuildEncrypted());
                                }
                                break;
                            }

                            default:
                            {
                                break;
                            }
                            }
                        }
                        else
                        {
                            u.Disconnect(); // Message is to long?
                        }
                    }
                }
            }
            else
            {
                u.Disconnect();
            }
        }
コード例 #25
0
        public void Remove(Entities.User u)
        {
            if (u.Room != null)
            {
                if (u.Room.ID == this.ID)
                {
                    lock (this.RoomLock) {
                        Player p;
                        byte   oldSlot = 0;

                        lock (_playerLock) {
                            if (Players.ContainsKey(u.RoomSlot))
                            {
                                Players.TryRemove(u.RoomSlot, out p);

                                if (p != null)
                                {
                                    oldSlot = u.RoomSlot;
                                    p.User.SetRoom(null, 0);
                                }
                                else
                                {
                                    u.SetRoom(null, 0);
                                }

                                if (Players.Count > 0)
                                {
                                    // Asign new master //
                                    if (oldSlot == Master)
                                    {
                                        // Remove the suppermaster buff :)
                                        this.Supermaster = false;

                                        // Calculate the priority level.
                                        int[] priority = new int[MaximumPlayers];
                                        for (byte i = 0; i < MaximumPlayers; i++)
                                        {
                                            if (Players.ContainsKey(i))
                                            {
                                                if (Players[i] != null)
                                                {
                                                    priority[i] = 1 + (int)Players[i].User.Premium;
                                                }
                                                else
                                                {
                                                    priority[i] = 0; // no priority.
                                                }
                                            }
                                            else
                                            {
                                                priority[i] = 0; // no priority.
                                            }
                                        }

                                        // Find the new master.
                                        sbyte newMaster   = -1;
                                        int   masterPrior = 0;
                                        for (byte j = 0; j < MaximumPlayers; j++)
                                        {
                                            if (priority[j] > masterPrior) // A player with higher piority has been found.
                                            {
                                                newMaster   = (sbyte)j;    // set the master slot
                                                masterPrior = priority[j]; // store the piority.
                                            }
                                        }

                                        // We have found a new master!
                                        if (newMaster >= 0)
                                        {
                                            Master = (byte)newMaster;
                                            Players[Master].Ready = true;
                                        }
                                        else
                                        {
                                            Destroy();
                                        }
                                    }
                                }
                                else
                                {
                                    Destroy();
                                }

                                byte[] pBuffer = new Packets.RoomLeave(u, oldSlot, this).BuildEncrypted();
                                if (Players.Count > 0)
                                {
                                    Send(pBuffer);
                                }

                                u.Send(pBuffer);

                                //tell the players
                                if (State == RoomState.Playing)
                                {
                                    //     string _playerLeft = Cristina.Core.Cristina.Localization.GetLocMessageFrom("PLAYER_LEFT");

                                    //   if (_playerLeft.Contains("%/nickname/%"))
                                    //    _playerLeft = _playerLeft.Replace("/nickname/%", u.Displayname);

                                    Cristina.Core.Cristina.Chat.SaytoRoom(u.Displayname + " ha salido de la sala", this);
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #26
0
        protected override void Process(Entities.User user)
        {
            string inputUserName = GetString(2);
            string inputPassword = GetString(3);

            bool forceDisconnect = true;

            //valid UserName?
            if (inputUserName.Length >= 3 && Core.Constants.isAlphaNumeric(inputUserName))
            {
                //is password long enough?
                if (inputPassword.Length >= 3)
                {
                    MySqlDataReader reader = Databases.Auth.Select(
                        new string[] { "id", "username", "status", "displayname", "password", "passwordsalt" },
                        "users",
                        new Dictionary <string, object>()
                    {
                        { "username", inputUserName }
                    });

                    //Does the username exists?
                    if (reader.HasRows && reader.Read())
                    {
                        //The  user does exist:  retrieve data
                        uint   id             = reader.GetUInt32(0);
                        string dbUserName     = inputUserName;
                        byte   status         = reader.GetByte(2);        //0 = global network account ban
                        string displayname    = reader.GetString(3);
                        string dbPassword     = reader.GetString(4);
                        string dbPasswordSalt = reader.GetString(5);


                        //We hash password typed  by the player and check it against  the one stored in the DB
                        string hashedPassword = Core.Constants.GenerateSHAHash(String.Concat(inputPassword, dbPasswordSalt));

                        //CHECK!! Proceed
                        if (hashedPassword == dbPassword.ToLower())
                        {
                            var IsOnline = Managers.SessionManager.Instance.Sessions.Select(n => n.Value).Where(n => n.ID == id && n.IsActivated && !n.IsEnded).Count();

                            //Check to see if the same account is already logged in
                            //TODO: Improve this. What if a GameServer does not update this?
                            if (IsOnline == 0)
                            {
                                if (status > 0)
                                {
                                    user.OnAuthorize(id, dbUserName, displayname, status);
                                    user.Send(new Packets.ServerList(user));
                                }
                                else
                                {
                                    user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.Banned));
                                }
                            }
                            else
                            {
                                user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.AlreadyLoggedIn));
                            }
                        }
                        else
                        {
                            user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.WrongPW));
                        }
                    }
                    else
                    {
                        user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.WrongUser));
                    }


                    if (!reader.IsClosed)
                    {
                        reader.Close();
                    }
                }
                else
                {
                    user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.EnterPasswordError));
                }
            }
            else
            {
                user.Send(new Packets.ServerList(Packets.ServerList.ErrorCodes.EnterIDError));
            }


            if (forceDisconnect)
            {
                user.Disconnect();
            }
        }
コード例 #27
0
        protected override void Process(Entities.User u)
        {
            if (u.Authorized)
            {
                if (u.Room == null)
                {
                    Objects.Channel channel = Managers.ChannelManager.Instance.Get(u.Channel);

                    uint   roomId       = GetuInt(0);
                    string roomPassword = GetString(1);

                    if (channel.Rooms.ContainsKey(roomId))
                    {
                        Entities.Room r = null;
                        if (channel.Rooms.TryGetValue(roomId, out r))
                        {
                            bool validPassword = true;
                            bool validLevel    = true;

                            if (r.HasPassword && r.Password != roomPassword)
                            {
                                validPassword = false;
                            }

                            if (!SuitableLevel(r.LevelLimit, Core.LevelCalculator.GetLevelforExp(u.XP)))
                            {
                                validLevel = false;
                            }

                            if (validPassword)
                            {
                                if (validLevel)
                                {
                                    if (!r.Add(u))
                                    {
                                        if (r.UserLimit)
                                        {
                                            u.Send(new Packets.RoomJoin(Packets.RoomJoin.ErrorCodes.UsersExceeded));
                                        }
                                        else
                                        {
                                            u.Send(new Packets.RoomJoin(Packets.RoomJoin.ErrorCodes.RoomIsFull));
                                        }
                                    }
                                }
                                else
                                {
                                    u.Send(new Packets.RoomJoin(Packets.RoomJoin.ErrorCodes.BadLevel));
                                }
                            }
                            else
                            {
                                u.Send(new Packets.RoomJoin(Packets.RoomJoin.ErrorCodes.InvalidPassword));
                            }
                        }
                        else
                        {
                            u.Send(new Packets.RoomJoin(Packets.RoomJoin.ErrorCodes.GenericError));
                        }
                    }
                    else
                    {
                        u.Send(new Packets.RoomJoin(Packets.RoomJoin.ErrorCodes.GenericError));
                    }
                }
            }
            else
            {
                u.Disconnect();
            }
        }
コード例 #28
0
        protected override void Process(Entities.User u) {
            if (u.Authorized) {
                bool equipItem = !GetBool(0);
                byte bTargetClass = GetByte(1);
                if (bTargetClass < Objects.Inventory.Equipment.MAX_CLASSES)
                {
                    Classes targetClass = (Classes)bTargetClass;
                    string weaponCode = GetString(4).ToUpper();
                    byte targetSlot = 0;
                    if (weaponCode.Length == 4)
                    {
                        if (targetSlot < 8)
                        {
                            if (equipItem)
                            {
                                targetSlot = GetByte(5);
                                if (targetSlot < Objects.Inventory.Equipment.MAX_SLOTS)
                                {
                                    if (Managers.ItemManager.Instance.Items.ContainsKey(weaponCode))
                                    {
                                        Objects.Items.ItemData item = null;
                                        if (Managers.ItemManager.Instance.Items.TryGetValue(weaponCode, out item))
                                        {
                                            if (item.IsWeapon)
                                            {
                                                Objects.Items.Weapon weapon = (Objects.Items.Weapon)item;
                                                if (weapon != null)
                                                {
                                                    if ((weapon.Active && weapon.CanEquip[(byte)targetClass, targetSlot]) || u.AccessLevel > 3)
                                                    {
                                                        Objects.Inventory.Item equipmentItem = u.Inventory.Get(weapon.Code);
                                                        if (equipmentItem != null && equipmentItem.Slot >= 0)
                                                        { // Does the user have the item.
                                                            Objects.Inventory.Item equipedItem = u.Inventory.Equipment.Get(targetClass, targetSlot);
                                                            if (!u.Inventory.Retails.Contains(weapon.Code.ToUpper()) && (equipedItem == null || equipmentItem.Slot != equipedItem.Slot))
                                                            {
                                                                // string Type = getBlock(2);
                                                                if (equipmentItem.Equiped[(byte)targetClass] >= 0)
                                                                    u.Inventory.Equipment.Remove(targetClass, (byte)equipmentItem.Equiped[(byte)targetClass]);

                                                                u.Inventory.Equipment.Add(targetClass, targetSlot, equipmentItem);
                                                                u.Inventory.Equipment.Build();
                                                                u.Inventory.Equipment.BuildInternal();
                                                                u.Send(new Packets.Equipment(targetClass, u.Inventory.Equipment.ListsInternal[(byte)targetClass]));
                                                            }
                                                            else
                                                            {
                                                                u.Send(new Packets.Equipment(Packets.Equipment.ErrorCode.AlreadyEquipped)); // Already equiped.
                                                            }
                                                        }
                                                        else
                                                        {
                                                            bool isFound = false; // ATTAMPT TO CHECK IF THE ITEM IS A DEFAULT ITEM.
                                                            Objects.Inventory.Item equipedItem = u.Inventory.Equipment.Get(targetClass, targetSlot);
                                                            for (byte j = 0; j < Objects.Inventory.Inventory.DEFAULT_ITEMS.Length; j++)
                                                            {
                                                                if (weaponCode == Objects.Inventory.Inventory.DEFAULT_ITEMS[j])
                                                                {
                                                                    isFound = true;
                                                                    if (equipedItem == null || equipedItem.Slot != -1)
                                                                    {
                                                                        u.Inventory.Equipment.Add(targetClass, targetSlot, new Objects.Inventory.Item(-1, 0, Objects.Inventory.Inventory.DEFAULT_ITEMS[j], 0));
                                                                        u.Inventory.Equipment.Build();
                                                                        u.Inventory.Equipment.BuildInternal();
                                                                        u.Send(new Packets.Equipment(targetClass, u.Inventory.Equipment.ListsInternal[(byte)targetClass]));
                                                                    }
                                                                    else
                                                                    {
                                                                        u.Send(new Packets.Equipment(Packets.Equipment.ErrorCode.AlreadyEquipped)); // Already equiped.
                                                                    }
                                                                    break;
                                                                }
                                                            }
                                                            if (!isFound)
                                                            {
                                                                u.Disconnect(); // potentiality scripting or packet changing.. TODO: LOG
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        u.Disconnect(); // potentiality scripting or packet changing.. TODO: LOG
                                                    }
                                                }
                                                else
                                                {
                                                    u.Disconnect(); // Server error?
                                                }
                                            }
                                        }
                                        else
                                        {
                                            u.Disconnect(); // Server error?
                                        }
                                    }
                                    else
                                    {
                                        u.Disconnect(); // potentiality scripting or packet changing.. TODO: LOG
                                    }

                                }
                                else
                                {
                                    u.Disconnect(); // potentiality scripting or packet changing.. TODO: LOG
                                }
                            }
                            else
                            {
                                targetSlot = GetByte(3);
                                Objects.Inventory.Item equipedItem = u.Inventory.Equipment.Get(targetClass, targetSlot);
                                if (equipedItem != null)
                                {
                                    u.Inventory.Equipment.Remove(targetClass, targetSlot);
                                    u.Inventory.Equipment.Build();
                                    u.Send(new Packets.Equipment(targetClass, u.Inventory.Equipment.Lists[(byte)targetClass]));
                                }
                            }
                        }
                    }
                }
                else
                {
                    u.Disconnect();
                }
            }
        }
コード例 #29
0
        public bool Add(Entities.User u)
        {
            if (Players.Count < MaximumPlayers && !UserLimit)
            {
                if (isClanWar && u.ClanRank < 1)
                {
                    return(false);
                }

                lock (_playerLock) {
                    Team targetTeam = Team.Derbaran;

                    byte startScanIndex = 0;
                    byte endScanIndex   = (byte)(MaximumPlayers / 2);

                    var debTeam = Players.Select(n => n.Value).Where(n => n.Team == Team.Derbaran).Count();
                    var niuTeam = Players.Select(n => n.Value).Where(n => n.Team == Team.NIU).Count();

                    if (debTeam > niuTeam)
                    {
                        targetTeam     = Team.NIU;
                        startScanIndex = (byte)(MaximumPlayers / 2);
                        endScanIndex   = MaximumPlayers;
                    }

                    for (byte i = startScanIndex; i < endScanIndex; i++)
                    {
                        if (!Players.ContainsKey(i))
                        {
                            Player plr = new Player(i, u, targetTeam);

                            // Send Room //
                            if (Players.Count > 0)
                            {
                                Send((new Packets.RoomPlayers(new ArrayList()
                                {
                                    plr
                                }).BuildEncrypted()));
                            }
                            else
                            {
                                Master = i;
                            }

                            // Add Player
                            Players.TryAdd(i, plr);
                            u.SetRoom(this, i);

                            // Send Join Packet //
                            u.Send(new Packets.RoomJoin(i, this));
                            u.Send(new Packets.RoomPlayers(new ArrayList(Players.Select(n => n.Value).Where(n => n.Id != i).ToArray())));

                            // Send to all spectators
                            foreach (Entities.User Spectator in Spectators.Values)
                            {
                                u.Send(new Packets.RoomPlayers(new ArrayList(Players.Select(n => n.Value).Where(n => n.Id != i).ToArray())));
                            }

                            //Tell de players
                            if (State == RoomState.Playing)
                            {
                                //     string _message = Cristina.Core.Cristina.Localization.GetLocMessageFrom("PLAYER_JOINED");
                                //   if (_message.Contains("%/nickname/%"))
                                //     _message = _message.Replace("%/nickname/%", u.Displayname);

                                Cristina.Core.Cristina.Chat.SaytoRoom(u.Displayname + " se ha conectado", this);
                            }


                            // SEND THE ROOM UPDATE TO THE LOBBY //
                            byte roomPage   = (byte)Math.Floor((decimal)(this.ID / 8));
                            var  targetList = Managers.ChannelManager.Instance.Get(this.Channel).Users.Select(n => n.Value).Where(n => n.RoomListPage == roomPage && n.Room == null);
                            if (targetList.Count() > 0)
                            {
                                byte[] outBuffer = new Packets.RoomUpdate(this, true).BuildEncrypted();
                                foreach (Entities.User usr in targetList)
                                {
                                    usr.Send(outBuffer);
                                }
                            }
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
コード例 #30
0
        public void Process(Entities.User u, Core.Networking.InPacket packet)
        {
            string[] blocks = packet.Blocks;
            ushort   subId  = 0;

            try {
                ushort.TryParse(blocks[3], out subId);
            }catch { subId = 0; }

            if (subId > 0 && Enum.IsDefined(typeof(Enums.GameSubs), subId))
            {
                this.type = (Enums.GameSubs)subId;

                lock (handleLock) {
                    this.packet = packet;
                    mapData     = false;
                    updateLobby = false;
                    selfTarget  = false;
                    respond     = false;

                    this.blocks = new string[blocks.Length - 4];
                    Array.Copy(blocks, 4, this.blocks, 0, this.blocks.Length);

                    this.Room = u.Room;
                    Entities.Player p = null;
                    selfTarget = false;

                    try {
                        this.Room.Players.TryGetValue(u.RoomSlot, out p);
                    } catch { p = null; }

                    if (p != null)
                    {
                        this.Player = p;
                        roomSlot    = p.Id;

                        try {
                            Handle();
                        } catch { respond = false; }

                        if (respond)
                        {
                            string[] packetData;
                            if (errorCode == 1)
                            {
                                packetData    = new string[this.blocks.Length + 5];
                                packetData[0] = errorCode.ToString();
                                packetData[1] = roomSlot.ToString();
                                packetData[2] = Room.ID.ToString();
                                packetData[3] = blocks[2];                 // 2 - 0
                                packetData[4] = ((ushort)type).ToString(); // Type

                                Array.Copy(this.blocks, 0, packetData, 5, this.blocks.Length);
                            }
                            else
                            {
                                packetData = new string[] { errorCode.ToString() };
                            }

                            // Generate packet buffer //
                            byte[] buffer = new Packets.GameData(packetData).BuildEncrypted();
                            if (errorCode > 1 || selfTarget)
                            {
                                u.Send(buffer);
                            }
                            else
                            {
                                Room.Send(buffer);
                            }

                            if (mapData)
                            {
                                u.Send(new Packets.MapData(Room));
                            }

                            if (updateLobby) // Send a update to the lobby :)
                            {
                                byte roomPage   = (byte)Math.Floor((decimal)(Room.ID / 8));
                                var  targetList = Managers.ChannelManager.Instance.Get(Room.Channel).Users.Select(n => n.Value).Where(n => n.RoomListPage == roomPage && n.Room == null);
                                if (targetList.Count() > 0)
                                {
                                    byte[] outBuffer = new Packets.RoomUpdate(Room, true).BuildEncrypted();
                                    foreach (Entities.User usr in targetList)
                                    {
                                        usr.Send(outBuffer);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                u.Disconnect(); // Wrong id?
            }
        }