Merge branch 'master' into inventory

This commit is contained in:
RednedEpic 2020-03-04 21:35:20 -06:00
commit 6b22bcec2b
130 changed files with 2776 additions and 2158 deletions

View file

@ -6,16 +6,12 @@
<parent>
<groupId>org.geysermc</groupId>
<artifactId>geyser-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<version>parent</version>
<relativePath>../</relativePath>
</parent>
<artifactId>connector</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>api</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.geysermc</groupId>
<artifactId>common</artifactId>
@ -40,30 +36,6 @@
<version>1.7.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.minecrell</groupId>
<artifactId>terminalconsoleappender</artifactId>
<version>1.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.6.4</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>1.18</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.nukkitx.protocol</groupId>
<artifactId>bedrock-v389</artifactId>
@ -121,45 +93,4 @@
</exclusions>
</dependency>
</dependencies>
<build>
<finalName>${project.parent.name}-noshade</finalName>
<directory>../target</directory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifestEntries>
<Main-Class>org.geysermc.connector.GeyserConnector</Main-Class>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<configuration>
<finalName>${project.parent.name}</finalName>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
<configuration>
<finalName>${project.parent.name}</finalName>
<shadedArtifactAttached>true</shadedArtifactAttached>
<minimizeJar>true</minimizeJar>
</configuration>
</plugin>
</plugins>
</build>
</project>

View file

