Beispiel #1
0
        internal static void PokeHandler(Player player, Command cmd)
        {
            string targetName = cmd.Next();

            if (targetName == null)
            {
                CdPoke.PrintUsage(player);
                return;
            }
            Player target = Server.FindPlayerOrPrintMatches(player, targetName, false, true);

            if (target == null)
            {
                return;
            }
            if (target.Immortal)
            {
                player.Message("&SYou cannot poke {0}&S because they are immortal.", target.ClassyName);
                return;
            }
            if (target == player)
            {
                player.Message("&SYou cannot poke yourself.");
                return;
            }
            if (!Player.IsValidName(targetName))
            {
                return;
            }
            target.Message("&8You were just poked by {0}&8.",
                           player.ClassyName);
            player.Message("&8You poked {0}&8.", target.ClassyName);
        }
        void Nick(Player player, Command cmd)
        {
            if (!player.Can(Permissions.ChangeName))
            {
                world.NoAccessMessage(player);
                return;
            }
            string name = cmd.Next();

            if (name == null)
            {
                if (player.nick != player.name)
                {
                    world.SendToAll(Color.Sys + player.nick + " is now known as " + player.name, player);
                    player.Message("You are now known as " + name + ". Use " + Color.Help + "/nick" + Color.Sys + " again to reset.");
                    player.nick = player.name;
                    world.UpdatePlayer(player);
                }
                else
                {
                    player.Message("You do not have an alias set.");
                }
            }
            else if (Player.IsValidName(name))
            {
                world.SendToAll(Color.Sys + player.nick + " is now known as " + name, player);
                player.Message("You are now known as " + name + ". Use " + Color.Help + "/nick" + Color.Sys + " again to reset.");
                player.nick = name;
                world.UpdatePlayer(player);
            }
            else
            {
                player.Message("Invalid player name.");
            }
        }
Beispiel #3
0
        // login logic
        private bool LoginSequence()
        {
            PacketReader loginPacket = new PacketReader(reader);

            if (loginPacket.opcode != (uint)InputCodes.Handshake)
            {
                Logger.LogAlert("Session.LoginSequence: Unexpected opcode in the first packet: " + loginPacket.opcode);
                LoginFailure("Unexpected handshake message - possible protocol mismatch!");
                return(false);
            }

            int clientProtocolVersion = (int)loginPacket.ReadByte();

            if (clientProtocolVersion != Config.ProtocolVersion)
            {
                Logger.LogAlert("Session.LoginSequence: Wrong protocol version: " + clientProtocolVersion);
                LoginFailure("Incompatible protocol version!");
                return(false);
            }

            player.name = loginPacket.ReadString();
            if (!Player.IsValidName(player.name))
            {
                Logger.LogAlert("Session.LoginSequence: Unacceptible player name: " + player.name);
                LoginFailure("Invalid characters in player name!");
                return(false);
            }

            Logger.LogAlert("Session.LoginSequence: Success! " + player.name + " authenticated.");
            LoginSuccess();

            // string verificationKey = loginPacket.ReadString();
            // byte unused = loginPacket.ReadByte();
            return(true);
        }
Beispiel #4
0
        public Zone(string raw)
        {
            string[] parts = raw.Split(',');
            if (parts.Length < 3)
            {
                throw new Exception("Corrupt zone definition");
            }
            string[] header = parts[0].Split(' ');
            name      = header[0];
            xMin      = Int32.Parse(header[1]);
            yMin      = Int32.Parse(header[2]);
            hMin      = Int32.Parse(header[3]);
            xMax      = Int32.Parse(header[4]);
            yMax      = Int32.Parse(header[5]);
            hMax      = Int32.Parse(header[6]);
            buildRank = Int32.Parse(header[7]);

            foreach (string player in parts[1].Split(' '))
            {
                if (!Player.IsValidName(player))
                {
                    continue;
                }
                includedPlayers.Add(player);
            }

            foreach (string player in parts[2].Split(' '))
            {
                if (!Player.IsValidName(player))
                {
                    continue;
                }
                excludedPlayers.Add(player);
            }
        }
