Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug #26

Merged
merged 20 commits into from
Sep 20, 2024
Merged

Bug #26

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

## 下载
* [自动构建版](https://github.com/zhinghu/CatSeedLogin/actions/workflows/maven.yml)
* [最新版](https://github.com/zhinghu/CatSeedLogin/releases)
* [最新版](https://github.com/zhinghu/CatSeedLogin/releases/latest)
* [旧版](https://github.com/CatSeed/CatSeedLogin/tags)

## 使用方式
Expand Down
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,11 @@
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.11.1</version>
</dependency>
</dependencies>
<repositories>
Expand Down
146 changes: 68 additions & 78 deletions src/main/java/cc/baka9/catseedlogin/bukkit/Communication.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
Expand All @@ -16,71 +18,55 @@
import cc.baka9.catseedlogin.bukkit.object.LoginPlayerHelper;
import cc.baka9.catseedlogin.util.CommunicationAuth;

/**
* bukkit 与 bc 的通讯交流
*/
public class Communication {
private static ServerSocket serverSocket;
private static final ExecutorService executorService = Executors.newCachedThreadPool();

/**
* 异步关闭 socket server
*/
public static void socketServerStopAsync() {
CatSeedLogin.instance.runTaskAsync(Communication::socketServerStop);
}

public static void socketServerStop() {

if (serverSocket != null && !serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static synchronized void socketServerStop() {
closeServerSocket(serverSocket);
}

/**
* 异步启动 socket server 监听bc端发来的请求
*/
public static void socketServerStartAsync() {
CatSeedLogin.instance.runTaskAsync(Communication::socketServerStart);
}

/**
* 启动 socket server 监听bc端发来的请求
*/
private static void socketServerStart() {
private static synchronized void socketServerStart() {
try {
InetAddress inetAddress = InetAddress.getByName(Config.BungeeCord.Host);
serverSocket = new ServerSocket(Integer.parseInt(Config.BungeeCord.Port), 50, inetAddress);
acceptConnections(serverSocket);
} catch (UnknownHostException e) {
CatSeedLogin.instance.getLogger().warning("无法解析域名或IP地址: " + e.getMessage());
} catch (IOException e) {
CatSeedLogin.instance.getLogger().warning("启动Socket服务器时发生错误: " + e.getMessage());
}
}

private static void acceptConnections(ServerSocket serverSocket) {
while (!serverSocket.isClosed()) {
try {
InetAddress inetAddress = InetAddress.getByName(Config.BungeeCord.Host);
serverSocket = new ServerSocket(Integer.parseInt(Config.BungeeCord.Port), 50, inetAddress);
while (!serverSocket.isClosed()) {
Socket socket;
try {
socket = serverSocket.accept();
handleRequest(socket);
} catch (IOException e) {
break;
}
}
} catch (UnknownHostException e) {
CatSeedLogin.instance.getLogger().warning("无法解析域名或IP地址");
e.printStackTrace();
Socket socket = serverSocket.accept();
executorService.submit(() -> handleRequest(socket));
} catch (IOException e) {
e.printStackTrace();
if (serverSocket.isClosed()) {
break;
}
CatSeedLogin.instance.getLogger().warning("接受Socket连接时发生错误: " + e.getMessage());
}
}
}


/**
* 处理请求
*/
private static void handleRequest(Socket socket) throws IOException {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
private static void handleRequest(Socket socket) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String requestType = bufferedReader.readLine();
if (requestType == null) {
socket.close();
return;
}
String playerName = bufferedReader.readLine();
Expand All @@ -94,52 +80,56 @@ private static void handleRequest(Socket socket) throws IOException {
handleKeepLoggedInRequest(playerName, time, sign);
break;
default:
CatSeedLogin.instance.getLogger().warning("未知请求类型: " + requestType);
break;
}
} finally {
if (!socket.isClosed()) {
socket.close();
}
} catch (IOException e) {
CatSeedLogin.instance.getLogger().warning("处理请求时发生错误: " + e.getMessage());
}
}

private static void handleKeepLoggedInRequest(String playerName, String time, String sign) {
// 验证请求的合法性
// 对比玩家名,时间戳,和authKey加密的结果(加密是因为如果登录服不在内网环境下,则可能会被人使用这个功能给发包来直接绕过登录)
if (CommunicationAuth.encryption(playerName, time, Config.BungeeCord.AuthKey).equals(sign)) {
// 切换主线程给予登录状态
CatScheduler.runTask( () -> {
LoginPlayer lp = Cache.getIgnoreCase(playerName);
if (lp != null) {
LoginPlayerHelper.add(lp);
Player player = Bukkit.getPlayerExact(playerName);
if (player != null) {
player.updateInventory();
}
private static void handleKeepLoggedInRequest(String playerName, String time, String sign) {
if (CommunicationAuth.encryption(playerName, time, Config.BungeeCord.AuthKey).equals(sign)) {
CatScheduler.runTask(() -> {
LoginPlayer lp = Cache.getIgnoreCase(playerName);
if (lp != null) {
LoginPlayerHelper.add(lp);
Player player = Bukkit.getPlayerExact(playerName);
if (player != null) {
player.updateInventory();
}

});
}
} else {
CatSeedLogin.instance.getLogger().warning("玩家 " + playerName + " 未找到在缓存中。");
}
});
}
}

private static void handleConnectRequest(Socket socket, String playerName) {
// 切换主线程获取是否已登录
CatScheduler.runTask( () -> {
CatScheduler.runTask(() -> {
boolean result = LoginPlayerHelper.isLogin(playerName);

// 切换异步线程返回结果
CatSeedLogin.instance.runTaskAsync(() -> {
try {
socket.getOutputStream().write(result ? 1 : 0);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}

});

sendConnectResultAsync(socket, result);
});
}

private static void sendConnectResultAsync(Socket socket, boolean result) {
executorService.submit(() -> {
try (Socket autoCloseSocket = socket) {
autoCloseSocket.getOutputStream().write(result ? 1 : 0);
autoCloseSocket.getOutputStream().flush();
} catch (IOException e) {
CatSeedLogin.instance.getLogger().warning("发送连接结果时发生错误: " + e.getMessage());
}
});
}

private static void closeServerSocket(ServerSocket serverSocket) {
if (serverSocket != null && !serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException e) {
CatSeedLogin.instance.getLogger().warning("关闭Socket服务器时发生错误: " + e.getMessage());
}
}
}
}
25 changes: 14 additions & 11 deletions src/main/java/cc/baka9/catseedlogin/bukkit/Config.java
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
package cc.baka9.catseedlogin.bukkit;

import java.io.BufferedInputStream;
import java.io.File;
import java.util.Map;
import java.util.List;
import java.util.Optional;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.lang.reflect.Field;
import java.util.regex.Pattern;
import java.io.InputStreamReader;
import java.io.BufferedInputStream;
import java.util.stream.Collectors;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ConcurrentHashMap;

import org.bukkit.World;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;

/**
* 加载/保存/重载 yml配置文件
Expand Down Expand Up @@ -95,6 +95,7 @@ public static class Settings {
public static boolean CanTpSpawnLocation;
public static List<Pattern> CommandWhiteList = new ArrayList<>();
public static int AutoKick;
public static String NamePattern;
// 死亡状态退出游戏是否记录退出位置 (玩家可以通过死亡时退出服务器然后重新进入,再复活,登录返回死亡地点)
public static boolean DeathStateQuitRecordLocation;
public static boolean FloodgatePrefixProtect;
Expand All @@ -115,6 +116,7 @@ public static void load(){
ReenterInterval = config.getLong("ReenterInterval", resourceConfig.getLong("ReenterInterval"));
AfterLoginBack = config.getBoolean("AfterLoginBack", resourceConfig.getBoolean("AfterLoginBack"));
CanTpSpawnLocation = config.getBoolean("CanTpSpawnLocation", resourceConfig.getBoolean("CanTpSpawnLocation"));
NamePattern = config.getString("NamePattern", resourceConfig.getString("NamePattern", "^\\w+$"));
List<String> commandWhiteList = config.getStringList("CommandWhiteList");
if (commandWhiteList.isEmpty()) {
commandWhiteList = resourceConfig.getStringList("CommandWhiteList");
Expand Down Expand Up @@ -151,6 +153,7 @@ public static void save(){
config.set("CommandWhiteList", CommandWhiteList.stream().map(Pattern::toString).collect(Collectors.toList()));
config.set("DeathStateQuitRecordLocation", DeathStateQuitRecordLocation);
config.set("FloodgatePrefixProtect", FloodgatePrefixProtect);
config.set("NamePattern", NamePattern);
try {
config.save(new File(CatSeedLogin.instance.getDataFolder(), "settings.yml"));
} catch (IOException e) {
Expand Down
26 changes: 13 additions & 13 deletions src/main/java/cc/baka9/catseedlogin/bukkit/Listeners.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,28 @@
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.geysermc.floodgate.api.FloodgateApi;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.entity.EntityPickupItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.geysermc.floodgate.api.FloodgateApi;

import cc.baka9.catseedlogin.bukkit.task.Task;
import cc.baka9.catseedlogin.bukkit.database.Cache;
import cc.baka9.catseedlogin.bukkit.object.LoginPlayer;
import cc.baka9.catseedlogin.bukkit.object.LoginPlayerHelper;
import cc.baka9.catseedlogin.bukkit.task.Task;

public class Listeners implements Listener {

Expand Down Expand Up @@ -190,7 +190,7 @@ public void onPlayerJoin(PlayerJoinEvent event) {
@EventHandler
public void onPlayerPreLogin(AsyncPlayerPreLoginEvent event) {
String name = event.getName();
if (Config.Settings.LimitChineseID && !name.matches("^\\w+$")) {
if (Config.Settings.LimitChineseID && !name.matches(Config.Settings.NamePattern)) {
event.disallow(AsyncPlayerPreLoginEvent.Result.KICK_OTHER, "请使用由数字,字母和下划线组成的游戏名,才能进入游戏");
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public static boolean recordCurrentIP(Player player) {
if (Config.Settings.IPTimeout == 0) {
return storedIPs.contains(currentIP);
} else {
return exitTime != null && storedIPs.contains(currentIP) && (System.currentTimeMillis() - exitTime) <= (long) Config.Settings.IPTimeout * 60 * 1000;
return exitTime != null && storedIPs.contains(currentIP) && (System.currentTimeMillis() - exitTime) <= (long) Config.Settings.IPTimeout * 60 * 1000L;
}
}

Expand Down
Loading
Loading