public override void Read() { var message = Buffer.ReadString(); var preChatEvent = new PreChatEvent(message, CommandManager.ShouldProcess(message), Client.Player); EventManager.CallEvent(preChatEvent); if (preChatEvent.Cancelled) { return; } message = preChatEvent.Message; if (preChatEvent.ProcessAsCommand) { CommandManager.ParseCommand(Client.Player, message); return; } var chatEvent = new ChatEvent(message, "<{0}> {1}", Client.Player); EventManager.CallEvent(chatEvent); if (chatEvent.Cancelled) { return; } message = chatEvent.Message; var msg = string.Format(chatEvent.Format, Client.Player.GetName(), message); // Todo: Make this customizable Globals.ChatManager.BroadcastChat(msg); ConsoleFunctions.WriteInfoLine(msg); }
public static void StopServer(string stopMsg = "Server shutting down...") { if (ShutDown) { return; } ShutDown = true; ConsoleFunctions.WriteInfoLine("Shutting down..."); Globals.BroadcastPacket(new Disconnect(null) { Reason = new ChatText(stopMsg, TextColor.Reset) }); ConsoleFunctions.WriteInfoLine("Disabling all plugins..."); PluginManager.DisableAllPlugins(); ConsoleFunctions.WriteInfoLine("Saving all player data..."); foreach (Player player in Globals.LevelManager.GetAllPlayers()) { player.SavePlayer(); } ConsoleFunctions.WriteInfoLine("Saving chunks..."); Globals.LevelManager.SaveAllChunks(); ConsoleFunctions.WriteInfoLine("Stopping listening..."); //todo: ConsoleFunctions.WriteInfoLine("For some reason, the app decides to keep existing. Press Ctrl+C after a second. This will be fixed soon (hopefully)."); Globals.ServerListener.StopListenening(); Environment.Exit(0); }
public override void UseItem(Level world, Player player, Vector3 blockCoordinates, BlockFace face) { var block = world.GetBlock(blockCoordinates); ConsoleFunctions.WriteInfoLine("Block: " + block.Id); if (block.Id != 46) { var affectedBlock = world.GetBlock(blockCoordinates); if (affectedBlock.Id == 0) { var fire = new BlockFire { Coordinates = affectedBlock.Coordinates }; world.SetBlock(fire); } } else { //world.SetBlock(new BlockAir {Coordinates = block.Coordinates}); new Explosion(world, new Vector3(blockCoordinates.X, blockCoordinates.Y, blockCoordinates.Z), 5.0f).Explode(); //new PrimedTnt(world) //{ // KnownPosition = new PlayerLocation(blockCoordinates.X, blockCoordinates.Y, blockCoordinates.Z), // Fuse = (byte)(new Random().Next(0, 20) + 10) //}.SpawnEntity(); } }
public bool IsAuthenticated() { if (!Globals.Offlinemode) { try { var uri = new Uri( string.Format( "http://session.minecraft.net/game/checkserver.jsp?user={0}&serverId={1}", Username, PacketCryptography.JavaHexDigest(Encoding.UTF8.GetBytes("") .Concat(Wrapper.SharedKey) .Concat(PacketCryptography.PublicKeyToAsn1(Globals.ServerKey)) .ToArray()) )); var authenticated = new WebClient().DownloadString(uri); if (authenticated.Contains("NO")) { ConsoleFunctions.WriteInfoLine("Response: " + authenticated); return(false); } } catch (Exception exc) { //client.Kick("Error while authenticating..."); //client.Logger.Log(exc); return(false); } return(true); } return(true); }
public static void DisconnectClient(ClientWrapper client, string reason = null) { if (client != null) { if (client.Disconnected) { return; } if (client.Player != null) { ConsoleFunctions.WriteInfoLine(client.Player.Username + " disconnected" + (reason == null ? "." : " (Reason: {0})."), reason); client.Player.SavePlayer(); client.Player.Level.RemovePlayer(client.Player.EntityId); client.Player.Level.BroadcastPlayerRemoval(client); } client.ThreadPool.KillAllThreads(); client.TcpClient.Close(); ClientManager.RemoveClient(client); client.Disconnected = true; } else { ConsoleFunctions.WriteFatalErrorLine("Cannot disconnect a client from the server! (Save/Restart/Panic)"); } }
public void LoadPlayer() { string savename = Server.ServerSettings.OnlineMode ? Uuid : Username; if (File.Exists("Players/" + savename + ".pdata")) { byte[] data = File.ReadAllBytes("Players/" + savename + ".pdata"); data = FileCompression.Decompress(data); DataBuffer reader = new DataBuffer(data); double x = reader.ReadDouble(); double y = reader.ReadDouble(); double z = reader.ReadDouble(); float yaw = reader.ReadFloat(); float pitch = reader.ReadFloat(); bool onGround = reader.ReadBool(); ConsoleFunctions.WriteInfoLine("Position Loaded... (X: " + x + " Y: " + y + " Z: " + z + " Yaw: " + yaw + " Pitch: " + pitch + " OnGround: " + onGround + ")"); KnownPosition = new PlayerLocation(x, y, z) { Yaw = yaw, Pitch = pitch, OnGround = onGround }; Gamemode = (Gamemode)reader.ReadVarInt(); int healthLength = reader.ReadVarInt(); byte[] healthData = reader.Read(healthLength); int inventoryLength = reader.ReadVarInt(); byte[] inventoryData = reader.Read(inventoryLength); HealthManager.Import(healthData); Inventory.Import(inventoryData); IsOperator = reader.ReadBool(); } else { KnownPosition = Level.GetSpawnPoint(); } Loaded = true; }
public void StartListening() { int port = Server.ServerSettings.Port; if (!NetUtils.PortAvailability(port)) { ConsoleFunctions.WriteErrorLine("Port already in use... Shutting down server... [{0}]", port); Server.StopServer(); return; } ConsoleFunctions.WriteInfoLine("Starting server on port... {0}", port); _serverListener = new TcpListener(IPAddress.Any, port); if (_serverListener == null) { ConsoleFunctions.WriteErrorLine("An error occured when starting the client listener.. Null TCPListener.."); return; } _serverListener.Start(); ConsoleFunctions.WriteInfoLine("Ready & looking for client connections... "); ConsoleFunctions.WriteInfoLine("To shutdown the server safely press CTRL+C or use stop/shutdown!"); while (_serverListener.Server.IsBound) { TcpClient client = _serverListener.AcceptTcpClient(); ConsoleFunctions.WriteDebugLine("A new client has been accepted."); new Task(() => { HandleClientConnection(client); }).Start(); } }
public void SavePlayer() { var health = HealthManager.Export(); var inv = Inventory.GetBytes(); var buffer = new DataBuffer(new byte[0]); ConsoleFunctions.WriteInfoLine("Position Saving... (X: " + KnownPosition.X + " Y: " + KnownPosition.Y + " Z: " + KnownPosition.Z + " Yaw: " + KnownPosition.Yaw + " Pitch: " + KnownPosition.Pitch + " OnGround: " + KnownPosition.OnGround + ")"); buffer.WriteDouble(KnownPosition.X); buffer.WriteDouble(KnownPosition.Y); buffer.WriteDouble(KnownPosition.Z); buffer.WriteFloat(KnownPosition.Yaw); buffer.WriteFloat(KnownPosition.Pitch); buffer.WriteBool(KnownPosition.OnGround); buffer.WriteVarInt((int)Gamemode); buffer.WriteVarInt(health.Length); foreach (var b in health) { buffer.WriteByte(b); } buffer.WriteVarInt(inv.Length); foreach (var b in inv) { buffer.WriteByte(b); } buffer.WriteBool(IsOperator); var data = buffer.ExportWriter; data = FileCompression.Compress(data); var savename = Server.ServerSettings.OnlineMode ? Uuid : Username; File.WriteAllBytes("Players/" + savename + ".pdata", data); }
public bool IsAuthenticated() { if (Server.ServerSettings.OnlineMode) { try { var uri = new Uri( string.Format( "http://session.minecraft.net/game/checkserver.jsp?user={0}&serverId={1}", Username, PacketCryptography.JavaHexDigest(Encoding.UTF8.GetBytes("") .Concat(Wrapper.SharedKey) .Concat(PacketCryptography.PublicKeyToAsn1(Globals.ServerKey)) .ToArray()) )); var authenticated = new WebClient().DownloadString(uri); if (authenticated.Contains("NO")) { ConsoleFunctions.WriteInfoLine("Response: " + authenticated); return(false); } } catch (Exception e) { ConsoleFunctions.WriteWarningLine("Caught Exception in PlayerEntity.cs IsAuth function... {0}, {1}", true, e.StackTrace, e.Message); return(false); } } return(true); }
public override void UseItem(Level world, Player player, Vector3 blockCoordinates, BlockFace face) { blockCoordinates = GetNewCoordinatesFromFace(blockCoordinates, face); var block = world.GetBlock(blockCoordinates); ConsoleFunctions.WriteInfoLine("Block: " + block.Id); if (block.Id != 46) { var affectedBlock = world.GetBlock(blockCoordinates); if (affectedBlock.Id == 0) { var fire = new BlockFire { Coordinates = affectedBlock.Coordinates }; world.SetBlock(fire); } } else { new PrimedTNTEntity(world) { KnownPosition = blockCoordinates.ToPlayerLocation() }.SpawnEntity(); } }
public AnvilLevel(string worldname) { Difficulty = 0; LvlName = worldname; LevelType = LvlType.Default; Generator = new AnvilWorldProvider(worldname); ConsoleFunctions.WriteInfoLine("Level Type: Anvil"); }
public NetherLevel(string worldname) { Difficulty = 0; LvlName = worldname; LevelType = LvlType.Default; Generator = new NetherWorldProvider(worldname); ConsoleFunctions.WriteInfoLine("Level Type: Nether"); Dimension = -1; }
public override void Enable() { ConsoleFunctions.WriteInfoLine("Enabling!!!!!!"); CommandManager.AddCommand(new ExampleCommand("/")); var exampleSystem = new CommandSystem(new [] { "\\" }); exampleSystem.AddCommand(new ExampleCommand("\\")); CommandManager.AddCommandSystem(exampleSystem); }
public override void Execute(ICommandSender sender, string label, string[] args, string origMessage) { foreach (Player allPlayer in Globals.LevelManager.GetAllPlayers()) { allPlayer.SavePlayer(); } Globals.LevelManager.SaveAllChunks(); ConsoleFunctions.WriteInfoLine("World & Player data saved."); }
public BetterLevel(string worldname) { Difficulty = 0; LvlName = worldname; LevelType = LVLType.Default; Generator = new BetterWorldProvider(worldname); ConsoleFunctions.WriteInfoLine("Level Type: Better (Experimental)"); DefaultGamemode = Gamemode.Creative; }
public StandardLevel(string worldname) { Difficulty = 0; LvlName = worldname; LevelType = LvlType.Default; Generator = new StandardWorldProvider(worldname); ConsoleFunctions.WriteInfoLine("Level Type: Standard"); DefaultGamemode = Gamemode.Creative; }
private void GameTick(object source, ElapsedEventArgs e) { _sw.Start(); DayTick(); foreach (var blockEvent in BlockWithTicks.ToArray()) { if (blockEvent.Value <= CurrentWorldTime) { GetBlock(blockEvent.Key).OnTick(this); int value; BlockWithTicks.TryRemove(blockEvent.Key, out value); } } foreach (var player in OnlinePlayers.ToArray()) { player.OnTick(); } foreach (var entity in Entities.ToArray()) { entity.OnTick(); } if (_saveTick == 1500) { _saveTick = 0; ConsoleFunctions.WriteInfoLine("Saving chunks"); var sw = new Stopwatch(); sw.Start(); SaveChunks(); sw.Stop(); ConsoleFunctions.WriteInfoLine("Saving chunks took: " + sw.ElapsedMilliseconds + "MS"); ConsoleFunctions.WriteInfoLine("Clearing chunk cache..."); Generator.ClearCache(); //Clear chunk cache GC.Collect(); //Collect garbage } else { _saveTick++; } if (_saveTick == 750) { GC.Collect(); } _sw.Stop(); _lastCalc = _sw.ElapsedMilliseconds; _sw.Reset(); }
public Server(string[] args) { GuiApp.Setup(args); ConsoleFunctions.ClearConsole(); if (!args.Contains("--minimal")) { for (var i = 0; i < 10; i++) { ConsoleFunctions.Write( TextUtils.ToChatText( "\u00A74\u00A7l[ETHO]\u00A7r \u00A7l\u00A7nUSE\u00A77 --minimal\u00A7r \u00A7l\u00A7nIN PROGRAM ARGUMENTS TO FIX ASYNC WRITING OR DEAL W/ IT") ); } } ConsoleFunctions.WriteInfoLine("For some reason, writing async in non-minimal console doesn't work."); ConsoleFunctions.WriteInfoLine("For some reason, the server doesn't close all threads. Just kill it for now."); ConsoleFunctions.WriteInfoLine("Registering default events..."); EventManager.RegisterDefaultEvents(); ConsoleFunctions.WriteInfoLine("Loading plugins..."); PluginManager.RegisterPlugins(); ConsoleFunctions.WriteInfoLine("Initiating server on {0}", Globals.ProtocolName); CurrentDirectory = Directory.GetCurrentDirectory(); var currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += UnhandledException; ConsoleFunctions.Pause(); ConsoleFunctions.WriteInfoLine("Enabling global error handling... "); ConsoleFunctions.WriteLine("Enabled.", ConsoleColor.Green); ConsoleFunctions.Continue(); ConsoleFunctions.Pause(); ConsoleFunctions.WriteInfoLine("Checking if server properties exist... "); ConsoleFunctions.WriteLine(LoadSettings() ? "Loading." : "Created.", ConsoleColor.Green); ConsoleFunctions.Continue(); ConsoleFunctions.Pause(); ConsoleFunctions.WriteInfoLine("Loading server variables... "); ConsoleFunctions.WriteLine("Loaded.", ConsoleColor.Green); ConsoleFunctions.Continue(); ConsoleFunctions.Pause(); ConsoleFunctions.WriteInfoLine("Checking files and directories... "); CheckDirectoriesAndFiles(); ConsoleFunctions.WriteLine("Files are good hopefully.", ConsoleColor.Green); ConsoleFunctions.Continue(); Initiated = true; }
public void SendChat(ChatText message) { if (Wrapper.TcpClient == null) { ConsoleFunctions.WriteInfoLine(message); return; } new ChatMessage(Wrapper) { Message = message }.Write(); }
private void HandleClientCommNew(object client) { TcpClient tcpClient = (TcpClient)client; NetworkStream clientStream = tcpClient.GetStream(); ClientWrapper Client = new ClientWrapper(tcpClient); //Buffer size of 4096 Bytes, reason: I guess we don't need more? byte[] message = new byte[4096]; int bytesRead; while (true) { bytesRead = 0; try { //if (clientStream.DataAvailable) bytesRead = clientStream.Read(message, 0, 4096); if (bytesRead > 0) { ConsoleFunctions.WriteDebugLine("Packet received. Time: " + DateTime.Now.ToLocalTime()); ConsoleFunctions.WriteDebugLine("Packet ID: " + Globals.v2Int32(message, 1)[0]); PacketHandler.PacketHandler PH = new PacketHandler.PacketHandler(); Thread handler = new Thread(() => PH.HandlePacket(Client, message)); handler.Start(); } if (bytesRead == 0) { //Close connection with user. as he disconnected! break; } } catch (Exception ex) { ConsoleFunctions.WriteErrorLine("ERROR! \n" + ex.Message); break; } } ConsoleFunctions.WriteDebugLine("A client disconnected!"); if (Utils.PlayerHelper.isConnectedPlayer(Client)) { ConsoleFunctions.WriteInfoLine("Player '" + Utils.PlayerHelper.getPlayer(Client).Username + "' disconnected!"); Client._Player.SaveToFile(); Globals.Players.Remove(Utils.PlayerHelper.getPlayer(Client)); Globals.PlayerOnline--; Globals.updateTitle(); } tcpClient.Close(); Globals.ActiveConnections--; Globals.updateTitle(); }
private bool CheckAuthenticity() { foreach (FieldInfo field in Server.ServerSettings.GetType().GetFields()) { if (File.ReadAllText(ConfigName).Contains(field.Name)) { continue; } ConsoleFunctions.WriteInfoLine(field.Name + " " + field.GetValue(Server.ServerSettings)); WriteDefault(); return(false); } return(true); }
public override void Read() { if (Buffer != null) { var message = Buffer.ReadString(); switch (message) { case "MC|Brand": ConsoleFunctions.WriteInfoLine(Client.Player.Username + "'s client: " + Buffer.ReadString()); break; } } }
public override void Read() { Message = Buffer.ReadString(); if (Message.StartsWith("/")) { Globals.PluginManager.HandleCommand(Message, Client.Player); return; } Globals.BroadcastChat("<" + Client.Player.Username + "> " + Message.RemoveLineBreaks().Replace("\\", "\\\\").Replace("\"", "\'\'")); ConsoleFunctions.WriteInfoLine("<" + Client.Player.Username + "> " + Message.RemoveLineBreaks().Replace("\\", "\\\\").Replace("\"", "\'\'")); }
public override void Read() { var message = Buffer.ReadString(); if (message.StartsWith(Globals.ChatHandler.Value.CommandPrefix.ToString())) { Globals.PluginManager.HandleCommand(message, Client.Player); return; } //string msg = Globals.CleanForJson(Globals.ChatHandler.Value.PrepareMessage(Client.Player, message)); var msg = Globals.ChatHandler.Value.PrepareMessage(Client.Player, message); Globals.BroadcastChat(msg); ConsoleFunctions.WriteInfoLine(msg); }
public override void UseItem(Level world, Player player, Vector3 blockCoordinates, BlockFace face) { var blockatpos = world.GetBlock(blockCoordinates); if (!(blockatpos is BlockAir)) { BitArray b = new BitArray(new byte[] { blockatpos.Metadata }); ConsoleFunctions.WriteLine("\n\n"); ConsoleFunctions.WriteInfoLine("------------------------------------"); ConsoleFunctions.WriteInfoLine("Block: " + blockatpos); ConsoleFunctions.WriteInfoLine("------------------------------------"); for (int i = 0; i < b.Count; i++) { ConsoleFunctions.WriteInfoLine("Bit " + i + ": " + b[i]); } ConsoleFunctions.WriteInfoLine("------------------------------------\n\n"); player.SendChat("Info tool used, Metadata written to chat!", ChatColor.Gold); } }
public override void Execute(ICommandSender sender, string label, string[] args, string origMessage) { if (sender.IsPlayer()) { if (args.Length == 0) { sender.SendChat("Your current gamemode is [" + ((Player)sender).Gamemode + "]", TextColor.Gray); } else if (args.Length >= 1) { switch (args[0].ToLower()) { case "0": case "s": case "survival": ((Player)sender).SetGamemode(Gamemode.Survival); break; case "3": case "sp": case "spectator": ((Player)sender).SetGamemode(Gamemode.Spectator); break; case "2": case "a": case "adventure": ((Player)sender).SetGamemode(Gamemode.Adventure); break; default: ((Player)sender).SetGamemode(Gamemode.Creative); break; } } sender.SendChat($"Set your gamemode to [{((Player) sender).Gamemode}]", TextColor.Green); } else { ConsoleFunctions.WriteInfoLine("Cannot change gamemode through console."); } }
public void ListenForClients() { var port = Config.GetProperty("port", 25565); if (port != 25565) { _serverListener = new TcpListener(IPAddress.Any, port); } _serverListener.Start(); _listening = true; ConsoleFunctions.WriteServerLine("Ready for connections..."); ConsoleFunctions.WriteInfoLine("To shutdown the server safely press CTRL+C"); while (_listening) { var client = _serverListener.AcceptTcpClient(); ConsoleFunctions.WriteDebugLine("A new connection has been made!"); new Task((() => { HandleClientCommNew(client); })).Start(); //Task instead of Thread } }
public void SetGamemode(Gamemode target, bool silent) { Gamemode = target; new PlayerListItem(Wrapper) { Action = 1, Gamemode = Gamemode, Uuid = Uuid }.Broadcast(Level); new ChangeGameState(Wrapper) { Reason = GameStateReason.ChangeGameMode, Value = (float)target }.Write(); if (!silent) { ConsoleFunctions.WriteInfoLine(Username + "'s gamemode was changed to " + target.ToString("D")); SendChat("Your gamemode was changed to " + target.ToString(), ChatColor.Yellow); } }
public void StartServer() { if (!Initiated) { throw new Exception("Server not initiated!"); } Console.CancelKeyPress += ConsoleOnCancelKeyPress; StartTime = DateTime.UtcNow; ConsoleFunctions.WriteInfoLine("Enabling plugins..."); PluginManager.EnableAllPlugins(); ConsoleFunctions.WriteInfoLine("Enabled plugins."); try { new Thread(Globals.ServerListener.StartListening).Start(); new Thread(GuiApp.Start).Start(); } catch (Exception ex) { UnhandledException(this, new UnhandledExceptionEventArgs(ex, false)); } }
public override void Execute(ICommandSender sender, string label, string[] args, string origMessage) { if (sender.IsPlayer()) { var player = (Player)sender; if (args.Length == 0) { sender.SendChat($"Current level: {player.Level.LvlName}"); return; } var level = Globals.LevelManager.GetLevel(args[0]); if (level == null) { sender.SendChat("That level doesn't exist!", TextColor.Red); return; } Globals.LevelManager.TeleportToLevel(player, level); } else { ConsoleFunctions.WriteInfoLine("Cannot teleport console."); } }