Beispiel #5
0
        public SecurityController([NotNull] XContainer el, bool parseExceptions)
        {
            if (el == null)
            {
                throw new ArgumentNullException("el");
            }
            if (el.Element("minRank") != null)
            {
                // ReSharper disable PossibleNullReferenceException
                minRank = Rank.Parse(el.Element("minRank").Value);
                // ReSharper restore PossibleNullReferenceException
            }
            else
            {
                minRank = null;
            }

            if (parseExceptions)
            {
                //maxRank = Rank.Parse( root.Element( "maxRank" ).Value );
                foreach (XElement player in el.Elements("included"))
                {
                    if (!Player.IsValidName(player.Value))
                    {
                        continue;
                    }
                    PlayerInfo info = PlayerDB.FindPlayerInfoExact(player.Value);
                    if (info != null)
                    {
                        Include(info);
                    }
                }

                foreach (XElement player in el.Elements("excluded"))
                {
                    if (!Player.IsValidName(player.Value))
                    {
                        continue;
                    }
                    PlayerInfo info = PlayerDB.FindPlayerInfoExact(player.Value);
                    if (info != null)
                    {
                        Exclude(info);
                    }
                }
            }
            else
            {
                rawExceptions = el.Elements("included").Union(el.Elements("excluded")).ToArray();
            }
            UpdatePlayerListCache();
        }
Beispiel #6
0
        /// <summary> Creates a SecurityController based on a XML serialised object. </summary>
        /// <param name="el"> XML element that contains the serialized settings. </param>
        /// <param name="parseExceptions"> Whether or not the the player exception list should be parsed.
        /// If PlayerDB is not loaded, exceptions should NOT be parsed - otherwise they will not be preserved. </param>
        public SecurityController([NotNull] XContainer el, bool parseExceptions)
        {
            if (el == null)
            {
                throw new ArgumentNullException("el");
            }

            XElement tempEl;

            if ((tempEl = el.Element("minRank")) != null)
            {
                minRank = Rank.Parse(tempEl.Value);
            }

            if (parseExceptions)
            {
                foreach (XElement player in el.Elements("included"))
                {
                    if (!Player.IsValidName(player.Value))
                    {
                        continue;
                    }
                    PlayerInfo info = PlayerDB.FindExact(player.Value);
                    if (info != null)
                    {
                        Include(info);
                    }
                }

                foreach (XElement player in el.Elements("excluded"))
                {
                    if (!Player.IsValidName(player.Value))
                    {
                        continue;
                    }
                    PlayerInfo info = PlayerDB.FindExact(player.Value);
                    if (info != null)
                    {
                        Exclude(info);
                    }
                }
            }
            else
            {
                rawExceptions = el.Elements("included").Union(el.Elements("excluded")).ToArray();
            }
            UpdatePlayerListCache();
        }
Beispiel #7
0
        public SecurityController(XElement el)
        {
            if (el == null)
            {
                throw new ArgumentNullException("el");
            }
            if (el.Element("minRank") != null)
            {
                minRank = RankManager.ParseRank(el.Element("minRank").Value);
            }
            else
            {
                minRank = null;
            }

            //maxRank = RankManager.ParseRank( root.Element( "maxRank" ).Value );
            foreach (XElement player in el.Elements("included"))
            {
                if (!Player.IsValidName(player.Value))
                {
                    continue;
                }
                PlayerInfo info = PlayerDB.FindPlayerInfoExact(player.Value);
                if (info != null)
                {
                    Include(info);
                }
            }

            foreach (XElement player in el.Elements("excluded"))
            {
                if (!Player.IsValidName(player.Value))
                {
                    continue;
                }
                PlayerInfo info = PlayerDB.FindPlayerInfoExact(player.Value);
                if (info != null)
                {
                    Exclude(info);
                }
            }
            UpdatePlayerListCache();
        }
Beispiel #8
0
        void DoZone(Player player, Command cmd)
        {
            if (!player.Can(Permissions.SetSpawn))
            {
                world.NoAccessMessage(player);
                return;
            }

            string name = cmd.Next();

            if (name == null)
            {
                player.Message("No zone name specified. See " + Color.Help + "/help zone");
                return;
            }
            if (!Player.IsValidName(name))
            {
                player.Message("\"" + name + "\" is not a valid zone name");
                return;
            }
            Zone zone = new Zone();

            zone.name = name;

            string property = cmd.Next();

            if (property == null)
            {
                player.Message("No zone rank/whitelist/blacklist specified. See " + Color.Help + "/help zone");
                return;
            }
            PlayerClass minRank = world.classes.ParseClass(property);

            if (minRank != null)
            {
                zone.buildRank       = minRank.rank;
                player.tag           = zone;
                player.marksExpected = 2;
                player.marks.Clear();
                player.markCount         = 0;
                player.selectionCallback = MakeZone;
            }
        }
        public void Dummy(Player player, Command cmd)
        {
            string name = cmd.Next();

            if (name == null)
            {
                player.Message(Color.Sys, "Usage: " + Color.Help + "/dummy name");
                return;
            }
            if (!Player.IsValidName(name))
            {
                player.Message(Color.Sys, "Invalid name format.");
                return;
            }
            Position pos   = player.pos;
            Player   dummy = new Player(world, name);

            dummy.id = player.id + 100;
            world.SendToAll(PacketWriter.MakeAddEntity(dummy, pos), null);
        }