@ -30,42 +30,31 @@ import com.nukkitx.protocol.bedrock.BedrockServer;
import com.nukkitx.protocol.bedrock.v389.Bedrock_v389;
import lombok.Getter;
import org.fusesource.jansi.AnsiConsole;
import org.geysermc.api.Connector;
import org.geysermc.api.Geyser;
import org.geysermc.api.Player;
import org.geysermc.api.command.CommandMap;
import org.geysermc.api.logger.Logger;
import org.geysermc.api.plugin.Plugin;
import org.geysermc.common.AuthType;
import org.geysermc.common.PlatformType;
import org.geysermc.common.bootstrap.IGeyserBootstrap;
import org.geysermc.common.logger.IGeyserLogger;
import org.geysermc.connector.command.GeyserCommandMap;
import org.geysermc.connector.configuration.GeyserConfiguration;
import org.geysermc.connector.console.ConsoleCommandReader;
import org.geysermc.connector.console.GeyserLogger;
import org.geysermc.connector.metrics.Metrics;
import org.geysermc.connector.network.ConnectorServerEventHandler;
import org.geysermc.connector.network.remote.RemoteJavaServer;
import org.geysermc.connector.network.remote.RemoteServer;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.TranslatorsInit;
import org.geysermc.connector.plugin.GeyserPluginLoader;
import org.geysermc.connector.plugin.GeyserPluginManager;
import org.geysermc.connector.thread.PingPassthroughThread;
import org.geysermc.connector.utils.FileUtils;
import org.geysermc.connector.utils.Toolbox;
import org.geysermc.common.IGeyserConfiguration;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Getter
public class GeyserConnector implements Connector {
public class GeyserConnector {
public static final BedrockPacketCodec BEDROCK_PACKET_CODEC = Bedrock_v389.V389_CODEC;
@ -76,37 +65,31 @@ public class GeyserConnector implements Connector {
private static GeyserConnector instance;
private RemoteJavaServer remoteServer;
private RemoteServer remoteServer;
private AuthType authType;
private Logger logger;
private IGeyserLogger logger;
private IGeyserConfiguration config;
private CommandMap commandMap;
private GeyserConfiguration config;
private GeyserPluginManager pluginManager;
private GeyserCommandMap commandMap;
private boolean shuttingDown = false;
private final ScheduledExecutorService generalThreadPool;
private PingPassthroughThread passthroughThread;
private BedrockServer bedrockServer;
private PlatformType platformType;
private Metrics metrics;
public static void main(String[] args) {
instance = new GeyserConnector();
}
private GeyserConnector() {
private GeyserConnector(PlatformType platformType, IGeyserConfiguration config, IGeyserLogger logger) {
long startupTime = System.currentTimeMillis();
// Metric
if (!(System.console() == null) && System.getProperty("os.name", "Windows 10").toLowerCase().contains("windows")) {
AnsiConsole.systemInstall();
}
instance = this;
this.logger = GeyserLogger.DEFAULT;
this.logger = logger;
this.platformType = platformType;
logger.info("******************************************");
logger.info("");
@ -114,17 +97,8 @@ public class GeyserConnector implements Connector {
logger.info("");
logger.info("******************************************");
try {
File configFile = FileUtils.fileOrCopiedFromResource("config.yml", (x) -> x.replaceAll("generateduuid", UUID.randomUUID().toString()));
config = FileUtils.loadConfig(configFile, GeyserConfiguration.class);
} catch (IOException ex) {
logger.severe("Failed to read/create config.yml! Make sure it's up to date and/or readable+writable!", ex);
shutdown();
}
this.config = config;
this.generalThreadPool = Executors.newScheduledThreadPool(config.getGeneralThreadPool());
ConsoleCommandReader consoleReader = new ConsoleCommandReader(this);
consoleReader.startConsole();
logger.setDebug(config.isDebugMode());
@ -132,18 +106,14 @@ public class GeyserConnector implements Connector {
TranslatorsInit.start();
commandMap = new GeyserCommandMap(this);
remoteServer = new RemoteJavaServer(config.getRemote().getAddress(), config.getRemote().getPort());
Geyser.setConnector(this);
pluginManager = new GeyserPluginManager(new GeyserPluginLoader(this));
pluginManager.getLoader().loadPlugins();
remoteServer = new RemoteServer(config.getRemote().getAddress(), config.getRemote().getPort());
authType = AuthType.getByName(config.getRemote().getAuthType());
passthroughThread = new PingPassthroughThread(this);
if (config.isPingPassthrough())
generalThreadPool.scheduleAtFixedRate(passthroughThread, 1, 1, TimeUnit.SECONDS);
BedrockServer bedrockServer = new BedrockServer(new InetSocketAddress(config.getBedrock().getAddress(), config.getBedrock().getPort()));
bedrockServer = new BedrockServer(new InetSocketAddress(config.getBedrock().getAddress(), config.getBedrock().getPort()));
bedrockServer.setHandler(new ConnectorServerEventHandler(this));
bedrockServer.bind().whenComplete((avoid, throwable) -> {
if (throwable == null) {
@ -155,43 +125,46 @@ public class GeyserConnector implements Connector {
}).join();
if (config.getMetrics().isEnabled()) {
metrics = new Metrics("GeyserMC", config.getMetrics().getUUID(), false, java.util.logging.Logger.getLogger(""));
metrics = new Metrics(this, "GeyserMC", config.getMetrics().getUniqueId(), false, java.util.logging.Logger.getLogger(""));
metrics.addCustomChart(new Metrics.SingleLineChart("servers", () -> 1));
metrics.addCustomChart(new Metrics.SingleLineChart("players", Geyser::getPlayerCount));
metrics.addCustomChart(new Metrics.SimplePie("authMode", config.getRemote()::getAuthType));
metrics.addCustomChart(new Metrics.SingleLineChart("players", players::size));
metrics.addCustomChart(new Metrics.SimplePie("authMode", authType.name()::toLowerCase));
metrics.addCustomChart(new Metrics.SimplePie("platform", platformType::getPlatformName));
}
double completeTime = (System.currentTimeMillis() - startupTime) / 1000D;
logger.info(String.format("Done (%ss)! Run /help for help!", new DecimalFormat("#.###").format(completeTime)));
}
@Override
public Collection<? extends Player> getConnectedPlayers() {
return players.values();
logger.info(String.format("Done (%ss)! Run /geyser help for help!", new DecimalFormat("#.###").format(completeTime)));
}
public void shutdown() {
logger.info("Shutting down connector.");
for (Plugin plugin : pluginManager.getPlugins()) {
pluginManager.disablePlugin(plugin);
pluginManager.unloadPlugin(plugin);
}
logger.info("Shutting down Geyser.");
shuttingDown = true;
generalThreadPool.shutdown();
System.exit(0);
bedrockServer.close();
}
public void addPlayer(GeyserSession player) {
players.put(player.getAuthenticationData().getName(), player);
players.put(player.getAuthenticationData().getUUID(), player);
players.put(player.getAuthData().getName(), player);
players.put(player.getAuthData().getUUID(), player);
players.put(player.getSocketAddress(), player);
}
public void removePlayer(GeyserSession player) {
players.remove(player.getAuthenticationData().getName());
players.remove(player.getAuthenticationData().getUUID());
players.remove(player.getAuthData().getName());
players.remove(player.getAuthData().getUUID());
players.remove(player.getSocketAddress());
}
public static GeyserConnector start(PlatformType platformType, IGeyserBootstrap bootstrap) {
return new GeyserConnector(platformType, bootstrap.getGeyserConfig(), bootstrap.getGeyserLogger());
}
public static void stop() {
instance.shutdown();
}
public static GeyserConnector getInstance() {
return instance;
}
}

View file

@ -0,0 +1,16 @@
package org.geysermc.connector.command;
public interface CommandSender {
String getName();
default void sendMessage(String[] messages) {
for (String message : messages) {
sendMessage(message);
}
}
void sendMessage(String message);
boolean isConsole();
}

View file

@ -25,18 +25,24 @@
package org.geysermc.connector.command;
import org.geysermc.api.command.Command;
import org.geysermc.api.command.CommandSender;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
public abstract class GeyserCommand implements Command {
@Getter
@Setter
public abstract class GeyserCommand {
private String name;
private String description;
@Setter(AccessLevel.NONE)
private GeyserCommandMap commandMap;
private List<String> aliases;
private List<String> aliases = new ArrayList<>();
public GeyserCommand(String name) {
this(name, "A geyser command.");
@ -47,38 +53,5 @@ public abstract class GeyserCommand implements Command {
this.description = description;
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public List<String> getAliases() {
return aliases;
}
@Override
public void setAliases(List<String> aliases) {
this.aliases = aliases;
}
@Override
public abstract void execute(CommandSender sender, String[] args);
public GeyserCommandMap getCommandMap() {
return commandMap;
}
}

View file

@ -25,9 +25,6 @@
package org.geysermc.connector.command;
import org.geysermc.api.command.Command;
import org.geysermc.api.command.CommandMap;
import org.geysermc.api.command.CommandSender;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.command.defaults.HelpCommand;
import org.geysermc.connector.command.defaults.StopCommand;
@ -36,9 +33,9 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class GeyserCommandMap implements CommandMap {
public class GeyserCommandMap {
private final Map<String, Command> commandMap = Collections.synchronizedMap(new HashMap<String, Command>());
private final Map<String, GeyserCommand> commandMap = Collections.synchronizedMap(new HashMap<>());
private GeyserConnector connector;
public GeyserCommandMap(GeyserConnector connector) {
@ -52,11 +49,11 @@ public class GeyserCommandMap implements CommandMap {
registerCommand(new StopCommand(connector, "stop", "Shut down Geyser."));
}
public void registerCommand(Command command) {
public void registerCommand(GeyserCommand command) {
commandMap.put(command.getName(), command);
connector.getLogger().debug("Registered command " + command.getName());
if (command.getAliases() == null || command.getAliases().isEmpty())
if (command.getAliases().isEmpty())
return;
for (String alias : command.getAliases())
@ -64,34 +61,33 @@ public class GeyserCommandMap implements CommandMap {
}
public void runCommand(CommandSender sender, String command) {
String trim = command.trim();
String label = null;
String[] args = null;
if (!command.startsWith("geyser "))
return;
if (!trim.contains(" ")) {
label = trim.toLowerCase();
command = command.trim();
command = command.replace("geyser ", "");
String label;
String[] args;
if (!command.contains(" ")) {
label = command.toLowerCase();
args = new String[0];
} else {
label = trim.substring(0, trim.indexOf(" ")).toLowerCase();
String argLine = trim.substring(trim.indexOf(" " + 1));
label = command.substring(0, command.indexOf(" ")).toLowerCase();
String argLine = command.substring(command.indexOf(" " + 1));
args = argLine.contains(" ") ? argLine.split(" ") : new String[] { argLine };
}
if (label == null) {
connector.getLogger().warning("Invalid Command! Try /help for a list of commands.");
return;
}
Command cmd = commandMap.get(label);
GeyserCommand cmd = commandMap.get(label);
if (cmd == null) {
connector.getLogger().warning("Invalid Command! Try /help for a list of commands.");
connector.getLogger().error("Invalid Command! Try /geyser help for a list of commands.");
return;
}
cmd.execute(sender, args);
}
public Map<String, Command> getCommands() {
public Map<String, GeyserCommand> getCommands() {
return commandMap;
}
}

View file

@ -1,49 +0,0 @@
/*
* Copyright (c) 2019-2020 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.command;
import org.geysermc.api.command.ConsoleCommandSender;
import org.geysermc.connector.console.GeyserLogger;
public class GeyserConsoleCommandSender implements ConsoleCommandSender {
@Override
public String getName() {
return "CONSOLE";
}
@Override
public void sendMessage(String message) {
System.out.println(GeyserLogger.printConsole(message, true));
}
@Override
public void sendMessage(String[] messages) {
for (String message : messages) {
sendMessage(message);
}
}
}

View file

@ -25,17 +25,12 @@
package org.geysermc.connector.command.defaults;
import org.geysermc.api.ChatColor;
import org.geysermc.api.command.Command;
import org.geysermc.api.command.CommandSender;
import org.geysermc.common.ChatColor;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.command.CommandSender;
import org.geysermc.connector.command.GeyserCommand;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.*;
public class HelpCommand extends GeyserCommand {
@ -45,19 +40,19 @@ public class HelpCommand extends GeyserCommand {
super(name, description);
this.connector = connector;
this.setAliases(Arrays.asList("?"));
this.setAliases(Collections.singletonList("?"));
}
@Override
public void execute(CommandSender sender, String[] args) {
sender.sendMessage("---- Showing Help For: Geyser (Page 1/1) ----");
Map<String, Command> cmds = connector.getCommandMap().getCommands();
Map<String, GeyserCommand> cmds = connector.getCommandMap().getCommands();
List<String> commands = new ArrayList<String>(cmds.keySet());
List<String> commands = new ArrayList<>(cmds.keySet());
Collections.sort(commands);
for (String cmd : commands) {
sender.sendMessage(ChatColor.YELLOW + "/" + cmd + ChatColor.WHITE + ": " + cmds.get(cmd).getDescription());
sender.sendMessage(ChatColor.YELLOW + "/geyser " + cmd + ChatColor.WHITE + ": " + cmds.get(cmd).getDescription());
}
}
}

View file

@ -25,11 +25,11 @@
package org.geysermc.connector.command.defaults;
import org.geysermc.api.command.CommandSender;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.command.CommandSender;
import org.geysermc.connector.command.GeyserCommand;
import java.util.Arrays;
import java.util.Collections;
public class StopCommand extends GeyserCommand {
@ -39,11 +39,14 @@ public class StopCommand extends GeyserCommand {
super(name, description);
this.connector = connector;
this.setAliases(Arrays.asList("shutdown"));
this.setAliases(Collections.singletonList("shutdown"));
}
@Override
public void execute(CommandSender sender, String[] args) {
if (!sender.isConsole())
return;
connector.shutdown();
}
}

View file

@ -1,38 +0,0 @@
/*
* Copyright (c) 2019 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.configuration;
import lombok.Getter;
@Getter
public class BedrockConfiguration {
private String address;
private int port;
private String motd1;
private String motd2;
}

View file

@ -1,58 +0,0 @@
/*
* Copyright (c) 2019 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.configuration;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import java.util.Map;
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
public class GeyserConfiguration {
private BedrockConfiguration bedrock;
private RemoteConfiguration remote;
private Map<String, UserAuthenticationInfo> userAuths;
@JsonProperty("ping-passthrough")
private boolean pingPassthrough;
@JsonProperty("max-players")
private int maxPlayers;
@JsonProperty("debug-mode")
private boolean debugMode;
@JsonProperty("general-thread-pool")
private int generalThreadPool;
@JsonProperty("allow-third-party-capes")
private boolean allowThirdPartyCapes;
private MetricInfo metrics;
}

View file

@ -1,38 +0,0 @@
/*
* Copyright (c) 2019 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
@Getter
public class MetricInfo {
private boolean enabled;
@JsonProperty("uuid")
private String UUID;
}

View file

@ -1,42 +0,0 @@
/*
* Copyright (c) 2019 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.configuration;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
@Getter
public class RemoteConfiguration {
private String address;
private int port;
private String motd1;
private String motd2;
@JsonProperty("auth-type")
private String authType;
}

View file

@ -1,31 +0,0 @@
/*
* Copyright (c) 2019 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.configuration;
public class UserAuthenticationInfo {
public String email;
public String password;
}

View file

@ -1,98 +0,0 @@
/*
* Copyright (c) 2019-2020 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.console;
import org.geysermc.api.command.ConsoleCommandSender;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.command.GeyserConsoleCommandSender;
import net.minecrell.terminalconsole.TerminalConsoleAppender;
import org.jline.reader.EndOfFileException;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.reader.UserInterruptException;
import org.jline.terminal.Terminal;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ConsoleCommandReader {
private GeyserConnector connector;
private Terminal terminal;
private Thread thread;
public ConsoleCommandReader(GeyserConnector connector) {
this.connector = connector;
this.terminal = TerminalConsoleAppender.getTerminal();
}
public void startConsole() {
thread = new Thread(() -> {
if (terminal != null) {
LineReader lineReader = LineReaderBuilder.builder()
.appName("Geyser")
.terminal(terminal)
.build();
TerminalConsoleAppender.setReader(lineReader);
try {
String line;
while (true) {
try {
line = lineReader.readLine("> ");
} catch (EndOfFileException ignored) {
continue;
}
if (line == null)
break;
}
} catch (UserInterruptException e /* do nothing */) {
//
} finally {
TerminalConsoleAppender.setReader(null);
}
} else {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
String line;
while ((line = reader.readLine()) != null) {
ConsoleCommandSender sender = new GeyserConsoleCommandSender();
connector.getCommandMap().runCommand(sender, line);
}
} catch (IOException ex) {
Logger.getLogger("Geyser").log(Level.SEVERE, null, ex);
}
}
});
thread.setName("ConsoleCommandThread");
connector.getGeneralThreadPool().execute(thread);
}
}

View file

@ -1,135 +0,0 @@
/*
* Copyright (c) 2019-2020 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.console;
import io.sentry.Sentry;
import org.geysermc.api.ChatColor;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.logging.*;
public class GeyserLogger implements org.geysermc.api.logger.Logger {
private boolean colored = true;
private boolean debug = false;
public static final GeyserLogger DEFAULT = new GeyserLogger();
private GeyserLogger() {
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.INFO);
consoleHandler.setFormatter(new SimpleFormatter() {
private static final String format = "[%1$tT][%2$-5s] %3$s %n";
@Override
public synchronized String format(LogRecord lr) {
return String.format(format,
new Date(lr.getMillis()),
lr.getLevel().getLocalizedName(),
lr.getMessage()
);
}
});
try {
File logDir = new File("logs");
logDir.mkdir();
File logFile = new File(logDir, "latest.log");
int maxLogFileSize = 20;//Mo
if (logFile.exists() && (logFile.length()) > maxLogFileSize * 1024L * 1024L)
this.warning("Your log file is larger than " + maxLogFileSize + "Mo, you should backup and clean it !");
FileHandler fileHandler = new FileHandler(logFile.getCanonicalPath(), true);
fileHandler.setLevel(Level.INFO);
fileHandler.setFormatter(new SimpleFormatter() {
private static final String format = "[%1$tF %1$tT][%2$-5s] %3$s %n";
@Override
public synchronized String format(LogRecord lr) {
return String.format(format,
new Date(lr.getMillis()),
lr.getLevel().getLocalizedName(),
lr.getMessage()
);
}
});
} catch (IOException | SecurityException ex) {
Logger.getLogger(GeyserLogger.class.getName()).log(Level.SEVERE, null, ex);
}
if (System.getenv().containsKey("DP_SENTRY_CLIENT_KEY")) {
Handler sentryHandler = new io.sentry.jul.SentryHandler();
sentryHandler.setLevel(Level.SEVERE);
Sentry.init(System.getenv().get("DP_SENTRY_CLIENT_KEY"));
}
}
@Override
public void severe(String message) {
System.out.println(printConsole(ChatColor.DARK_RED + message, colored));
}
@Override
public void severe(String message, Throwable error) {
System.out.println(printConsole(ChatColor.DARK_RED + message + "\n" + error.getMessage(), colored));
}
@Override
public void error(String message) {
System.out.println(printConsole(ChatColor.RED + message, colored));
}
@Override
public void error(String message, Throwable error) {
System.out.println(printConsole(ChatColor.RED + message + "\n" + error, colored));
}
@Override
public void warning(String message) {
System.out.println(printConsole(ChatColor.YELLOW + message, colored));
}
@Override
public void info(String message) {
System.out.println(printConsole(ChatColor.WHITE + message, colored));
}
@Override
public void debug(String message) {
if (debug)
System.out.println(printConsole(ChatColor.GRAY + message, colored));
}
public static String printConsole(String message, boolean colors) {
return colors ? ChatColor.toANSI(message + ChatColor.RESET) : ChatColor.stripColors(message + ChatColor.RESET);
}
@Override
public void setDebug(boolean debug) {
this.debug = debug;
}
}

View file

@ -34,11 +34,13 @@ import com.nukkitx.protocol.bedrock.data.EntityDataMap;
import com.nukkitx.protocol.bedrock.data.EntityFlag;
import com.nukkitx.protocol.bedrock.data.EntityFlags;
import com.nukkitx.protocol.bedrock.packet.*;
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
import it.unimi.dsi.fastutil.longs.LongSet;
import lombok.Getter;
import lombok.Setter;
import org.geysermc.connector.console.GeyserLogger;
import org.geysermc.connector.entity.attribute.Attribute;
import org.geysermc.connector.entity.attribute.AttributeType;
import org.geysermc.connector.entity.type.EntityType;
@ -114,7 +116,7 @@ public class Entity {
valid = true;
session.getUpstream().sendPacket(addEntityPacket);
GeyserLogger.DEFAULT.debug("Spawned entity " + entityType + " at location " + position + " with id " + geyserId + " (java id " + entityId + ")");
session.getConnector().getLogger().debug("Spawned entity " + entityType + " at location " + position + " with id " + geyserId + " (java id " + entityId + ")");
}
/**

View file

@ -27,10 +27,11 @@ package org.geysermc.connector.entity;
import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.packet.AddPaintingPacket;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.geysermc.connector.console.GeyserLogger;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.utils.PaintingType;
@ -58,7 +59,7 @@ public class PaintingEntity extends Entity {
valid = true;
GeyserLogger.DEFAULT.debug("Spawned painting on " + position);
session.getConnector().getLogger().debug("Spawned painting on " + position);
}
public Vector3f fixOffset(boolean toBedrock) {

View file

@ -32,9 +32,11 @@ import com.nukkitx.protocol.bedrock.data.PlayerPermission;
import com.nukkitx.protocol.bedrock.packet.AddPlayerPacket;
import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;
import com.nukkitx.protocol.bedrock.packet.PlayerListPacket;
import lombok.Getter;
import lombok.Setter;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.utils.SkinUtils;
@ -108,7 +110,7 @@ public class PlayerEntity extends LivingEntity {
if (!playerList) {
// remove from playerlist if player isn't on playerlist
Geyser.getGeneralThreadPool().execute(() -> {
GeyserConnector.getInstance().getGeneralThreadPool().execute(() -> {
PlayerListPacket playerList = new PlayerListPacket();
playerList.setAction(PlayerListPacket.Action.REMOVE);
playerList.getEntries().add(new PlayerListPacket.Entry(uuid));

View file

@ -27,7 +27,6 @@ package org.geysermc.connector.metrics;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import javax.net.ssl.HttpsURLConnection;
@ -72,15 +71,19 @@ public class Metrics {
// A list with all custom charts
private final List<CustomChart> charts = new ArrayList<>();
private GeyserConnector connector;
/**
* Class constructor.
*
* @param connector The GeyserConnector instance
* @param name The name of the server software.
* @param serverUUID The uuid of the server.
* @param logFailedRequests Whether failed requests should be logged or not.
* @param logger The logger for the failed requests.
*/
public Metrics(String name, String serverUUID, boolean logFailedRequests, Logger logger) {
public Metrics(GeyserConnector connector, String name, String serverUUID, boolean logFailedRequests, Logger logger) {
this.connector = connector;
this.name = name;
this.serverUUID = serverUUID;
Metrics.logFailedRequests = logFailedRequests;
@ -106,7 +109,7 @@ public class Metrics {
* Starts the Scheduler which submits our data every 30 minutes.
*/
private void startSubmitting() {
Geyser.getGeneralThreadPool().scheduleAtFixedRate(this::submitData, 1, 30, TimeUnit.MINUTES);
connector.getGeneralThreadPool().scheduleAtFixedRate(this::submitData, 1, 30, TimeUnit.MINUTES);
// Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start
// WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted!
// WARNING: Just don't do it!
@ -144,7 +147,7 @@ public class Metrics {
*/
private JsonObject getServerData() {
// OS specific data
int playerAmount = Geyser.getPlayerCount();
int playerAmount = connector.getPlayers().size();
String osName = System.getProperty("os.name");
String osArch = System.getProperty("os.arch");

View file

@ -29,11 +29,9 @@ import com.github.steveice10.mc.protocol.data.status.ServerStatusInfo;
import com.nukkitx.protocol.bedrock.BedrockPong;
import com.nukkitx.protocol.bedrock.BedrockServerEventHandler;
import com.nukkitx.protocol.bedrock.BedrockServerSession;
import org.geysermc.api.Player;
import org.geysermc.api.events.PingEvent;
import org.geysermc.common.IGeyserConfiguration;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.configuration.GeyserConfiguration;
import org.geysermc.connector.console.GeyserLogger;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.utils.MessageUtils;
@ -49,50 +47,35 @@ public class ConnectorServerEventHandler implements BedrockServerEventHandler {
@Override
public boolean onConnectionRequest(InetSocketAddress inetSocketAddress) {
GeyserLogger.DEFAULT.info(inetSocketAddress + " tried to connect!");
connector.getLogger().info(inetSocketAddress + " tried to connect!");
return true;
}
@Override
public BedrockPong onQuery(InetSocketAddress inetSocketAddress) {
GeyserLogger.DEFAULT.debug(inetSocketAddress + " has pinged you!");
GeyserConfiguration config = connector.getConfig();
PingEvent pongEvent = new PingEvent(inetSocketAddress);
pongEvent.setEdition("MCPE");
pongEvent.setGameType("Default");
pongEvent.setNintendoLimited(false);
pongEvent.setProtocolVersion(GeyserConnector.BEDROCK_PACKET_CODEC.getProtocolVersion());
pongEvent.setVersion(GeyserConnector.BEDROCK_PACKET_CODEC.getMinecraftVersion());
connector.getLogger().debug(inetSocketAddress + " has pinged you!");
connector.getPluginManager().runEvent(pongEvent);
if (connector.getConfig().isPingPassthrough()) {
ServerStatusInfo serverInfo = connector.getPassthroughThread().getInfo();
if (serverInfo != null) {
pongEvent.setMotd(MessageUtils.getBedrockMessage(serverInfo.getDescription()));
pongEvent.setSubMotd(config.getBedrock().getMotd2());
pongEvent.setPlayerCount(serverInfo.getPlayerInfo().getOnlinePlayers());
pongEvent.setMaximumPlayerCount(serverInfo.getPlayerInfo().getMaxPlayers());
}
} else {
pongEvent.setPlayerCount(1);
pongEvent.setMaximumPlayerCount(config.getMaxPlayers());
pongEvent.setMotd(config.getBedrock().getMotd1());
pongEvent.setSubMotd(config.getBedrock().getMotd2());
}
IGeyserConfiguration config = connector.getConfig();
ServerStatusInfo serverInfo = connector.getPassthroughThread().getInfo();
BedrockPong pong = new BedrockPong();
pong.setEdition(pongEvent.getEdition());
pong.setGameType(pongEvent.getGameType());
pong.setNintendoLimited(pongEvent.isNintendoLimited());
pong.setProtocolVersion(pongEvent.getProtocolVersion());
pong.setVersion(pongEvent.getVersion());
pong.setMotd(pongEvent.getMotd());
pong.setSubMotd(pongEvent.getSubMotd());
pong.setPlayerCount(pongEvent.getPlayerCount());
pong.setMaximumPlayerCount(pongEvent.getMaximumPlayerCount());
pong.setEdition("MCPE");
pong.setGameType("Default");
pong.setNintendoLimited(false);
pong.setProtocolVersion(GeyserConnector.BEDROCK_PACKET_CODEC.getProtocolVersion());
pong.setVersion(GeyserConnector.BEDROCK_PACKET_CODEC.getMinecraftVersion());
pong.setIpv4Port(config.getBedrock().getPort());
if (connector.getConfig().isPingPassthrough() && serverInfo != null) {
pong.setMotd(MessageUtils.getBedrockMessage(serverInfo.getDescription()));
pong.setSubMotd(config.getBedrock().getMotd2());
pong.setPlayerCount(serverInfo.getPlayerInfo().getOnlinePlayers());
pong.setMaximumPlayerCount(serverInfo.getPlayerInfo().getMaxPlayers());
} else {
pong.setPlayerCount(connector.getPlayers().size());
pong.setMaximumPlayerCount(config.getMaxPlayers());
pong.setMotd(config.getBedrock().getMotd1());
pong.setMotd(config.getBedrock().getMotd2());
}
return pong;
}
@ -101,7 +84,7 @@ public class ConnectorServerEventHandler implements BedrockServerEventHandler {
bedrockServerSession.setLogging(true);
bedrockServerSession.setPacketHandler(new UpstreamPacketHandler(connector, new GeyserSession(connector, bedrockServerSession)));
bedrockServerSession.addDisconnectHandler(disconnectReason -> {
GeyserLogger.DEFAULT.info("Bedrock user with ip: " + bedrockServerSession.getAddress().getAddress() + " has disconnected for reason " + disconnectReason);
connector.getLogger().info("Bedrock user with ip: " + bedrockServerSession.getAddress().getAddress() + " has disconnected for reason " + disconnectReason);
GeyserSession player = connector.getPlayers().get(bedrockServerSession.getAddress());
if (player != null) {

View file

@ -27,8 +27,8 @@ package org.geysermc.connector.network;
import com.nukkitx.protocol.bedrock.BedrockPacket;
import com.nukkitx.protocol.bedrock.packet.*;
import org.geysermc.common.IGeyserConfiguration;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.configuration.UserAuthenticationInfo;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.Registry;
import org.geysermc.connector.utils.LoginEncryptionUtils;
@ -66,7 +66,7 @@ public class UpstreamPacketHandler extends LoggingPacketHandler {
switch (packet.getStatus()) {
case COMPLETED:
session.connect(connector.getRemoteServer());
connector.getLogger().info("Player connected with username " + session.getAuthenticationData().getName());
connector.getLogger().info("Player connected with username " + session.getAuthData().getName());
break;
case HAVE_ALL_PACKS:
ResourcePackStackPacket stack = new ResourcePackStackPacket();
@ -90,11 +90,11 @@ public class UpstreamPacketHandler extends LoggingPacketHandler {
private boolean couldLoginUserByName(String bedrockUsername) {
if (connector.getConfig().getUserAuths() != null) {
UserAuthenticationInfo info = connector.getConfig().getUserAuths().get(bedrockUsername);
IGeyserConfiguration.IUserAuthenticationInfo info = connector.getConfig().getUserAuths().get(bedrockUsername);
if (info != null) {
connector.getLogger().info("using stored credentials for bedrock user " + session.getAuthenticationData().getName());
session.authenticate(info.email, info.password);
connector.getLogger().info("using stored credentials for bedrock user " + session.getAuthData().getName());
session.authenticate(info.getEmail(), info.getPassword());
// TODO send a message to bedrock user telling them they are connected (if nothing like a motd
// somes from the Java server w/in a few seconds)
@ -109,7 +109,7 @@ public class UpstreamPacketHandler extends LoggingPacketHandler {
public boolean handle(MovePlayerPacket packet) {
if (!session.isLoggedIn() && !session.isLoggingIn()) {
// TODO it is safer to key authentication on something that won't change (UUID, not username)
if (!couldLoginUserByName(session.getAuthenticationData().getName())) {
if (!couldLoginUserByName(session.getAuthData().getName())) {
LoginEncryptionUtils.showLoginWindow(session);
}
// else we were able to log the user in
@ -126,9 +126,4 @@ public class UpstreamPacketHandler extends LoggingPacketHandler {
boolean defaultHandler(BedrockPacket packet) {
return translateAndDefault(packet);
}
@Override
public boolean handle(InventoryTransactionPacket packet) {
return translateAndDefault(packet);
}
}

View file

@ -27,11 +27,10 @@ package org.geysermc.connector.network.remote;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.geysermc.api.RemoteServer;
@Getter
@AllArgsConstructor
public class RemoteJavaServer implements RemoteServer {
public class RemoteServer {
private String address;
private int port;

View file

@ -30,11 +30,9 @@ import com.github.steveice10.mc.auth.exception.request.RequestException;
import com.github.steveice10.mc.protocol.MinecraftProtocol;
import com.github.steveice10.mc.protocol.data.game.entity.player.GameMode;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerRespawnPacket;
import com.github.steveice10.mc.protocol.packet.handshake.client.HandshakePacket;
import com.github.steveice10.packetlib.Client;
import com.github.steveice10.packetlib.event.session.ConnectedEvent;
import com.github.steveice10.packetlib.event.session.DisconnectedEvent;
import com.github.steveice10.packetlib.event.session.PacketReceivedEvent;
import com.github.steveice10.packetlib.event.session.SessionAdapter;
import com.github.steveice10.packetlib.event.session.*;
import com.github.steveice10.packetlib.packet.Packet;
import com.github.steveice10.packetlib.tcp.TcpSessionFactory;
import com.nukkitx.math.GenericMath;
@ -49,33 +47,44 @@ import com.nukkitx.protocol.bedrock.data.GamePublishSetting;
import com.nukkitx.protocol.bedrock.data.GameRuleData;
import com.nukkitx.protocol.bedrock.data.PlayerPermission;
import com.nukkitx.protocol.bedrock.packet.*;
import lombok.Getter;
import lombok.Setter;
import org.geysermc.api.Player;
import org.geysermc.api.RemoteServer;
import org.geysermc.api.session.AuthData;
import org.geysermc.api.window.FormWindow;
import org.geysermc.common.AuthType;
import org.geysermc.common.window.FormWindow;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.command.CommandSender;
import org.geysermc.connector.entity.PlayerEntity;
import org.geysermc.connector.inventory.PlayerInventory;
import org.geysermc.connector.network.remote.RemoteServer;
import org.geysermc.connector.network.session.auth.AuthData;
import org.geysermc.connector.network.session.auth.BedrockClientData;
import org.geysermc.connector.network.session.cache.*;
import org.geysermc.connector.network.translators.Registry;
import org.geysermc.connector.network.translators.block.BlockTranslator;
import org.geysermc.connector.utils.ChunkUtils;
import org.geysermc.connector.utils.Toolbox;
import org.geysermc.floodgate.util.BedrockData;
import org.geysermc.floodgate.util.EncryptionUtil;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
@Getter
public class GeyserSession implements Player {
public class GeyserSession implements CommandSender {
private final GeyserConnector connector;
private final UpstreamSession upstream;
private RemoteServer remoteServer;
private Client downstream;
private AuthData authenticationData;
@Setter private AuthData authData;
@Setter private BedrockClientData clientData;
private PlayerEntity playerEntity;
private PlayerInventory inventory;
@ -139,9 +148,14 @@ public class GeyserSession implements Player {
public void connect(RemoteServer remoteServer) {
startGame();
this.remoteServer = remoteServer;
if (!(connector.getConfig().getRemote().getAuthType().hashCode() == "online".hashCode())) {
connector.getLogger().info("Attempting to login using offline mode... authentication is disabled.");
authenticate(authenticationData.getName());
if (connector.getAuthType() != AuthType.ONLINE) {
connector.getLogger().info(
"Attempting to login using " + connector.getAuthType().name().toLowerCase() + " mode... " +
(connector.getAuthType() == AuthType.OFFLINE ?
"authentication is disabled." : "authentication will be encrypted"
)
);
authenticate(authData.getName());
}
ChunkUtils.sendEmptyChunks(this, playerEntity.getPosition().toInt(), 0, false);
@ -185,14 +199,62 @@ public class GeyserSession implements Player {
protocol = new MinecraftProtocol(username);
}
boolean floodgate = connector.getAuthType() == AuthType.FLOODGATE;
final PublicKey publicKey;
if (floodgate) {
PublicKey key = null;
try {
key = EncryptionUtil.getKeyFromFile(
connector.getConfig().getFloodgateKeyFile(),
PublicKey.class
);
} catch (IOException | InvalidKeySpecException | NoSuchAlgorithmException e) {
connector.getLogger().error("Error while reading Floodgate key file", e);
}
publicKey = key;
} else publicKey = null;
if (publicKey != null) {
connector.getLogger().info("Loaded Floodgate key!");
}
downstream = new Client(remoteServer.getAddress(), remoteServer.getPort(), protocol, new TcpSessionFactory());
downstream.getSession().addListener(new SessionAdapter() {
@Override
public void packetSending(PacketSendingEvent event) {
//todo move this somewhere else
if (event.getPacket() instanceof HandshakePacket && floodgate) {
String encrypted = "";
try {
encrypted = EncryptionUtil.encryptBedrockData(publicKey, new BedrockData(
clientData.getGameVersion(),
authData.getName(),
authData.getXboxUUID(),
clientData.getDeviceOS().ordinal(),
clientData.getLanguageCode(),
clientData.getCurrentInputMode().ordinal(),
upstream.getSession().getAddress().getAddress().getHostAddress()
));
} catch (Exception e) {
connector.getLogger().error("Failed to encrypt message", e);
}
HandshakePacket handshakePacket = event.getPacket();
event.setPacket(new HandshakePacket(
handshakePacket.getProtocolVersion(),
handshakePacket.getHostname() + '\0' + BedrockData.FLOODGATE_IDENTIFIER + '\0' + encrypted,
handshakePacket.getPort(),
handshakePacket.getIntent()
));
}
}
@Override
public void connected(ConnectedEvent event) {
loggingIn = false;
loggedIn = true;
connector.getLogger().info(authenticationData.getName() + " (logged in as: " + protocol.getProfile().getName() + ")" + " has connected to remote java server on address " + remoteServer.getAddress());
connector.getLogger().info(authData.getName() + " (logged in as: " + protocol.getProfile().getName() + ")" + " has connected to remote java server on address " + remoteServer.getAddress());
playerEntity.setUuid(protocol.getProfile().getId());
playerEntity.setUsername(protocol.getProfile().getName());
}
@ -201,7 +263,7 @@ public class GeyserSession implements Player {
public void disconnected(DisconnectedEvent event) {
loggingIn = false;
loggedIn = false;
connector.getLogger().info(authenticationData.getName() + " has disconnected from remote java server on address " + remoteServer.getAddress() + " because of " + event.getReason());
connector.getLogger().info(authData.getName() + " has disconnected from remote java server on address " + remoteServer.getAddress() + " because of " + event.getReason());
upstream.disconnect(event.getReason());
}
@ -245,21 +307,17 @@ public class GeyserSession implements Player {
closed = true;
}
public boolean isClosed() {
return closed;
}
public void close() {
disconnect("Server closed.");
}
public void setAuthenticationData(AuthData authData) {
authenticationData = authData;
this.authData = authData;
}
@Override
public String getName() {
return authenticationData.getName();
return authData.getName();
}
@Override
@ -276,10 +334,8 @@ public class GeyserSession implements Player {
}
@Override
public void sendMessage(String[] messages) {
for (String message : messages) {
sendMessage(message);
}
public boolean isConsole() {
return false;
}
public void sendForm(FormWindow window, int id) {
@ -296,7 +352,6 @@ public class GeyserSession implements Player {
upstream.sendPacket(chunkRadiusUpdatedPacket);
}
@Override
public InetSocketAddress getSocketAddress() {
return this.upstream.getAddress();
}

View file

@ -2,13 +2,12 @@ package org.geysermc.connector.network.session.auth;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.geysermc.api.session.AuthData;
import java.util.UUID;
@Getter
@AllArgsConstructor
public class BedrockAuthData implements AuthData {
public class AuthData {
private String name;
private UUID UUID;

View file

@ -0,0 +1,92 @@
package org.geysermc.connector.network.session.auth;
import com.fasterxml.jackson.annotation.JsonEnumDefaultValue;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import java.util.UUID;
@JsonIgnoreProperties(ignoreUnknown = true)
@Getter
public class BedrockClientData {
@JsonProperty(value = "GameVersion")
private String gameVersion;
@JsonProperty(value = "ServerAddress")
private String serverAddress;
@JsonProperty(value = "ThirdPartyName")
private String username;
@JsonProperty(value = "LanguageCode")
private String languageCode;
@JsonProperty(value = "SkinId")
private String skinId;
@JsonProperty(value = "SkinData")
private String skinData;
@JsonProperty(value = "CapeId")
private String capeId;
@JsonProperty(value = "CapeData")
private byte[] capeData;
@JsonProperty(value = "CapeOnClassicSkin")
private boolean capeOnClassicSkin;
@JsonProperty(value = "SkinResourcePatch")
private String geometryName;
@JsonProperty(value = "SkinGeometryData")
private String geometryData;
@JsonProperty(value = "PremiumSkin")
private boolean premiumSkin;
@JsonProperty(value = "DeviceId")
private String deviceId;
@JsonProperty(value = "DeviceModel")
private String deviceModel;
@JsonProperty(value = "DeviceOS")
private DeviceOS deviceOS;
@JsonProperty(value = "UIProfile")
private UIProfile uiProfile;
@JsonProperty(value = "GuiScale")
private int guiScale;
@JsonProperty(value = "CurrentInputMode")
private InputMode currentInputMode;
@JsonProperty(value = "DefaultInputMode")
private InputMode defaultInputMode;
@JsonProperty("PlatformOnlineId")
private String platformOnlineId;
@JsonProperty(value = "PlatformOfflineId")
private String platformOfflineId;
@JsonProperty(value = "SelfSignedId")
private UUID selfSignedId;
@JsonProperty(value = "ClientRandomId")
private long clientRandomId;
public enum UIProfile {
@JsonEnumDefaultValue
CLASSIC,
POCKET
}
public enum DeviceOS {
@JsonEnumDefaultValue
UNKOWN,
ANDROID,
IOS,
OSX,
FIREOS,
GEARVR,
HOLOLENS,
WIN10,
WIN32,
DEDICATED,
ORBIS,
NX,
SWITCH
}
public enum InputMode {
@JsonEnumDefaultValue
UNKNOWN,
KEYBOARD_MOUSE,
TOUCH, // I guess Touch?
CONTROLLER
}
}

View file

@ -26,14 +26,14 @@
package org.geysermc.connector.network.session.cache;
import com.nukkitx.protocol.bedrock.packet.ModalFormRequestPacket;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import lombok.Getter;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.api.window.FormWindow;
import java.util.HashMap;
import java.util.Map;
import lombok.Getter;
import org.geysermc.common.window.FormWindow;
import org.geysermc.connector.network.session.GeyserSession;
public class WindowCache {

View file

@ -27,7 +27,7 @@ package org.geysermc.connector.network.translators;
import com.github.steveice10.packetlib.packet.Packet;
import com.nukkitx.protocol.bedrock.BedrockPacket;
import org.geysermc.connector.console.GeyserLogger;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.network.session.GeyserSession;
import java.util.HashMap;
@ -55,7 +55,7 @@ public class Registry<T> {
return true;
}
} catch (Throwable ex) {
GeyserLogger.DEFAULT.error("Could not translate packet " + packet.getClass().getSimpleName(), ex);
GeyserConnector.getInstance().getLogger().error("Could not translate packet " + packet.getClass().getSimpleName(), ex);
ex.printStackTrace();
}
}

View file

@ -36,6 +36,7 @@ import com.github.steveice10.mc.protocol.packet.ingame.server.scoreboard.ServerT
import com.github.steveice10.mc.protocol.packet.ingame.server.scoreboard.ServerUpdateScorePacket;
import com.github.steveice10.mc.protocol.packet.ingame.server.window.*;
import com.github.steveice10.mc.protocol.packet.ingame.server.world.*;
import com.github.steveice10.mc.protocol.packet.login.server.LoginPluginRequestPacket;
import com.nukkitx.nbt.CompoundTagBuilder;
import com.nukkitx.nbt.NbtUtils;
import com.nukkitx.nbt.stream.NBTOutputStream;
@ -91,6 +92,8 @@ public class TranslatorsInit {
}
public static void start() {
Registry.registerJava(LoginPluginRequestPacket.class, new JavaLoginPluginMessageTranslator());
Registry.registerJava(ServerJoinGamePacket.class, new JavaJoinGameTranslator());
Registry.registerJava(ServerPluginMessagePacket.class, new JavaPluginMessageTranslator());
Registry.registerJava(ServerChatPacket.class, new JavaChatTranslator());

View file

@ -27,7 +27,8 @@ package org.geysermc.connector.network.translators.bedrock;
import com.github.steveice10.mc.protocol.packet.ingame.client.ClientChatPacket;
import com.nukkitx.protocol.bedrock.packet.CommandRequestPacket;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
@ -36,8 +37,8 @@ public class BedrockCommandRequestTranslator extends PacketTranslator<CommandReq
@Override
public void translate(CommandRequestPacket packet, GeyserSession session) {
String command = packet.getCommand().replace("/", "");
if (Geyser.getConnector().getCommandMap().getCommands().containsKey(command)) {
Geyser.getConnector().getCommandMap().runCommand(session, command);
if (GeyserConnector.getInstance().getCommandMap().getCommands().containsKey(command)) {
GeyserConnector.getInstance().getCommandMap().runCommand(session, command);
} else {
ClientChatPacket chatPacket = new ClientChatPacket(packet.getCommand());
session.getDownstream().getSession().send(chatPacket);

View file

@ -31,7 +31,8 @@ import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.packet.MoveEntityAbsolutePacket;
import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;
import com.nukkitx.protocol.bedrock.packet.SetEntityDataPacket;
import org.geysermc.api.ChatColor;
import org.geysermc.common.ChatColor;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.PlayerEntity;
import org.geysermc.connector.entity.type.EntityType;

View file

@ -26,6 +26,8 @@
package org.geysermc.connector.network.translators.bedrock;
import com.nukkitx.protocol.bedrock.packet.SetLocalPlayerAsInitializedPacket;
import org.geysermc.common.AuthType;
import org.geysermc.connector.entity.PlayerEntity;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;

View file

@ -35,7 +35,7 @@ import com.nukkitx.nbt.tag.ListTag;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import it.unimi.dsi.fastutil.ints.*;
import org.geysermc.connector.console.GeyserLogger;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.utils.Toolbox;
import java.io.InputStream;
@ -114,7 +114,7 @@ public class BlockTranslator {
} else {
int duplicateRuntimeId = addedStatesMap.get(blockTag);
if (duplicateRuntimeId == -1) {
GeyserLogger.DEFAULT.debug("Mapping " + javaId + " was not found for bedrock edition!");
GeyserConnector.getInstance().getLogger().debug("Mapping " + javaId + " was not found for bedrock edition!");
} else {
JAVA_TO_BEDROCK_BLOCK_MAP.put(javaRuntimeId, duplicateRuntimeId);
}

View file

@ -41,8 +41,8 @@ import com.github.steveice10.opennbt.tag.builtin.ShortTag;
import com.github.steveice10.opennbt.tag.builtin.StringTag;
import com.github.steveice10.opennbt.tag.builtin.Tag;
import com.nukkitx.protocol.bedrock.data.ItemData;
import org.geysermc.api.Geyser;
import org.geysermc.connector.console.GeyserLogger;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.utils.MessageUtils;
import org.geysermc.connector.utils.Toolbox;
@ -88,7 +88,7 @@ public class ItemTranslator {
if (potion != null) {
return ItemData.of(bedrockItem.getBedrockId(), potion.getBedrockId(), stack.getAmount(), translateToBedrockNBT(stack.getNbt()));
}
Geyser.getLogger().debug("Unknown java potion: " + potionTag.getValue());
GeyserConnector.getInstance().getLogger().debug("Unknown java potion: " + potionTag.getValue());
}
}
return ItemData.of(bedrockItem.getBedrockId(), (short) bedrockItem.getBedrockData(), stack.getAmount(), translateToBedrockNBT(stack.getNbt()));
@ -105,7 +105,7 @@ public class ItemTranslator {
}
}
GeyserLogger.DEFAULT.debug("Missing mapping for bedrock item " + data.getId() + ":" + data.getDamage());
GeyserConnector.getInstance().getLogger().debug("Missing mapping for bedrock item " + data.getId() + ":" + data.getDamage());
return ItemEntry.AIR;
}
@ -199,7 +199,7 @@ public class ItemTranslator {
javaTag.setValue(javaValue);
tags.add(javaTag);
} else {
Geyser.getLogger().debug("Unknown bedrock enchantment: " + bedrockId);
GeyserConnector.getInstance().getLogger().debug("Unknown bedrock enchantment: " + bedrockId);
}
}
return new ListTag("Enchantments", tags);
@ -310,7 +310,7 @@ public class ItemTranslator {
Enchantment enchantment = Enchantment.getByJavaIdentifier(((StringTag) javaEnchId).getValue());
if (enchantment == null) {
Geyser.getLogger().debug("Unknown java enchantment: " + javaEnchId.getValue());
GeyserConnector.getInstance().getLogger().debug("Unknown java enchantment: " + javaEnchId.getValue());
continue;
}

View file

@ -28,6 +28,7 @@ package org.geysermc.connector.network.translators.java;
import com.github.steveice10.mc.protocol.data.message.TranslationMessage;
import com.github.steveice10.mc.protocol.packet.ingame.server.ServerChatPacket;
import com.nukkitx.protocol.bedrock.packet.TextPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.utils.MessageUtils;
@ -39,7 +40,7 @@ public class JavaChatTranslator extends PacketTranslator<ServerChatPacket> {
TextPacket textPacket = new TextPacket();
textPacket.setPlatformChatId("");
textPacket.setSourceName("");
textPacket.setXuid(session.getAuthenticationData().getXboxUUID());
textPacket.setXuid(session.getAuthData().getXboxUUID());
switch (packet.getType()) {
case CHAT:
textPacket.setType(TextPacket.Type.CHAT);

View file

@ -0,0 +1,16 @@
package org.geysermc.connector.network.translators.java;
import com.github.steveice10.mc.protocol.packet.login.client.LoginPluginResponsePacket;
import com.github.steveice10.mc.protocol.packet.login.server.LoginPluginRequestPacket;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
public class JavaLoginPluginMessageTranslator extends PacketTranslator<LoginPluginRequestPacket> {
@Override
public void translate(LoginPluginRequestPacket packet, GeyserSession session) {
// A vanilla client doesn't know any PluginMessage in the Login state, so we don't know any either.
session.getDownstream().getSession().send(
new LoginPluginResponsePacket(packet.getMessageId(), null)
);
}
}

View file

@ -31,7 +31,9 @@ import com.nukkitx.math.vector.Vector3f;
import com.nukkitx.protocol.bedrock.data.EntityEventType;
import com.nukkitx.protocol.bedrock.packet.*;
import org.geysermc.connector.console.GeyserLogger;
import com.nukkitx.protocol.bedrock.packet.MovePlayerPacket;
import com.nukkitx.protocol.bedrock.packet.SetEntityDataPacket;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
@ -82,7 +84,7 @@ public class JavaPlayerPositionRotationTranslator extends PacketTranslator<Serve
ClientTeleportConfirmPacket teleportConfirmPacket = new ClientTeleportConfirmPacket(packet.getTeleportId());
session.getDownstream().getSession().send(teleportConfirmPacket);
GeyserLogger.DEFAULT.info("Spawned player at " + packet.getX() + " " + packet.getY() + " " + packet.getZ());
session.getConnector().getLogger().info("Spawned player at " + packet.getX() + " " + packet.getY() + " " + packet.getZ());
return;
}

View file

@ -27,7 +27,7 @@ package org.geysermc.connector.network.translators.java.entity.spawn;
import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnMobPacket;
import com.nukkitx.math.vector.Vector3f;
import org.geysermc.connector.console.GeyserLogger;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
@ -47,7 +47,7 @@ public class JavaSpawnMobTranslator extends PacketTranslator<ServerSpawnMobPacke
EntityType type = EntityUtils.toBedrockEntity(packet.getType());
if (type == null) {
GeyserLogger.DEFAULT.warning("Entity type " + packet.getType() + " was null.");
session.getConnector().getLogger().warning("Entity type " + packet.getType() + " was null.");
return;
}

View file

@ -28,7 +28,7 @@ package org.geysermc.connector.network.translators.java.entity.spawn;
import com.github.steveice10.mc.protocol.data.game.entity.type.object.ObjectType;
import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnObjectPacket;
import com.nukkitx.math.vector.Vector3f;
import org.geysermc.connector.console.GeyserLogger;
import org.geysermc.connector.entity.Entity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
@ -51,7 +51,7 @@ public class JavaSpawnObjectTranslator extends PacketTranslator<ServerSpawnObjec
EntityType type = EntityUtils.toBedrockEntity(packet.getType());
if (type == null) {
GeyserLogger.DEFAULT.warning("Entity type " + packet.getType() + " was null.");
session.getConnector().getLogger().warning("Entity type " + packet.getType() + " was null.");
return;
}

View file

@ -27,7 +27,8 @@ package org.geysermc.connector.network.translators.java.entity.spawn;
import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnPaintingPacket;
import com.nukkitx.math.vector.Vector3f;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.entity.PaintingEntity;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
@ -39,7 +40,7 @@ public class JavaSpawnPaintingTranslator extends PacketTranslator<ServerSpawnPai
public void translate(ServerSpawnPaintingPacket packet, GeyserSession session) {
Vector3f position = Vector3f.from(packet.getPosition().getX(), packet.getPosition().getY(), packet.getPosition().getZ());
Geyser.getGeneralThreadPool().execute(() -> { // #slowdownbrother, just don't execute it directly
GeyserConnector.getInstance().getGeneralThreadPool().execute(() -> { // #slowdownbrother, just don't execute it directly
PaintingEntity entity = new PaintingEntity(
packet.getEntityId(),
session.getEntityCache().getNextEntityId().incrementAndGet(),

View file

@ -27,7 +27,8 @@ package org.geysermc.connector.network.translators.java.entity.spawn;
import com.github.steveice10.mc.protocol.packet.ingame.server.entity.spawn.ServerSpawnPlayerPacket;
import com.nukkitx.math.vector.Vector3f;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.entity.PlayerEntity;
import org.geysermc.connector.entity.type.EntityType;
import org.geysermc.connector.network.session.GeyserSession;
@ -43,7 +44,7 @@ public class JavaSpawnPlayerTranslator extends PacketTranslator<ServerSpawnPlaye
PlayerEntity entity = session.getEntityCache().getPlayerEntity(packet.getUuid());
if (entity == null) {
Geyser.getLogger().error("Haven't received PlayerListEntry packet before spawning player! We ignore the player " + packet.getUuid());
GeyserConnector.getInstance().getLogger().error("Haven't received PlayerListEntry packet before spawning player! We ignore the player " + packet.getUuid());
return;
}

View file

@ -26,7 +26,8 @@
package org.geysermc.connector.network.translators.java.scoreboard;
import com.github.steveice10.mc.protocol.packet.ingame.server.scoreboard.ServerTeamPacket;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.scoreboard.Scoreboard;
@ -41,7 +42,7 @@ public class JavaTeamTranslator extends PacketTranslator<ServerTeamPacket> {
@Override
public void translate(ServerTeamPacket packet, GeyserSession session) {
Geyser.getLogger().debug("Team packet " + packet.getTeamName() + " " + packet.getAction()+" "+ Arrays.toString(packet.getPlayers()));
GeyserConnector.getInstance().getLogger().debug("Team packet " + packet.getTeamName() + " " + packet.getAction()+" "+ Arrays.toString(packet.getPlayers()));
Scoreboard scoreboard = session.getScoreboardCache().getScoreboard();
switch (packet.getAction()) {

View file

@ -27,7 +27,8 @@ package org.geysermc.connector.network.translators.java.scoreboard;
import com.github.steveice10.mc.protocol.data.game.scoreboard.ScoreboardAction;
import com.github.steveice10.mc.protocol.packet.ingame.server.scoreboard.ServerUpdateScorePacket;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
import org.geysermc.connector.scoreboard.Objective;
@ -42,7 +43,7 @@ public class JavaUpdateScoreTranslator extends PacketTranslator<ServerUpdateScor
Objective objective = scoreboard.getObjective(packet.getObjective());
if (objective == null && packet.getAction() != ScoreboardAction.REMOVE) {
Geyser.getLogger().info("Tried to update score without the existence of its requested objective '" + packet.getObjective() + '\'');
GeyserConnector.getInstance().getLogger().info("Tried to update score without the existence of its requested objective '" + packet.getObjective() + '\'');
return;
}

View file

@ -30,7 +30,7 @@ import com.github.steveice10.mc.protocol.packet.ingame.server.window.ServerOpenW
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.nukkitx.protocol.bedrock.packet.ContainerClosePacket;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.inventory.Inventory;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.PacketTranslator;
@ -71,7 +71,7 @@ public class JavaOpenWindowTranslator extends PacketTranslator<ServerOpenWindowP
name = jsonObject.get("translate").getAsString();
}
} catch (Exception e) {
Geyser.getLogger().debug("JavaOpenWindowTranslator: " + e.toString());
GeyserConnector.getInstance().getLogger().debug("JavaOpenWindowTranslator: " + e.toString());
}
Inventory newInventory = new Inventory(name, packet.getWindowId(), packet.getType(), newTranslator.size + 36);
@ -80,7 +80,7 @@ public class JavaOpenWindowTranslator extends PacketTranslator<ServerOpenWindowP
InventoryTranslator openTranslator = TranslatorsInit.getInventoryTranslators().get(openInventory.getWindowType());
if (!openTranslator.getClass().equals(newTranslator.getClass())) {
InventoryUtils.closeInventory(session, openInventory.getId());
Geyser.getGeneralThreadPool().schedule(() -> InventoryUtils.openInventory(session, newInventory), 500, TimeUnit.MILLISECONDS);
GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> InventoryUtils.openInventory(session, newInventory), 500, TimeUnit.MILLISECONDS);
return;
}
}

View file

@ -31,9 +31,11 @@ import com.github.steveice10.mc.protocol.packet.ingame.server.world.ServerChunkD
import com.nukkitx.math.vector.Vector3i;
import com.nukkitx.network.VarInts;
import com.nukkitx.protocol.bedrock.packet.LevelChunkPacket;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.BiomeTranslator;
import org.geysermc.connector.network.translators.PacketTranslator;
@ -45,7 +47,7 @@ public class JavaChunkDataTranslator extends PacketTranslator<ServerChunkDataPac
@Override
public void translate(ServerChunkDataPacket packet, GeyserSession session) {
// Not sure if this is safe or not, however without this the client usually times out
Geyser.getConnector().getGeneralThreadPool().execute(() -> {
GeyserConnector.getInstance().getGeneralThreadPool().execute(() -> {
try {
if (packet.getColumn().getBiomeData() != null) { //Full chunk
ChunkUtils.ChunkData chunkData = ChunkUtils.translateToBedrock(packet.getColumn());

View file

@ -1,126 +0,0 @@
/*
* Copyright (c) 2019 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.plugin;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.nukkitx.protocol.bedrock.handler.BedrockPacketHandler;
import org.geysermc.api.Connector;
import org.geysermc.api.plugin.Plugin;
import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class GeyserPluginLoader extends ClassLoader {
private Connector connector;
public GeyserPluginLoader(Connector connector) {
this.connector = connector;
}
public void loadPlugins() {
File dir = new File("plugins");
if (!dir.exists()) {
dir.mkdir();
}
for (File f : dir.listFiles()) {
if (!f.getName().toLowerCase().endsWith(".jar"))
continue;
try {
ZipFile file = new ZipFile(f);
ZipEntry e = file.getEntry("plugin.yml");
if (e == null || e.isDirectory()) {
connector.getLogger().severe("Plugin " + f.getName() + " has no valid plugin.yml!");
continue;
}
file.stream().forEach((x) -> {
if (x.getName().endsWith(".class")) {
try {
InputStream is = file.getInputStream(x);
byte[] b = new byte[is.available()];
is.read(b);
this.defineClass(x.getName().replace(".class", "").replaceAll("/", "."), b, 0, b.length);
is.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
InputStream is = file.getInputStream(e);
PluginYML yml = mapper.readValue(is, PluginYML.class);
is.close();
Plugin plugin = (Plugin) Class.forName(yml.main, true, this).newInstance();
Class cl = Plugin.class;
Field name = cl.getDeclaredField("name");
name.setAccessible(true);
Field version = cl.getDeclaredField("version");
version.setAccessible(true);
name.set(plugin, yml.name);
version.set(plugin, yml.version);
connector.getLogger().info("Loading plugin " + yml.name + " version " + yml.version);
connector.getPluginManager().loadPlugin(plugin);
} catch (Exception e) {
connector.getLogger().severe("Error loading plugin " + f.getName());
e.printStackTrace();
}
}
for (Plugin plugin : connector.getPluginManager().getPlugins()) {
connector.getPluginManager().enablePlugin(plugin);
}
}
public void loadPlugin(Plugin plugin) {
plugin.onLoad();
}
public void enablePlugin(Plugin plugin) {
plugin.setEnabled(true);
plugin.onEnable();
}
public void disablePlugin(Plugin plugin) {
plugin.setEnabled(false);
plugin.onDisable();
}
}

View file

@ -1,107 +0,0 @@
/*
* Copyright (c) 2019 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.plugin;
import lombok.Getter;
import org.geysermc.api.events.EventHandler;
import org.geysermc.api.events.Listener;
import org.geysermc.api.plugin.Plugin;
import org.geysermc.api.plugin.PluginManager;
import java.awt.*;
import java.lang.reflect.Method;
import java.util.*;
import java.util.List;
public class GeyserPluginManager implements PluginManager {
private final List<PluginListener> EVENTS = new ArrayList<>();
@Getter
private GeyserPluginLoader loader;
private Map<String, Plugin> plugins = new HashMap<>();
public GeyserPluginManager(GeyserPluginLoader loader) {
this.loader = loader;
}
public void loadPlugin(Plugin plugin) {
loader.loadPlugin(plugin);
plugins.put(plugin.getName(), plugin);
}
public void unloadPlugin(Plugin plugin) {
plugins.remove(plugin);
}
public void enablePlugin(Plugin plugin) {
loader.enablePlugin(plugin);
}
public void disablePlugin(Plugin plugin) {
loader.disablePlugin(plugin);
}
public Set<Plugin> getPlugins() {
return new HashSet<>(plugins.values());
}
@Override
public void registerEventListener(Plugin p, Listener l) {
try {
Class<? extends Listener> clazz = l.getClass();
for(Method m : clazz.getMethods()) {
if(m.getAnnotation(EventHandler.class) != null) {
PluginListener listener = new PluginListener();
listener.plugin = p;
listener.listener = l;
listener.clazz = m.getParameterTypes()[0];
listener.priority = m.getAnnotation(EventHandler.class).value();
listener.run = m;
EVENTS.add(listener);
}
}
} catch (Exception e) {
//
}
}
@Override
public void runEvent(Object o) {
for(EventHandler.EventPriority p : EventHandler.EventPriority.values()) {
for (PluginListener listener : EVENTS) {
listener.runIfNeeded(p, o);
}
}
}
@Override
public Plugin getPluginByName(String name) {
return plugins.get(name);
}
}

View file

@ -1,28 +0,0 @@
package org.geysermc.connector.plugin;
import org.geysermc.api.events.EventHandler;
import org.geysermc.api.events.Listener;
import org.geysermc.api.plugin.Plugin;
import org.geysermc.connector.console.GeyserLogger;
import java.lang.reflect.Method;
public class PluginListener {
Method run;
Plugin plugin;
Listener listener;
Class clazz;
EventHandler.EventPriority priority;
void runIfNeeded(EventHandler.EventPriority p, Object o) {
if(p.equals(priority) && clazz.isInstance(o)) {
try {
run.invoke(listener, o);
} catch (ReflectiveOperationException ex) {
GeyserLogger.DEFAULT.severe("Exception while trying to run event! Contact the maintainer of " + plugin.getName());
ex.printStackTrace();
}
}
}
}

View file

@ -1,40 +0,0 @@
/*
* Copyright (c) 2019 GeyserMC. http://geysermc.org
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author GeyserMC
* @link https://github.com/GeyserMC/Geyser
*/
package org.geysermc.connector.plugin;
import com.fasterxml.jackson.annotation.JsonProperty;
public class PluginYML {
@JsonProperty("name")
String name;
@JsonProperty("version")
String version;
@JsonProperty("main")
String main;
}

View file

@ -31,7 +31,7 @@ import com.nukkitx.protocol.bedrock.packet.RemoveObjectivePacket;
import com.nukkitx.protocol.bedrock.packet.SetDisplayObjectivePacket;
import com.nukkitx.protocol.bedrock.packet.SetScorePacket;
import lombok.Getter;
import org.geysermc.api.Geyser;
import org.geysermc.connector.network.session.GeyserSession;
import java.util.*;
@ -77,7 +77,7 @@ public class Scoreboard {
public Team registerNewTeam(String teamName, Set<String> players) {
if (teams.containsKey(teamName)) {
Geyser.getLogger().info("Ignoring team " + teamName + ". It overrides without removing old team.");
session.getConnector().getLogger().info("Ignoring team " + teamName + ". It overrides without removing old team.");
return getTeam(teamName);
}
@ -120,7 +120,7 @@ public class Scoreboard {
for (String objectiveId : new ArrayList<>(objectives.keySet())) {
Objective objective = objectives.get(objectiveId);
if (objective.isTemp()) {
Geyser.getLogger().debug("Ignoring temp Scoreboard Objective '"+ objectiveId +'\'');
session.getConnector().getLogger().debug("Ignoring temp Scoreboard Objective '"+ objectiveId +'\'');
continue;
}

View file

@ -27,20 +27,26 @@ package org.geysermc.connector.utils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.geysermc.connector.GeyserConnector;
import java.io.*;
import java.util.function.Function;
public class FileUtils {
public static <T> T loadConfig(File src, Class<T> valueType) throws IOException {
ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
return objectMapper.readValue(src, valueType);
}
public static File fileOrCopiedFromResource(String name, Function<String, String> s) throws IOException {
File file = new File(name);
return fileOrCopiedFromResource(new File(name), name, s);
}
public static File fileOrCopiedFromResource(File file, String name, Function<String, String> s) throws IOException {
if (!file.exists()) {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
InputStream input = GeyserConnector.class.getResourceAsStream("/" + name); // resources need leading "/" prefix
@ -59,6 +65,4 @@ public class FileUtils {
return file;
}
}

View file

@ -30,7 +30,7 @@ import com.github.steveice10.opennbt.tag.builtin.CompoundTag;
import com.nukkitx.protocol.bedrock.data.ContainerId;
import com.nukkitx.protocol.bedrock.data.ItemData;
import com.nukkitx.protocol.bedrock.packet.InventorySlotPacket;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.inventory.Inventory;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.translators.TranslatorsInit;
@ -50,7 +50,7 @@ public class InventoryUtils {
translator.prepareInventory(session, inventory);
//TODO: find better way to handle double chest delay
if (translator instanceof DoubleChestInventoryTranslator) {
Geyser.getGeneralThreadPool().schedule(() -> {
GeyserConnector.getInstance().getGeneralThreadPool().schedule(() -> {
translator.openInventory(session, inventory);
translator.updateInventory(session, inventory);
}, 200, TimeUnit.MILLISECONDS);

View file

@ -34,17 +34,19 @@ import com.nukkitx.network.util.Preconditions;
import com.nukkitx.protocol.bedrock.packet.LoginPacket;
import com.nukkitx.protocol.bedrock.packet.ServerToClientHandshakePacket;
import com.nukkitx.protocol.bedrock.util.EncryptionUtils;
import net.minidev.json.JSONObject;
import org.geysermc.api.events.player.PlayerFormResponseEvent;
import org.geysermc.api.window.CustomFormBuilder;
import org.geysermc.api.window.CustomFormWindow;
import org.geysermc.api.window.FormWindow;
import org.geysermc.api.window.component.InputComponent;
import org.geysermc.api.window.component.LabelComponent;
import org.geysermc.api.window.response.CustomFormResponse;
import org.geysermc.common.window.CustomFormBuilder;
import org.geysermc.common.window.CustomFormWindow;
import org.geysermc.common.window.FormWindow;
import org.geysermc.common.window.component.InputComponent;
import org.geysermc.common.window.component.LabelComponent;
import org.geysermc.common.window.response.CustomFormResponse;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.network.session.GeyserSession;
import org.geysermc.connector.network.session.auth.BedrockAuthData;
import org.geysermc.connector.network.session.auth.AuthData;
import org.geysermc.connector.network.session.auth.BedrockClientData;
import org.geysermc.connector.network.session.cache.WindowCache;
import javax.crypto.SecretKey;
@ -97,7 +99,7 @@ public class LoginEncryptionUtils {
encryptConnectionWithCert(connector, session, loginPacket.getSkinData().toString(), certChainData);
}
private static void encryptConnectionWithCert(GeyserConnector connector, GeyserSession session, String playerSkin, JsonNode certChainData) {
private static void encryptConnectionWithCert(GeyserConnector connector, GeyserSession session, String clientData, JsonNode certChainData) {
try {
boolean validChain = validateChainData(certChainData);
@ -110,17 +112,23 @@ public class LoginEncryptionUtils {
throw new RuntimeException("AuthData was not found!");
}
JSONObject extraData = (JSONObject) jwt.getPayload().toJSONObject().get("extraData");
session.setAuthenticationData(new BedrockAuthData(extraData.getAsString("displayName"), UUID.fromString(extraData.getAsString("identity")), extraData.getAsString("XUID")));
JsonNode extraData = payload.get("extraData");
session.setAuthenticationData(new AuthData(
extraData.get("displayName").asText(),
UUID.fromString(extraData.get("identity").asText()),
extraData.get("XUID").asText()
));
if (payload.get("identityPublicKey").getNodeType() != JsonNodeType.STRING) {
throw new RuntimeException("Identity Public Key was not found!");
}
ECPublicKey identityPublicKey = EncryptionUtils.generateKey(payload.get("identityPublicKey").textValue());
JWSObject clientJwt = JWSObject.parse(playerSkin);
JWSObject clientJwt = JWSObject.parse(clientData);
EncryptionUtils.verifyJwt(clientJwt, identityPublicKey);
session.setClientData(JSON_MAPPER.convertValue(JSON_MAPPER.readTree(clientJwt.getPayload().toBytes()), BedrockClientData.class));
if (EncryptionUtils.canUseEncryption()) {
LoginEncryptionUtils.startEncryptionHandshake(session, identityPublicKey);
}
@ -165,17 +173,13 @@ public class LoginEncryptionUtils {
FormWindow window = windowCache.getWindows().remove(AUTH_FORM_ID);
window.setResponse(formData.trim());
if (session.isLoggedIn()) {
PlayerFormResponseEvent event = new PlayerFormResponseEvent(session, AUTH_FORM_ID, window);
connector.getPluginManager().runEvent(event);
} else {
if (!session.isLoggedIn()) {
if (window instanceof CustomFormWindow) {
CustomFormWindow customFormWindow = (CustomFormWindow) window;
if (!customFormWindow.getTitle().equals("Login"))
return false;
CustomFormResponse response = (CustomFormResponse) customFormWindow.getResponse();
if (response != null) {
String email = response.getInputResponses().get(2);
String password = response.getInputResponses().get(3);
@ -183,7 +187,6 @@ public class LoginEncryptionUtils {
session.authenticate(email, password);
}
// TODO should we clear the window cache in all cases or just if not already logged in?
// Clear windows so authentication data isn't accidentally cached
windowCache.getWindows().clear();
}

View file

@ -27,16 +27,16 @@ package org.geysermc.connector.utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.geysermc.api.Geyser;
import org.geysermc.connector.GeyserConnector;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.UUID;
@ -44,7 +44,7 @@ import java.util.concurrent.*;
public class SkinProvider {
public static final Gson GSON = new GsonBuilder().create();
public static final boolean ALLOW_THIRD_PARTY_CAPES = ((GeyserConnector)Geyser.getConnector()).getConfig().isAllowThirdPartyCapes();
public static final boolean ALLOW_THIRD_PARTY_CAPES = GeyserConnector.getInstance().getConfig().isAllowThirdPartyCapes();
private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(ALLOW_THIRD_PARTY_CAPES ? 21 : 14);
public static final byte[] STEVE_SKIN = new ProvidedSkin("bedrock/skin/skin_steve.png").getSkin();
@ -83,7 +83,7 @@ public class SkinProvider {
getOrDefault(requestCape(capeUrl, false), EMPTY_CAPE, 5)
);
Geyser.getLogger().debug("Took " + (System.currentTimeMillis() - time) + "ms for " + playerId);
GeyserConnector.getInstance().getLogger().debug("Took " + (System.currentTimeMillis() - time) + "ms for " + playerId);
return skinAndCape;
}, EXECUTOR_SERVICE);
}
@ -187,7 +187,7 @@ public class SkinProvider {
private static byte[] requestImage(String imageUrl, boolean cape) throws Exception {
BufferedImage image = ImageIO.read(new URL(imageUrl));
Geyser.getLogger().debug("Downloaded " + imageUrl);
GeyserConnector.getInstance().getLogger().debug("Downloaded " + imageUrl);
if (cape) {
image = image.getWidth() > 64 ? scale(image) : image;
@ -198,8 +198,7 @@ public class SkinProvider {
image = newImage;
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(image.getWidth() * 4 + image.getHeight() * 4);
try {
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(image.getWidth() * 4 + image.getHeight() * 4)) {
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int rgba = image.getRGB(x, y);
@ -211,10 +210,6 @@ public class SkinProvider {
}
image.flush();
return outputStream.toByteArray();
} finally {
try {
outputStream.close();
} catch (IOException ignored) {}
}
}

View file

@ -30,9 +30,11 @@ import com.google.gson.JsonObject;
import com.nukkitx.protocol.bedrock.data.ImageData;
import com.nukkitx.protocol.bedrock.data.SerializedSkin;
import com.nukkitx.protocol.bedrock.packet.PlayerListPacket;
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.geysermc.api.Geyser;
import org.geysermc.common.AuthType;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.entity.PlayerEntity;
import org.geysermc.connector.network.session.GeyserSession;
@ -44,6 +46,7 @@ import java.util.UUID;
import java.util.function.Consumer;
public class SkinUtils {
public static PlayerListPacket.Entry buildCachedEntry(GameProfile profile, long geyserId) {
GameProfileData data = GameProfileData.from(profile);
SkinProvider.Cape cape = SkinProvider.getCachedCape(data.getCapeUrl());
@ -121,8 +124,8 @@ public class SkinUtils {
return new GameProfileData(skinUrl, capeUrl, isAlex);
} catch (Exception exception) {
if (!((GeyserConnector) Geyser.getConnector()).getConfig().getRemote().getAuthType().equals("offline")) {
Geyser.getLogger().debug("Got invalid texture data for " + profile.getName() + " " + exception.getMessage());
if (GeyserConnector.getInstance().getAuthType() != AuthType.OFFLINE) {
GeyserConnector.getInstance().getLogger().debug("Got invalid texture data for " + profile.getName() + " " + exception.getMessage());
}
// return default skin with default cape when texture data is invalid
return new GameProfileData(SkinProvider.EMPTY_SKIN.getTextureUrl(), SkinProvider.EMPTY_CAPE.getTextureUrl(), false);
@ -132,7 +135,7 @@ public class SkinUtils {
public static void requestAndHandleSkinAndCape(PlayerEntity entity, GeyserSession session,
Consumer<SkinProvider.SkinAndCape> skinAndCapeConsumer) {
Geyser.getGeneralThreadPool().execute(() -> {
GeyserConnector.getInstance().getGeneralThreadPool().execute(() -> {
GameProfileData data = GameProfileData.from(entity.getProfile());
SkinProvider.requestSkinAndCape(entity.getUuid(), data.getSkinUrl(), data.getCapeUrl())
@ -176,11 +179,12 @@ public class SkinUtils {
}
}
} catch (Exception e) {
Geyser.getLogger().error("Failed getting skin for " + entity.getUuid(), e);
GeyserConnector.getInstance().getLogger().error("Failed getting skin for " + entity.getUuid(), e);
}
if (skinAndCapeConsumer != null) skinAndCapeConsumer.accept(skinAndCape);
});
});
}

View file

@ -34,10 +34,11 @@ import com.nukkitx.nbt.stream.NBTInputStream;
import com.nukkitx.nbt.tag.CompoundTag;
import com.nukkitx.protocol.bedrock.data.ItemData;
import com.nukkitx.protocol.bedrock.packet.StartGamePacket;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import org.geysermc.connector.GeyserConnector;
import org.geysermc.connector.console.GeyserLogger;
import org.geysermc.connector.network.translators.item.ItemEntry;
import java.io.ByteArrayInputStream;
@ -68,7 +69,7 @@ public class Toolbox {
biomesTag = (CompoundTag) biomenbtInputStream.readTag();
BIOMES = biomesTag;
} catch (Exception ex) {
GeyserLogger.DEFAULT.warning("Failed to get biomes from biome definitions, is there something wrong with the file?");
GeyserConnector.getInstance().getLogger().warning("Failed to get biomes from biome definitions, is there something wrong with the file?");
throw new AssertionError(ex);
}

View file

@ -20,10 +20,14 @@ remote:
address: 127.0.0.1
# The port of the remote (Java Edition) server
port: 25565
# Authentication type. Can be offline, online, or floodgate (see https://github.com/GeyserMC/Geyser/wiki/Floodgate).
auth-type: online
# Floodgate uses encryption to ensure use from authorised sources.
# This should point to the public key generated by Floodgate (Bungee or CraftBukkit)
# You can ignore this when not using Floodgate.
floodgate-key-file: public-key.pem
## the Xbox/MCPE username is the key for the Java server auth-info
## this allows automatic configuration/login to the remote Java server
## if you are brave/stupid enough to put your Mojang account info into