Beispiel #10
0
        public Zone([NotNull] string raw, [CanBeNull] World world)
            : this()
        {
            if (raw == null)
            {
                throw new ArgumentNullException("raw");
            }
            string[] parts = raw.Split(',');

            string[] header = parts[0].Split(' ');
            Name   = header[0];
            Bounds = new BoundingBox(Int32.Parse(header[1]), Int32.Parse(header[2]), Int32.Parse(header[3]),
                                     Int32.Parse(header[4]), Int32.Parse(header[5]), Int32.Parse(header[6]));

            Rank buildRank = Rank.Parse(header[7]);

            // if all else fails, fall back to lowest class
            if (buildRank == null)
            {
                if (world != null)
                {
                    Controller.MinRank = world.BuildSecurity.MinRank;
                }
                else
                {
                    Controller.ResetMinRank();
                }
                Logger.Log(LogType.Error,
                           "Zone: Error parsing zone definition: unknown rank \"{0}\". Permission reset to default ({1}).",
                           header[7], Controller.MinRank.Name);
            }
            else
            {
                Controller.MinRank = buildRank;
            }


            // Part 2:
            foreach (string player in parts[1].Split(' '))
            {
                if (!Player.IsValidName(player))
                {
                    continue;
                }
                PlayerInfo info = PlayerDB.FindPlayerInfoExact(player);
                if (info == null)
                {
                    continue;                // player name not found in the DB (discarded)
                }
                Controller.Include(info);
            }

            // Part 3: excluded list
            foreach (string player in parts[2].Split(' '))
            {
                if (!Player.IsValidName(player))
                {
                    continue;
                }
                PlayerInfo info = PlayerDB.FindPlayerInfoExact(player);
                if (info == null)
                {
                    continue;                // player name not found in the DB (discarded)
                }
                Controller.Exclude(info);
            }

            // Part 4: extended header
            if (parts.Length > 3)
            {
                string[] xheader = parts[3].Split(' ');
                CreatedBy = PlayerDB.FindPlayerInfoExact(xheader[0]);
                if (CreatedBy != null)
                {
                    CreatedDate = DateTime.Parse(xheader[1]);
                }
                EditedBy = PlayerDB.FindPlayerInfoExact(xheader[2]);
                if (EditedBy != null)
                {
                    EditedDate = DateTime.Parse(xheader[3]);
                }
            }
        }
Beispiel #11
0
        public static void VoteParams(Player player, Command cmd)
        {
            string option = cmd.Next();

            if (option == null)
            {
                player.Message("Invalid param");
                return;
            }
            switch (option)
            {
            default:
                if (VoteIsOn)
                {
                    if (VoteKickReason == null)
                    {
                        player.Message("Last Question: {0}&C asked: {1}", VoteStarter, Question);
                        player.Message(Usage);
                        return;
                    }
                    else
                    {
                        player.Message("Last VoteKick: &CA VoteKick has started for {0}&C, reason: {1}", TargetName,
                                       VoteKickReason);
                    }
                    player.Message(Usage);
                    return;
                }
                else
                {
                    player.Message(option);
                }
                break;

            case "abort":
            case "stop":
                if (!VoteIsOn)
                {
                    player.Message("No vote is currently running");
                    return;
                }

                if (!player.Can(Permission.MakeVotes))
                {
                    player.Message("You do not have Permission to abort votes");
                    return;
                }
                VoteIsOn = false;
                foreach (Player V in Voted)
                {
                    if (V.HasVoted)
                    {
                        V.HasVoted = false;
                    }
                    V.Message("Your vote was cancelled");
                }
                Voted.Clear();
                TargetName = null;
                Server.Players.Message("{0} &Saborted the vote.", player.ClassyName);
                break;

            case "yes":
                if (!VoteIsOn)
                {
                    player.Message("No vote is currently running");
                    return;
                }

                if (player.HasVoted)
                {
                    player.Message("&CYou have already voted");
                    return;
                }
                Voted.Add(player);
                VotedYes++;
                player.HasVoted = true;
                player.Message("&8You have voted for 'Yes'");
                break;

            case "kick":
                string toKick = cmd.Next();
                string Reason = cmd.NextAll();
                VoteKickReason = Reason;
                if (toKick == null)
                {
                    player.Message("Target cannot be empty. " + Usage);
                    return;
                }

                Player target = Server.FindPlayerOrPrintMatches(player, toKick, false, true);

                if (target == null)
                {
                    // FIX: Target is null when no such player is online, this caused crashes
                    return;
                }

                if (!Player.IsValidName(target.Name))
                {
                    return;
                }

                if (!player.Can(Permission.MakeVoteKicks))
                {
                    player.Message("You do not have permissions to start a VoteKick");
                    return;
                }

                if (VoteIsOn)
                {
                    player.Message("A vote has already started. Each vote lasts 1 minute.");
                    return;
                }

                if (VoteKickReason.Length < 3)
                {
                    player.Message("Invalid reason");
                    return;
                }

                if (target == player)
                {
                    player.Message("You cannot VoteKick yourself, lol");
                    return;
                }

                VoteThread = new Thread(new ThreadStart(delegate
                {
                    TargetName = target.Name;
                    if (!Player.IsValidName(TargetName))
                    {
                        player.Message("Invalid name");
                        return;
                    }
                    NewVote();
                    VoteStarter = player.ClassyName;
                    Server.Players.Message("{0}&S started a VoteKick for player: {1}", player.ClassyName,
                                           target.ClassyName);
                    Server.Players.Message("&WReason: {0}", VoteKickReason);
                    Server.Players.Message("&9Vote now! &S/Vote &AYes &Sor /Vote &CNo");
                    VoteIsOn = true;
                    Logger.Log(LogType.SystemActivity, "{0} started a votekick on player {1} reason: {2}",
                               player.Name, target.Name, VoteKickReason);
                    Thread.Sleep(60000);
                    VoteKickCheck();
                }));
                VoteThread.Start();
                break;

            case "no":
                if (!VoteIsOn)
                {
                    player.Message("No vote is currently running");
                    return;
                }
                if (player.HasVoted)
                {
                    player.Message("&CYou have already voted");
                    return;
                }
                VotedNo++;
                Voted.Add(player);
                player.HasVoted = true;
                player.Message("&8You have voted for 'No'");
                break;

            case "1":
                if (PropHunt.IsOn)
                {
                    if (!PropHunt.VoteIsOn)
                    {
                        player.Message("Voting has not yet started.");
                        return;
                    }

                    if (player.HasVoted)
                    {
                        player.Message("&CYou have already voted.");
                        return;
                    }
                    PropHunt.Voted.Add(player);
                    PropHunt.Voted1++;
                    player.HasVoted = true;
                    player.Message("&8You have voted for {0}.", PropHunt.World1.ClassyName);
                }
                break;

            case "2":
                if (PropHunt.IsOn)
                {
                    if (!PropHunt.VoteIsOn)
                    {
                        player.Message("Voting has not yet started.");
                        return;
                    }

                    if (player.HasVoted)
                    {
                        player.Message("&CYou have already voted.");
                        return;
                    }
                    PropHunt.Voted.Add(player);
                    PropHunt.Voted2++;
                    player.HasVoted = true;
                    player.Message("&8You have voted for {0}.", PropHunt.World2.ClassyName);
                }
                break;

            case "3":
                if (PropHunt.IsOn)
                {
                    if (!PropHunt.VoteIsOn)
                    {
                        player.Message("Voting has not yet started.");
                        return;
                    }

                    if (player.HasVoted)
                    {
                        player.Message("&CYou have already voted.");
                        return;
                    }
                    PropHunt.Voted.Add(player);
                    PropHunt.Voted3++;
                    player.HasVoted = true;
                    player.Message("&8You have voted for {0}.", PropHunt.World3.ClassyName);
                }
                break;

            case "ask":
                string AskQuestion = cmd.NextAll();
                Question = AskQuestion;
                if (!player.Can(Permission.MakeVotes))
                {
                    player.Message("You do not have permissions to ask a question");
                    return;
                }
                if (VoteIsOn)
                {
                    player.Message("A vote has already started. Each vote lasts 1 minute.");
                    return;
                }
                if (Question.Length < 5)
                {
                    player.Message("Invalid question");
                    return;
                }

                VoteThread = new Thread(new ThreadStart(delegate
                {
                    NewVote();
                    VoteStarter = player.ClassyName;
                    Server.Players.Message("{0}&S Asked: {1}", player.ClassyName, Question);
                    Server.Players.Message("&9Vote now! &S/Vote &AYes &Sor /Vote &CNo");
                    VoteIsOn = true;
                    Thread.Sleep(60000);
                    VoteCheck();
                }));
                VoteThread.Start();
                break;
            }
        }
Beispiel #12
0
        public Zone([NotNull] string raw, [CanBeNull] World world)
            : this()
        {
            if (raw == null)
            {
                throw new ArgumentNullException("raw");
            }
            string[] parts = raw.Split(',');

            string[] header = parts[0].Split(' ');
            Name   = header[0];
            Bounds = new BoundingBox(Int32.Parse(header[1]), Int32.Parse(header[2]), Int32.Parse(header[3]),
                                     Int32.Parse(header[4]), Int32.Parse(header[5]), Int32.Parse(header[6]));

            Rank buildRank = Rank.Parse(header[7]);

            if (header[0].Contains("Door_"))
            {
                buildRank = RankManager.DefaultRank;
            }
            // if all else fails, fall back to lowest class... ignore door instances
            if (buildRank == null && !header[0].Contains("Door_"))
            {
                if (world != null)
                {
                    Controller.MinRank = world.BuildSecurity.MinRank;
                }
                else
                {
                    Controller.ResetMinRank();
                }
                Logger.Log(LogType.Error,
                           "Zone: Error parsing zone definition: unknown rank \"{0}\". Permission reset to default ({1}). Ignore this message if you have recently changed rank permissions.",
                           header[7], Controller.MinRank.Name);
            }
            else
            {
                Controller.MinRank = buildRank;
            }

            if (PlayerDB.IsLoaded)
            {
                // Part 2:
                if (parts[1].Length > 0)
                {
                    foreach (string playerName in parts[1].Split(' '))
                    {
                        if (!Player.IsValidName(playerName))
                        {
                            Logger.Log(LogType.Warning,
                                       "Invalid entry in zone \"{0}\" whitelist: {1}", Name, playerName);
                            continue;
                        }
                        PlayerInfo info = PlayerDB.FindPlayerInfoExact(playerName);
                        if (info == null)
                        {
                            Logger.Log(LogType.Warning,
                                       "Unrecognized player in zone \"{0}\" whitelist: {1}", Name, playerName);
                            continue; // player name not found in the DB (discarded)
                        }
                        Controller.Include(info);
                    }
                }

                // Part 3: excluded list
                if (parts[2].Length > 0)
                {
                    foreach (string playerName in parts[2].Split(' '))
                    {
                        if (!Player.IsValidName(playerName))
                        {
                            Logger.Log(LogType.Warning,
                                       "Invalid entry in zone \"{0}\" blacklist: {1}", Name, playerName);
                            continue;
                        }
                        PlayerInfo info = PlayerDB.FindPlayerInfoExact(playerName);
                        if (info == null)
                        {
                            Logger.Log(LogType.Warning,
                                       "Unrecognized player in zone \"{0}\" whitelist: {1}", Name, playerName);
                            continue; // player name not found in the DB (discarded)
                        }
                        Controller.Exclude(info);
                    }
                }
            }
            else
            {
                rawWhitelist = parts[1];
                rawBlacklist = parts[2];
            }

            // Part 4: extended header
            if (parts.Length > 3)
            {
                string[] xheader = parts[3].Split(' ');
                if (xheader[0] == "-")
                {
                    CreatedBy   = null;
                    CreatedDate = DateTime.MinValue;
                }
                else
                {
                    CreatedBy   = xheader[0];
                    CreatedDate = DateTime.Parse(xheader[1]);
                }

                if (xheader[2] == "-")
                {
                    EditedBy   = null;
                    EditedDate = DateTime.MinValue;
                }
                else
                {
                    EditedBy   = xheader[2];
                    EditedDate = DateTime.Parse(xheader[3]);
                }
            }

            //message
            if (parts.Length > 4 && !string.IsNullOrWhiteSpace(parts[4]))
            {
                Message = parts[4].Replace('\\', ',');
            }
            else
            {
                Message = null;
            }
        }
Beispiel #13
0
        public Zone([NotNull] string raw, [CanBeNull] World world)
            : this()
        {
            if (raw == null)
            {
                throw new ArgumentNullException("raw");
            }
            string[] parts = raw.Split(',');

            string[] header = parts[0].Split(' ');
            Name   = header[0];
            Bounds = new BoundingBox(Int32.Parse(header[1]), Int32.Parse(header[2]), Int32.Parse(header[3]),
                                     Int32.Parse(header[4]), Int32.Parse(header[5]), Int32.Parse(header[6]));

            // If no ranks are loaded (e.g. MapConverter/MapRenderer)(
            if (RankManager.Ranks.Count > 0)
            {
                Rank buildRank = Rank.Parse(header[7]);
                // if all else fails, fall back to lowest class
                if (buildRank == null)
                {
                    if (world != null)
                    {
                        Controller.MinRank = world.BuildSecurity.MinRank;
                    }
                    else
                    {
                        Controller.ResetMinRank();
                    }
                    Logger.Log(LogType.Error,
                               "Zone: Error parsing zone definition: unknown rank \"{0}\". Permission reset to default ({1}).",
                               header[7], Controller.MinRank.Name);
                }
                else
                {
                    Controller.MinRank = buildRank;
                }
            }

            // If PlayerDB is not loaded (e.g. ConfigGUI)
            if (PlayerDB.IsLoaded)
            {
                // Part 2:
                if (parts[1].Length > 0)
                {
                    foreach (string playerName in parts[1].Split(' '))
                    {
                        if (!Player.IsValidName(playerName))
                        {
                            Logger.Log(LogType.Warning,
                                       "Invalid entry in zone \"{0}\" whitelist: {1}", Name, playerName);
                            continue;
                        }
                        PlayerInfo info = PlayerDB.FindPlayerInfoExact(playerName);
                        if (info == null)
                        {
                            Logger.Log(LogType.Warning,
                                       "Unrecognized player in zone \"{0}\" whitelist: {1}", Name, playerName);
                            continue; // player name not found in the DB (discarded)
                        }
                        Controller.Include(info);
                    }
                }

                // Part 3: excluded list
                if (parts[2].Length > 0)
                {
                    foreach (string playerName in parts[2].Split(' '))
                    {
                        if (!Player.IsValidName(playerName))
                        {
                            Logger.Log(LogType.Warning,
                                       "Invalid entry in zone \"{0}\" blacklist: {1}", Name, playerName);
                            continue;
                        }
                        PlayerInfo info = PlayerDB.FindPlayerInfoExact(playerName);
                        if (info == null)
                        {
                            Logger.Log(LogType.Warning,
                                       "Unrecognized player in zone \"{0}\" whitelist: {1}", Name, playerName);
                            continue; // player name not found in the DB (discarded)
                        }
                        Controller.Exclude(info);
                    }
                }
            }
            else
            {
                RawWhitelist = parts[1];
                RawBlacklist = parts[2];
            }

            // Part 4: extended header
            if (parts.Length > 3)
            {
                string[] xheader = parts[3].Split(' ');
                if (xheader[0] == "-")
                {
                    CreatedBy   = null;
                    CreatedDate = DateTime.MinValue;
                }
                else
                {
                    CreatedBy   = xheader[0];
                    CreatedDate = DateTime.Parse(xheader[1]);
                }

                if (xheader[2] == "-")
                {
                    EditedBy   = null;
                    EditedDate = DateTime.MinValue;
                }
                else
                {
                    EditedBy   = xheader[2];
                    EditedDate = DateTime.Parse(xheader[3]);
                }
            }
        }
        static void ImportBans(Player player, CommandReader cmd)
        {
            string serverName = cmd.Next();
            string fileName   = cmd.Next();

            // Make sure all parameters are specified
            if (serverName == null || fileName == null)
            {
                CdImport.PrintUsage(player);
                return;
            }

            // Check if file exists
            if (!File.Exists(fileName))
            {
                player.Message("File not found: {0}", fileName);
                return;
            }

            string[] names;

            switch (serverName.ToLower())
            {
            case "mcsharp":
            case "mczall":
            case "mclawl":
                try {
                    names = File.ReadAllLines(fileName);
                } catch (Exception ex) {
                    Logger.Log(LogType.Error,
                               "Could not open \"{0}\" to import bans: {1}",
                               fileName, ex);
                    return;
                }
                break;

            default:
                player.Message("fCraft does not support importing from {0}", serverName);
                return;
            }

            if (!cmd.IsConfirmed)
            {
                player.Confirm(cmd, "Import {0} bans from \"{1}\"?",
                               names.Length, Path.GetFileName(fileName));
                return;
            }

            string reason = "(import from " + serverName + ")";

            foreach (string name in names)
            {
                if (Player.IsValidName(name))
                {
                    PlayerInfo info = PlayerDB.FindExact(name) ??
                                      PlayerDB.AddUnrecognizedPlayer(name, RankChangeType.Default);
                    info.Ban(player, reason, true, true);
                }
                else
                {
                    IPAddress ip;
                    if (IPAddressUtil.IsIP(name) && IPAddress.TryParse(name, out ip))
                    {
                        ip.BanIP(player, reason, true, true);
                    }
                    else
                    {
                        player.Message("Could not parse \"{0}\" as either name or IP. Skipping.", name);
                    }
                }
            }

            PlayerDB.Save();
            IPBanList.Save();
        }
Beispiel #15
0
        // login logic
        void LoginSequence()
        {
            byte opcode = reader.ReadByte();

            if (opcode != (byte)InputCodes.Handshake)
            {
                world.log.Log("Session.LoginSequence: Unexpected opcode in the first packet: {0}.", LogType.Error, opcode);
                KickNow("Unexpected handshake message - possible protocol mismatch!");
                return;
            }

            // check protocol version
            int clientProtocolVersion = reader.ReadByte();

            if (clientProtocolVersion != Config.ProtocolVersion)
            {
                world.log.Log("Session.LoginSequence: Wrong protocol version: {0}.", LogType.Error, clientProtocolVersion);
                KickNow("Incompatible protocol version!");
                return;
            }

            // check name for nonstandard characters
            string playerName       = ReadString();
            string verificationCode = ReadString();

            reader.ReadByte(); // unused

            if (!Player.IsValidName(playerName))
            {
                world.log.Log("Session.LoginSequence: Unacceptible player name: {0} ({1})", LogType.SuspiciousActivity, playerName, GetIP().ToString());
                KickNow("Invalid characters in player name!");
                return;
            }

            // check if player is banned
            player = new Player(world, playerName, this, world.map.spawn);
            if (player.info.banned)
            {
                player.info.ProcessFailedLogin(player);
                world.log.Log("Banned player {0} tried to log in.", LogType.SuspiciousActivity, player.name);
                world.SendToAll(PacketWriter.MakeMessage(Color.Sys + "Banned player " + player.name + " tried to log in."), player);
                KickNow("You were banned by " + player.info.bannedBy + " " + DateTime.Now.Subtract(player.info.banDate).Days + " days ago.");
                return;
            }

            // check if player's IP is banned
            IPBanInfo IPBanInfo = world.bans.Get(GetIP());

            if (IPBanInfo != null)
            {
                player.info.ProcessFailedLogin(player);
                IPBanInfo.ProcessAttempt(player);
                world.log.Log("{0} tried to log in from a banned IP.", LogType.SuspiciousActivity, player.name);
                world.SendToAll(PacketWriter.MakeMessage(Color.Sys + player.name + " tried to log in from a banned IP."), null);
                KickNow("Your IP was banned by " + IPBanInfo.bannedBy + " " + DateTime.Now.Subtract(IPBanInfo.banDate).Days + " days ago.");
                return;
            }

            // verify name
            if (!world.server.VerifyName(player.name, verificationCode))
            {
                string standardMessage = String.Format("Session.LoginSequence: Could not verify player name for {0} ({1}).",
                                                       player.name, GetIP());
                if (player.info.timesVisited == 1 || player.info.lastIP.ToString() != GetIP().ToString())
                {
                    switch (world.config.GetString("VerifyNames"))
                    {
                    case "Always":
                    case "Balanced":
                        player.info.ProcessFailedLogin(player);
                        world.log.Log("{0} IP did not match. Player was kicked.", LogType.SuspiciousActivity, standardMessage);
                        KickNow("Could not verify player name!");
                        return;

                    case "Never":
                        world.log.Log("{0} IP did not match. Player was allowed in anyway because VerifyNames is set to Never.",
                                      LogType.SuspiciousActivity,
                                      standardMessage);
                        Send(PacketWriter.MakeMessage(Color.Red + "Your name could not be verified."));
                        world.SendToAll(PacketWriter.MakeMessage(Color.Red + "Name and IP of " + player.name + " could not be verified!"), player);
                        break;
                    }
                }
                else
                {
                    switch (world.config.GetString("VerifyNames"))
                    {
                    case "Always":
                        player.info.ProcessFailedLogin(player);
                        world.log.Log("{0} IP matched previous records for that name. " +
                                      "Player was kicked anyway because VerifyNames is set to Always.", LogType.SuspiciousActivity,
                                      standardMessage);
                        KickNow("Could not verify player name!");
                        return;

                    case "Balanced":
                    case "Never":
                        world.log.Log("{0} IP matched previous records for that name. Player was allowed in.", LogType.SuspiciousActivity,
                                      standardMessage);
                        Send(PacketWriter.MakeMessage(Color.Red + "Your name could not be verified."));
                        if (world.config.GetBool("AnnounceUnverifiedNames"))
                        {
                            world.SendToAll(PacketWriter.MakeMessage(Color.Red + "Name of " + player.name +
                                                                     " could not be verified, but IP matches."), player);
                        }
                        break;
                    }
                }
            }

            // check if another player with the same name is on
            Player potentialClone = world.FindPlayer(player.name);

            if (potentialClone != null)
            {
                player.info.ProcessFailedLogin(player);
                world.log.Log("Session.LoginSequence: Player {0} tried to log in from two computers at once.", LogType.SuspiciousActivity, player.name);
                potentialClone.Message("Warning: someone just attempted to log in using your name.");
                KickNow("Already connected form elsewhere!");
                return;
            }

            potentialClone = world.FindPlayer(GetIP());
            if (potentialClone != null)
            {
                player.info.ProcessFailedLogin(player);
                world.log.Log("Session.LoginSequence: Player {0} tried to log in from same IP ({1}) as {2}.", LogType.SuspiciousActivity,
                              player.name, GetIP().ToString(), potentialClone.name);
                potentialClone.Message("Warning: someone just attempted to log in using your IP.");
                KickNow("Only one connection per IP allowed!");
                return;
            }

            // Register player for future block updates
            if (!world.RegisterPlayer(player))
            {
                KickNow("Sorry, server is full.");
                return;
            }

            player.info.ProcessLogin(player);

            // Player is now authenticated. Send server info.
            writer.Write(PacketWriter.MakeHandshake(world, player));

            // Start sending over the level copy
            writer.WriteLevelBegin();
            byte[] buffer    = new byte[1024];
            int    bytesSent = 0;

            // Fetch compressed map copy
            byte[] blockData;
            using (MemoryStream stream = new MemoryStream()) {
                world.map.GetCompressedCopy(stream, true);
                blockData = stream.ToArray();
            }
            world.log.Log("Session.LoginSequence: Sending compressed level copy ({0} bytes) to {1}.", LogType.Debug,
                          blockData.Length, player.name);

            while (bytesSent < blockData.Length)
            {
                int chunkSize = blockData.Length - bytesSent;
                if (chunkSize > 1024)
                {
                    chunkSize = 1024;
                }
                Array.Copy(blockData, bytesSent, buffer, 0, chunkSize);
                byte progress = (byte)(100 * bytesSent / blockData.Length);

                // write in chunks of 1024 bytes or less
                writer.WriteLevelChunk(buffer, chunkSize, progress);
                bytesSent += chunkSize;
            }

            // Done sending over level copy
            writer.Write(PacketWriter.MakeLevelEnd(world.map));

            // Send playerlist and add player himself
            writer.WriteAddEntity(255, player.name, player.pos);
            world.SendPlayerList(player);

            // Reveal newcommer to existing players
            world.log.Log("{0} ({1}) has joined the server.", LogType.UserActivity, player.name, player.info.playerClass.name);
            world.SendToAll(PacketWriter.MakeAddEntity(player, player.pos), player);
            world.SendToAll(PacketWriter.MakeMessage(Color.Sys + player.name + " (" + player.info.playerClass.color +
                                                     player.info.playerClass.name + Color.Sys + ") has joined the server."),
                            player);

            // Welcome message
            if (player.info.timesVisited > 1)
            {
                player.Message("Welcome back to " + world.config.GetString("ServerName"));
            }
            else
            {
                player.Message("Welcome to " + world.config.GetString("ServerName"));
            }

            player.Message("Your player class is " + player.info.playerClass.color + player.info.playerClass.name + Color.Sys +
                           ". Type /help for details.");

            if (world.config.GetBool("LowLatencyMode"))
            {
                client.NoDelay = true;
            }

            // Done.
            world.log.Log("Session.LoginSequence: {0} is now ready.", LogType.Debug,
                          player.name);
            GC.Collect();
        }