├── ScreenShot.png ├── .gitignore ├── Description_EN.png ├── src └── main │ ├── java │ └── cc │ │ └── eumc │ │ └── uniban │ │ ├── exception │ │ └── CommandBreakException.java │ │ ├── serverinterface │ │ ├── PlayerInfo.java │ │ ├── BukkitPlayerInfo.java │ │ └── BungeePlayerInfo.java │ │ ├── task │ │ ├── IdentifySubscriptionTask.java │ │ ├── UpdateCheckTask.java │ │ ├── LocalBanListRefreshTask.java │ │ └── SubscriptionRefreshTask.java │ │ ├── extension │ │ ├── HttpService.java │ │ └── UniBanExtension.java │ │ ├── config │ │ ├── ThirdPartySupportConfig.java │ │ ├── ServerEntry.java │ │ ├── Message.java │ │ ├── BungeeConfig.java │ │ ├── BukkitConfig.java │ │ └── PluginConfig.java │ │ ├── controller │ │ ├── BukkitCommandController.java │ │ ├── BungeeCommandController.java │ │ ├── AccessController.java │ │ ├── DeliveryController.java │ │ ├── UniBanBukkitController.java │ │ ├── UniBanBungeeController.java │ │ ├── CommandController.java │ │ └── UniBanController.java │ │ ├── handler │ │ ├── BanListRequestHandler.java │ │ └── IDRequestHandler.java │ │ ├── util │ │ ├── BungeeBanSupport.java │ │ ├── VanillaListSupport.java │ │ ├── LiteBansSupport.java │ │ ├── AdvancedBanSupport.java │ │ ├── ServerListPing.java │ │ ├── Encryption.java │ │ └── HttpRequest.java │ │ ├── Utility.java │ │ ├── listener │ │ ├── PaperListener.java │ │ ├── BukkitPlayerListener.java │ │ └── BungeePlayerListener.java │ │ ├── command │ │ ├── BungeeCommand.java │ │ └── BukkitCommand.java │ │ ├── UniBanBukkitPlugin.java │ │ └── UniBanBungeePlugin.java │ └── resources │ ├── bungee.yml │ ├── plugin.yml │ ├── RemoteListReceiver_example.php │ └── config.yml ├── pom.xml ├── README.md └── LICENSE /ScreenShot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/richardhyy/EusUniBan/HEAD/ScreenShot.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | /src/main/java/META-INF/ 3 | -------------------------------------------------------------------------------- /Description_EN.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/richardhyy/EusUniBan/HEAD/Description_EN.png -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/exception/CommandBreakException.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.exception; 2 | 3 | public class CommandBreakException extends Exception { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /src/main/resources/bungee.yml: -------------------------------------------------------------------------------- 1 | name: UniBan 2 | main: cc.eumc.uniban.UniBanBungeePlugin 3 | version: ${project.version} 4 | author: EucalyptusLeaves 5 | softDepends: [LiteBans, AdvancedBan, BungeeAdminTool, BungeeBan] -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/serverinterface/PlayerInfo.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.serverinterface; 2 | 3 | import java.util.UUID; 4 | 5 | public interface PlayerInfo { 6 | UUID getUUID(); 7 | String getName(); 8 | void sendMessage(String msg); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/task/IdentifySubscriptionTask.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.task; 2 | 3 | import cc.eumc.uniban.controller.UniBanController; 4 | 5 | public class IdentifySubscriptionTask implements Runnable { 6 | final UniBanController controller; 7 | public IdentifySubscriptionTask(UniBanController instance) { 8 | this.controller = instance; 9 | } 10 | 11 | @Override 12 | public void run() { 13 | // TODO IdentifySubscriptionTask 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/resources/plugin.yml: -------------------------------------------------------------------------------- 1 | name: UniBan 2 | version: ${project.version} 3 | main: cc.eumc.uniban.UniBanBukkitPlugin 4 | api-version: 1.13 5 | authors: [EucalyptusLeaves] 6 | softdepend: [LiteBans, AdvancedBan] 7 | commands: 8 | uniban: 9 | permissions: 10 | uniban.admin: 11 | default: op 12 | description: Permission for UniBan management commands 13 | uniban.getnotified: 14 | default: op 15 | description: Permission for getting notified when a player who is banned by more than threshold settings logining 16 | uniban.ignore: 17 | description: Ignore online ban & warning threshold -------------------------------------------------------------------------------- /src/main/resources/RemoteListReceiver_example.php: -------------------------------------------------------------------------------- 1 | implements PlayerInfo { 10 | T p; 11 | public BukkitPlayerInfo(T p) { 12 | this.p = p; 13 | } 14 | 15 | @Override 16 | public @Nullable UUID getUUID() { 17 | if (!(p instanceof Player)) { 18 | return null; 19 | } 20 | return ((Player)p).getUniqueId(); 21 | } 22 | 23 | @Override 24 | public @Nullable String getName() { 25 | if (!(p instanceof Player)) { 26 | return null; 27 | } 28 | return ((Player)p).getName(); 29 | } 30 | 31 | @Override 32 | public void sendMessage(String msg) { 33 | if (p instanceof Player) { 34 | ((Player)p).sendMessage(msg); 35 | } else if (p instanceof CommandSender) { 36 | ((CommandSender)p).sendMessage(msg); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/serverinterface/BungeePlayerInfo.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.serverinterface; 2 | 3 | import net.md_5.bungee.api.CommandSender; 4 | import net.md_5.bungee.api.chat.TextComponent; 5 | import net.md_5.bungee.api.connection.ProxiedPlayer; 6 | import org.jetbrains.annotations.Nullable; 7 | 8 | import java.util.UUID; 9 | 10 | public class BungeePlayerInfo implements PlayerInfo { 11 | T p; 12 | public BungeePlayerInfo(T p) { 13 | this.p = p; 14 | } 15 | 16 | @Override 17 | public @Nullable UUID getUUID() { 18 | if (!(p instanceof ProxiedPlayer)) { 19 | return null; 20 | } 21 | return ((ProxiedPlayer)p).getUniqueId(); 22 | 23 | } 24 | 25 | @Override 26 | public String getName() { 27 | if (!(p instanceof ProxiedPlayer)) { 28 | return null; 29 | } 30 | return ((ProxiedPlayer)p).getName(); 31 | } 32 | 33 | @Override 34 | public void sendMessage(String msg) { 35 | if (p instanceof ProxiedPlayer) { 36 | ((ProxiedPlayer)p).sendMessage(new TextComponent(msg)); 37 | } else if (p instanceof CommandSender) { 38 | ((CommandSender)p).sendMessage(new TextComponent(msg)); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/controller/BukkitCommandController.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.controller; 2 | 3 | import cc.eumc.uniban.UniBanBukkitPlugin; 4 | import cc.eumc.uniban.config.BukkitConfig; 5 | 6 | import java.util.List; 7 | import java.util.UUID; 8 | 9 | public class BukkitCommandController extends CommandController { 10 | UniBanBukkitPlugin plugin; 11 | public BukkitCommandController(UniBanBukkitPlugin instance, BukkitConfig bukkitConfig) { 12 | super(bukkitConfig); 13 | this.plugin = instance; 14 | } 15 | 16 | @Override 17 | void doReload() { 18 | plugin.reloadConfig(); 19 | plugin.reloadController(); 20 | plugin.registerTask(); 21 | } 22 | 23 | @Override 24 | boolean isBannedOnline(UUID uuid) { 25 | return plugin.getController().isBannedOnline(uuid); 26 | } 27 | 28 | @Override 29 | List getBannedServerList(UUID uuid) { 30 | return plugin.getController().getBannedServerList(uuid); 31 | } 32 | 33 | @Override 34 | void addWhitelist(UUID uuid) { 35 | plugin.getController().addWhitelist(uuid); 36 | } 37 | 38 | @Override 39 | void removeWhitelist(UUID uuid) { 40 | plugin.getController().removeWhitelist(uuid); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/controller/BungeeCommandController.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.controller; 2 | 3 | import cc.eumc.uniban.UniBanBungeePlugin; 4 | import cc.eumc.uniban.config.BungeeConfig; 5 | 6 | import java.util.List; 7 | import java.util.UUID; 8 | 9 | public class BungeeCommandController extends CommandController { 10 | UniBanBungeePlugin plugin; 11 | public BungeeCommandController(UniBanBungeePlugin instance, BungeeConfig bungeeConfig) { 12 | super(bungeeConfig); 13 | this.plugin = instance; 14 | } 15 | 16 | @Override 17 | void doReload() { 18 | plugin.reloadConfig(); 19 | plugin.reloadController(); 20 | plugin.registerTask(); 21 | } 22 | 23 | @Override 24 | boolean isBannedOnline(UUID uuid) { 25 | return plugin.getController().isBannedOnline(uuid); 26 | } 27 | 28 | @Override 29 | List getBannedServerList(UUID uuid) { 30 | return plugin.getController().getBannedServerList(uuid); 31 | } 32 | 33 | @Override 34 | void addWhitelist(UUID uuid) { 35 | plugin.getController().addWhitelist(uuid); 36 | } 37 | 38 | @Override 39 | void removeWhitelist(UUID uuid) { 40 | plugin.getController().removeWhitelist(uuid); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/handler/BanListRequestHandler.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.handler; 2 | 3 | import cc.eumc.uniban.controller.AccessController; 4 | import cc.eumc.uniban.controller.UniBanController; 5 | import com.sun.net.httpserver.HttpExchange; 6 | import com.sun.net.httpserver.HttpHandler; 7 | 8 | import java.io.IOException; 9 | import java.io.OutputStream; 10 | 11 | public class BanListRequestHandler implements HttpHandler { 12 | UniBanController controller; 13 | AccessController accessController = new AccessController(); 14 | 15 | public BanListRequestHandler(UniBanController instance) { 16 | this.controller = instance; 17 | } 18 | 19 | @Override 20 | public void handle(HttpExchange t) throws IOException { 21 | if (!accessController.canAccess(t.getRemoteAddress().getHostName())) { 22 | // if host was blocked 23 | t.close(); 24 | return; 25 | } 26 | controller.sendInfo("Ban-list request from: " + t.getRemoteAddress().getHostName()); 27 | String response = controller.getBanListJson(); 28 | t.sendResponseHeaders(200, response.length()); 29 | OutputStream os = t.getResponseBody(); 30 | os.write(response.getBytes()); 31 | os.close(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/handler/IDRequestHandler.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.handler; 2 | 3 | import cc.eumc.uniban.config.PluginConfig; 4 | import cc.eumc.uniban.controller.AccessController; 5 | import cc.eumc.uniban.controller.UniBanController; 6 | import com.sun.net.httpserver.HttpExchange; 7 | import com.sun.net.httpserver.HttpHandler; 8 | 9 | import java.io.IOException; 10 | import java.io.OutputStream; 11 | 12 | public class IDRequestHandler implements HttpHandler { 13 | UniBanController controller; 14 | AccessController accessController = new AccessController(); 15 | 16 | public IDRequestHandler(UniBanController instance) { 17 | this.controller = instance; 18 | } 19 | 20 | @Override 21 | public void handle(HttpExchange t) throws IOException { 22 | if (!accessController.canAccess(t.getRemoteAddress().getHostName())) { 23 | // if host was blocked 24 | t.close(); 25 | return; 26 | } 27 | controller.sendInfo("ID request from: " + t.getRemoteAddress().getHostName()); 28 | String response = PluginConfig.NodeID; 29 | t.sendResponseHeaders(200, response.length()); 30 | OutputStream os = t.getResponseBody(); 31 | os.write(response.getBytes()); 32 | os.close(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/util/BungeeBanSupport.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.util; 2 | 3 | import cc.eumc.uniban.controller.UniBanController; 4 | import net.craftminecraft.bungee.bungeeban.BanManager; 5 | import net.craftminecraft.bungee.bungeeban.banstore.BanEntry; 6 | 7 | import java.util.HashSet; 8 | import java.util.List; 9 | import java.util.Set; 10 | import java.util.UUID; 11 | 12 | public class BungeeBanSupport { 13 | public static Set fetchAllBanned(UniBanController controller) { 14 | List banEntryList = BanManager.getBanList(); 15 | if (banEntryList == null) return new HashSet<>(); 16 | 17 | Set bannedUUID = new HashSet<>(); 18 | 19 | for (BanEntry banEntry : banEntryList) { 20 | if (controller.shouldIgnoreReason(banEntry.getReason())) { 21 | continue; 22 | } 23 | 24 | String uuidStr = banEntry.getBanned(); 25 | 26 | // Check if it returns with UUID without dashes 27 | if (!uuidStr.contains("-")) { 28 | uuidStr = uuidStr.replaceFirst( 29 | "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5" 30 | ); 31 | } 32 | 33 | bannedUUID.add(UUID.fromString(uuidStr)); 34 | 35 | } 36 | 37 | return bannedUUID; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/Utility.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban; 2 | 3 | import cc.eumc.uniban.controller.CommandController; 4 | import cc.eumc.uniban.util.Encryption; 5 | 6 | public class Utility { 7 | public static void main(String[] args) { 8 | if (args.length == 0) { 9 | System.out.println("Usage: @ ... @"); 10 | System.out.println("Example: example.com:60009@UniBan uniban.eumc.cc/public:443"); 11 | return; 12 | } 13 | 14 | System.out.println("Subscription key(s) of your server(s) which contains your address and connection password:"); 15 | 16 | for (String arg : args) { 17 | String[] split = arg.split("@"); 18 | String address = "", password = ""; 19 | 20 | if (split.length == 2) { 21 | address = split[0]; 22 | password = split[1]; 23 | } 24 | else if (split.length == 1){ 25 | address = split[0]; 26 | } 27 | if (!address.contains(":")) { 28 | address += ":60009"; 29 | System.out.println(" " + address + " does not contain a valid port, use 60009 by default"); 30 | } 31 | 32 | System.out.println(Encryption.encrypt(address + "@" + password, CommandController.SHARING_KEY)); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/listener/PaperListener.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.listener; 2 | 3 | import cc.eumc.uniban.UniBanBukkitPlugin; 4 | import cc.eumc.uniban.controller.AccessController; 5 | import cc.eumc.uniban.controller.UniBanController; 6 | import com.destroystokyo.paper.event.server.PaperServerListPingEvent; 7 | import org.bukkit.event.EventHandler; 8 | import org.bukkit.event.EventPriority; 9 | import org.bukkit.event.Listener; 10 | 11 | import java.net.InetSocketAddress; 12 | 13 | public class PaperListener implements Listener { 14 | UniBanBukkitPlugin plugin; 15 | AccessController accessController = new AccessController(); 16 | 17 | public PaperListener(UniBanBukkitPlugin plugin) { 18 | this.plugin = plugin; 19 | } 20 | 21 | @EventHandler(priority = EventPriority.LOWEST) 22 | public void onListPing(PaperServerListPingEvent e) { 23 | InetSocketAddress address = e.getClient().getVirtualHost(); 24 | if (address == null) { 25 | return; 26 | } 27 | if (!address.getHostName().equals("UNIBAN")) { 28 | return; 29 | } 30 | 31 | String clientHost = e.getClient().getAddress().getHostString(); 32 | if (!accessController.canAccess(clientHost)) { 33 | // if host was blocked 34 | e.setCancelled(true); 35 | return; 36 | } 37 | 38 | UniBanController controller = plugin.getController(); 39 | controller.sendInfo("Ban-list request from: " + clientHost); 40 | e.setMotd(controller.getBanListJson()); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/task/UpdateCheckTask.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.task; 2 | 3 | import cc.eumc.uniban.config.Message; 4 | 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.net.URL; 8 | import java.util.Scanner; 9 | import java.util.function.Consumer; 10 | 11 | public class UpdateCheckTask implements Runnable { 12 | 13 | String version; 14 | int resourceId; 15 | 16 | public UpdateCheckTask(String version, int resourceId) { 17 | this.version = version; 18 | this.resourceId = resourceId; 19 | } 20 | 21 | @Override 22 | public void run() { 23 | getVersion(version -> { 24 | if (version.equalsIgnoreCase("Invalid resource")) { 25 | System.out.println(Message.MessagePrefix + Message.InvalidSpigotResourceID); 26 | } 27 | if (version.equalsIgnoreCase(this.version)) { 28 | System.out.println(Message.MessagePrefix + Message.UpToDate); 29 | } else { 30 | System.out.println(Message.MessagePrefix + String.format(Message.NewVersionAvailable, version)); 31 | } 32 | }); 33 | } 34 | 35 | public void getVersion(final Consumer consumer) { 36 | try (InputStream inputStream = new URL("https://api.spigotmc.org/legacy/update.php?resource=" + this.resourceId).openStream(); Scanner scanner = new Scanner(inputStream)) { 37 | if (scanner.hasNext()) { 38 | consumer.accept(scanner.next()); 39 | } 40 | } catch (IOException e) { 41 | System.out.println(Message.MessagePrefix + Message.FailedCheckingUpdate); 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/util/VanillaListSupport.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.util; 2 | 3 | import cc.eumc.uniban.config.ThirdPartySupportConfig; 4 | import cc.eumc.uniban.controller.UniBanController; 5 | import com.google.gson.Gson; 6 | 7 | import java.io.File; 8 | import java.io.FileReader; 9 | import java.util.*; 10 | 11 | public class VanillaListSupport { 12 | static class VanillaBan { 13 | public String uuid; 14 | public String name; 15 | public String created; 16 | public String source; 17 | public String expires; 18 | public String reason; 19 | } 20 | 21 | public static Set fetchAllBanned(UniBanController controller) { 22 | Set banned = new HashSet<>(); 23 | File file = new File(ThirdPartySupportConfig.DataFolder, "banned-players.json"); 24 | if (!file.exists()) { 25 | return banned; 26 | } 27 | 28 | try { 29 | FileReader reader = new FileReader(file); 30 | Gson g = new Gson(); 31 | List vanillaBanList; 32 | vanillaBanList = Arrays.asList(g.fromJson(reader, VanillaBan[].class)); 33 | 34 | try { 35 | vanillaBanList.forEach(vanillaBan -> { 36 | if (!controller.shouldIgnoreReason(vanillaBan.reason)) { 37 | banned.add(UUID.fromString(vanillaBan.uuid)); 38 | } 39 | }); 40 | } catch (IllegalArgumentException e) { 41 | e.printStackTrace(); 42 | } 43 | 44 | } catch (Exception e) { 45 | e.printStackTrace(); 46 | } 47 | 48 | return banned; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/controller/AccessController.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.controller; 2 | 3 | import cc.eumc.uniban.config.PluginConfig; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public class AccessController { 9 | Map lastAccessMap = new HashMap<>(); 10 | int MinPeriodPerServer; 11 | 12 | public AccessController() { 13 | this.MinPeriodPerServer = PluginConfig.MinPeriodPerServer; 14 | } 15 | 16 | /** 17 | * Manually define minimum requesting interval 18 | * @param minPeriodPerServer Unit: minute 19 | */ 20 | public AccessController(double minPeriodPerServer) { 21 | this.MinPeriodPerServer = (int) (60 * minPeriodPerServer); 22 | } 23 | 24 | public boolean canAccess(String host) { 25 | if (PluginConfig.EnabledAccessControl) { 26 | if (PluginConfig.WhitelistEnabled && PluginConfig.Whitelist.contains(host)) { 27 | return true; 28 | } 29 | if (PluginConfig.BlacklistEnabled && (PluginConfig.Blacklist.contains(host) || PluginConfig.Blacklist.contains("*"))) { 30 | return false; 31 | } 32 | return canAccessByCheckFrequency(host); 33 | } 34 | return true; 35 | } 36 | 37 | public boolean canAccessByCheckFrequency(String host) { 38 | if (MinPeriodPerServer == 0) return true; 39 | 40 | final long now = System.currentTimeMillis() / 1000; 41 | final long lastAccess = lastAccessMap.getOrDefault(host, 0L); 42 | lastAccessMap.put(host, now); 43 | if (lastAccess != 0L) { 44 | return now - lastAccess >= MinPeriodPerServer; 45 | } 46 | else { 47 | return true; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/command/BungeeCommand.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.command; 2 | 3 | import cc.eumc.uniban.UniBanBungeePlugin; 4 | import cc.eumc.uniban.controller.BungeeCommandController; 5 | import cc.eumc.uniban.exception.CommandBreakException; 6 | import cc.eumc.uniban.serverinterface.BungeePlayerInfo; 7 | import net.md_5.bungee.api.CommandSender; 8 | import net.md_5.bungee.api.chat.TextComponent; 9 | import net.md_5.bungee.api.plugin.Command; 10 | 11 | import java.util.List; 12 | 13 | public class BungeeCommand extends Command { 14 | UniBanBungeePlugin plugin; 15 | BungeeCommandController commandController; 16 | public BungeeCommand(UniBanBungeePlugin instance) { 17 | super("uniban", "uniban.admin"); 18 | this.plugin = instance; 19 | commandController = new BungeeCommandController(instance, plugin.getBungeeConfig()); 20 | } 21 | 22 | @Override 23 | public void execute(CommandSender sender, String[] args) { 24 | /* 25 | if (args.length == 2 && args[0].equalsIgnoreCase("lookupuuid")) { 26 | sender.sendMessage(new TextComponent(UniBanController.nameToUUID(args[1]).toString())); 27 | return; 28 | } 29 | */ 30 | 31 | List msgLines = null; 32 | try { 33 | msgLines = commandController.executeCommand(args, plugin.getController(), new BungeePlayerInfo<>(sender)); 34 | for (String line : msgLines) { 35 | sender.sendMessage(new TextComponent(line)); 36 | } 37 | } catch (CommandBreakException ignored) { 38 | if (msgLines != null) { 39 | for (String line : msgLines) { 40 | sender.sendMessage(new TextComponent(line)); 41 | } 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/util/LiteBansSupport.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.util; 2 | 3 | import cc.eumc.uniban.controller.UniBanController; 4 | import litebans.api.Database; 5 | 6 | import java.sql.PreparedStatement; 7 | import java.sql.ResultSet; 8 | import java.sql.SQLException; 9 | import java.util.HashSet; 10 | import java.util.Set; 11 | import java.util.UUID; 12 | 13 | public class LiteBansSupport { 14 | public static Set fetchAllBanned(UniBanController controller) { 15 | if (Database.get() == null) return new HashSet<>(); 16 | 17 | String query = "SELECT * FROM {bans}"; 18 | Set bannedUUID = new HashSet<>(); 19 | try (PreparedStatement st = Database.get().prepareStatement(query)) { 20 | try (ResultSet result = st.executeQuery()) { 21 | while (result.next()) { 22 | String uuidStr = result.getString("uuid"); 23 | String reason = result.getString("reason"); 24 | 25 | if (controller.shouldIgnoreReason(reason)) { 26 | continue; 27 | } 28 | 29 | try { 30 | UUID uuid = UUID.fromString(uuidStr); 31 | // check if removed or expired 32 | // Fix: Logical error 33 | if (!Database.get().isPlayerBanned(uuid, null)) continue; 34 | bannedUUID.add(uuid); 35 | } catch (IllegalArgumentException ignore) { 36 | System.out.println("Illegal UUID returned from LiteBans:" + uuidStr); 37 | } 38 | //System.out.println(uuidStr); 39 | } 40 | } 41 | } catch (SQLException e) { 42 | e.printStackTrace(); 43 | } 44 | return bannedUUID; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/util/AdvancedBanSupport.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.util; 2 | 3 | import cc.eumc.uniban.controller.UniBanController; 4 | import me.leoko.advancedban.manager.DatabaseManager; 5 | import me.leoko.advancedban.utils.SQLQuery; 6 | 7 | import java.sql.ResultSet; 8 | import java.util.HashSet; 9 | import java.util.Set; 10 | import java.util.UUID; 11 | 12 | public class AdvancedBanSupport { 13 | public static Set fetchAllBanned(UniBanController controller) { 14 | if (DatabaseManager.get() == null) return new HashSet<>(); 15 | 16 | Set bannedUUID = new HashSet<>(); 17 | 18 | try { 19 | ResultSet result = DatabaseManager.get().executeResultStatement(SQLQuery.SELECT_ALL_PUNISHMENTS); 20 | while (result.next()) { 21 | try { 22 | String uuidStr = result.getString("uuid"); 23 | String reason = result.getString("reason"); 24 | 25 | if (controller.shouldIgnoreReason(reason)) { 26 | continue; 27 | } 28 | 29 | // AdvancedBan returns with UUID without dashes 30 | if (!uuidStr.contains("-")) { 31 | uuidStr = uuidStr.replaceFirst( 32 | "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5" 33 | ); 34 | } 35 | 36 | bannedUUID.add(UUID.fromString(uuidStr)); 37 | } 38 | catch (IllegalArgumentException ignore) { 39 | System.out.println("Illegal UUID returned from AdvancedBan: " + result.getString("uuid")); 40 | } 41 | //System.out.println(result.getString("uuid")); 42 | } 43 | } 44 | catch (Exception e) { 45 | e.printStackTrace(); 46 | } 47 | 48 | return bannedUUID; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/config/Message.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.config; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public class Message { 7 | public static String WarningMessage; 8 | public static String BannedOnlineKickMessage; 9 | public static String IgnoredOP; 10 | public static String MessagePrefix; 11 | public static String Error; 12 | public static String Reloaded; 13 | public static String PlayerNotExist; 14 | public static String PlayerState; 15 | public static String PlayerBanned; 16 | public static String PlayerNormal; 17 | public static String InvalidSubscriptionKey; 18 | public static String SubscriptionKeyAdded; 19 | public static String YourSubscriptionKey; 20 | public static String SubscriptionKeyLink; 21 | public static String SubscriptionExempted; 22 | public static String FailedExempting; 23 | public static String WhitelistAdded; 24 | public static String WhitelistRemoved; 25 | public static String SubscriptionsHeader; 26 | public static String ThirdPartyPluginSupportHeader; 27 | public static String Encrypted; 28 | public static String BroadcastStarted; 29 | public static String BroadcastActiveModeEnabled; 30 | public static String BroadcastViaServerListPing; 31 | public static String BroadcastFailed; 32 | public static String PluginEnabled; 33 | public static String PluginNotFound; 34 | public static String UpToDate; 35 | public static String NewVersionAvailable; 36 | public static String InvalidSpigotResourceID; 37 | public static String FailedCheckingUpdate; 38 | public static String LoadedFromLocalCache; 39 | public static String Processing; 40 | public static String HelpMessageHeader; 41 | public static List HelpMessageList; 42 | 43 | public static String replace(String str) { 44 | return str.replace("&", "§"); 45 | } 46 | 47 | public static List replace(List strList) { 48 | List resultList = new ArrayList<>(); 49 | strList.forEach(str -> { 50 | resultList.add(replace(str)); 51 | }); 52 | return resultList; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/controller/DeliveryController.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.controller; 2 | 3 | import cc.eumc.uniban.config.PluginConfig; 4 | import de.cgrotz.kademlia.Kademlia; 5 | import de.cgrotz.kademlia.config.UdpListener; 6 | import de.cgrotz.kademlia.node.Key; 7 | import de.cgrotz.kademlia.node.Node; 8 | 9 | import java.util.ArrayList; 10 | import java.util.Base64; 11 | import java.util.List; 12 | 13 | public class DeliveryController { 14 | static boolean ready = false; 15 | Kademlia kad; 16 | UniBanController controller; 17 | 18 | public DeliveryController(UniBanController controller) { 19 | this.controller = controller; 20 | 21 | // TODO DHT 22 | // In production the nodeId would preferably be static for one node 23 | kad = new Kademlia(Key.build(PluginConfig.NodeID), PluginConfig.Legacy_Host +":"+PluginConfig.Legacy_Port); 24 | // Bootstrap using a remote server (there is no special configuration on the remote server necessary) 25 | controller.runTaskLater(() -> { 26 | controller.sendInfo("[DHT] Preparing bootstrap"); 27 | List udpListenerCollection = new ArrayList<>(); 28 | PluginConfig.Subscriptions.forEach((serverEntry, key) -> { 29 | udpListenerCollection.add(new UdpListener(serverEntry.host, serverEntry.port)); 30 | }); 31 | kad.bootstrap(Node.builder().advertisedListeners(udpListenerCollection).build()); 32 | controller.sendInfo("[DHT] Ready"); 33 | ready = true; 34 | }, 1); 35 | } 36 | 37 | /** 38 | * Get value from the DHT 39 | * @param key Key.build() 40 | * @return value decoded with base64 or null if not ready 41 | */ 42 | public String get(Key key) { 43 | if (!ready) return null; 44 | 45 | return new String(Base64.getDecoder().decode(kad.get(key).getBytes())); 46 | } 47 | 48 | /** 49 | * Put value into the DHT 50 | * @param key Key.build() 51 | * @param value will be encoded with base64 52 | * @return false: not ready 53 | */ 54 | public boolean put(Key key, String value) { 55 | if (!ready) return false; 56 | 57 | kad.put(key, Base64.getEncoder().encodeToString(value.getBytes())); 58 | return true; 59 | } 60 | 61 | public static boolean isReady() { 62 | return ready; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/config/BungeeConfig.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.config; 2 | 3 | import cc.eumc.uniban.UniBanBungeePlugin; 4 | import net.md_5.bungee.config.Configuration; 5 | 6 | import java.io.File; 7 | import java.util.HashSet; 8 | import java.util.List; 9 | import java.util.Set; 10 | 11 | public class BungeeConfig extends PluginConfig { 12 | UniBanBungeePlugin plugin; 13 | public BungeeConfig(UniBanBungeePlugin instance) { 14 | super(); 15 | 16 | // T√ODO Support for bungeecord 17 | // Fix: Broadcast disabled wrongly on BungeeCord 18 | this.plugin = instance; 19 | 20 | new ThirdPartySupportConfig(plugin.getDataFolder(), 21 | instance.getProxy().getPluginManager().getPlugin("AdvancedBan")!=null, 22 | instance.getProxy().getPluginManager().getPlugin("BungeeAdminTool")!=null, 23 | instance.getProxy().getPluginManager().getPlugin("BungeeBan")!=null, 24 | instance.getProxy().getPluginManager().getPlugin("LiteBans")!=null, 25 | new File(plugin.getDataFolder(), "banned-players.json").exists() 26 | ); 27 | 28 | } 29 | 30 | 31 | @Override 32 | public void saveConfig() { 33 | UniBanBungeePlugin.getInstance().saveConfig(); 34 | } 35 | 36 | @Override 37 | public boolean configGetBoolean(String path, Boolean def) { 38 | return getConfig().getBoolean(path, def); 39 | } 40 | 41 | @Override 42 | public String configGetString(String path, String def) { 43 | return getConfig().getString(path, def); 44 | } 45 | 46 | @Override 47 | public Double configGetDouble(String path, Double def) { 48 | return getConfig().getDouble(path, def); 49 | } 50 | 51 | @Override 52 | public int configGetInt(String path, int def) { 53 | return getConfig().getInt(path, def); 54 | } 55 | 56 | public Configuration getConfig() { 57 | return UniBanBungeePlugin.getInstance().getConfig(); 58 | } 59 | 60 | @Override 61 | public List configGetStringList(String path) { 62 | return getConfig().getStringList(path); 63 | } 64 | 65 | @Override 66 | public boolean configIsSection(String path) { 67 | return getConfig().getSection(path)!=null; 68 | } 69 | 70 | @Override 71 | public Set getConfigurationSectionKeys(String path) { 72 | return new HashSet<>(getConfig().getSection(path).getKeys()); 73 | } 74 | 75 | @Override 76 | public void configSet(String path, Object object) { 77 | getConfig().set(path, object); 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/config/BukkitConfig.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.config; 2 | 3 | import cc.eumc.uniban.UniBanBukkitPlugin; 4 | import org.bukkit.configuration.file.FileConfiguration; 5 | 6 | import java.io.File; 7 | import java.util.List; 8 | import java.util.Set; 9 | 10 | public class BukkitConfig extends PluginConfig { 11 | UniBanBukkitPlugin plugin; 12 | 13 | public BukkitConfig(UniBanBukkitPlugin instance) { 14 | super(); 15 | this.plugin = instance; 16 | 17 | new ThirdPartySupportConfig(plugin.getDataFolder(), 18 | instance.getServer().getPluginManager().isPluginEnabled("AdvancedBan"), 19 | instance.getServer().getPluginManager().isPluginEnabled("BungeeAdminTool"), 20 | instance.getServer().getPluginManager().isPluginEnabled("BungeeBan"), 21 | instance.getServer().getPluginManager().isPluginEnabled("LiteBans"), 22 | new File(plugin.getDataFolder(), "banned-players.json").exists() 23 | ); 24 | 25 | if (BukkitConfig.ConfigVersion != BukkitConfig.PluginConfigVersion) { 26 | instance.getLogger().warning("Your configuration version is " + BukkitConfig.ConfigVersion + " which may not be well supported by the plugin. It is suggested that you backup and delete it, then reload UniBan."); 27 | } 28 | } 29 | 30 | @Override 31 | public void saveConfig() { 32 | UniBanBukkitPlugin.getInstance().saveConfig(); 33 | } 34 | 35 | @Override 36 | public boolean configGetBoolean(String path, Boolean def) { 37 | return getConfig().getBoolean(path, def); 38 | } 39 | 40 | @Override 41 | public String configGetString(String path, String def) { 42 | return getConfig().getString(path, def); 43 | } 44 | 45 | @Override 46 | public Double configGetDouble(String path, Double def) { 47 | return getConfig().getDouble(path, def); 48 | } 49 | 50 | @Override 51 | public int configGetInt(String path, int def) { 52 | return getConfig().getInt(path, def); 53 | } 54 | 55 | public FileConfiguration getConfig() { 56 | return UniBanBukkitPlugin.getInstance().getConfig(); 57 | } 58 | 59 | @Override 60 | public List configGetStringList(String path) { 61 | return getConfig().getStringList(path); 62 | } 63 | 64 | @Override 65 | public boolean configIsSection(String path) { 66 | return getConfig().isConfigurationSection(path); 67 | } 68 | 69 | @Override 70 | public Set getConfigurationSectionKeys(String path) { 71 | return getConfig().getConfigurationSection(path).getKeys(false); 72 | } 73 | 74 | @Override 75 | public void configSet(String path, Object object) { 76 | getConfig().set(path, object); 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/task/LocalBanListRefreshTask.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.task; 2 | 3 | import cc.eumc.uniban.config.PluginConfig; 4 | import cc.eumc.uniban.config.ThirdPartySupportConfig; 5 | import cc.eumc.uniban.controller.UniBanController; 6 | import cc.eumc.uniban.util.AdvancedBanSupport; 7 | import cc.eumc.uniban.util.BungeeBanSupport; 8 | import cc.eumc.uniban.util.LiteBansSupport; 9 | import cc.eumc.uniban.util.VanillaListSupport; 10 | import org.bukkit.BanEntry; 11 | import org.bukkit.BanList; 12 | import org.bukkit.Bukkit; 13 | import org.bukkit.OfflinePlayer; 14 | 15 | import java.util.HashSet; 16 | import java.util.Set; 17 | import java.util.UUID; 18 | 19 | public class LocalBanListRefreshTask implements Runnable { 20 | final UniBanController controller; 21 | 22 | boolean isBungee; 23 | 24 | boolean running = false; 25 | 26 | public LocalBanListRefreshTask(UniBanController instance, boolean isBungee) { 27 | this.controller = instance; 28 | this.isBungee = isBungee; 29 | } 30 | 31 | @Override 32 | public void run() { 33 | if (running) { 34 | return; 35 | } 36 | running = true; 37 | 38 | Set uuidSet = new HashSet<>(); 39 | 40 | if (!isBungee) { 41 | for (OfflinePlayer offlinePlayer : Bukkit.getServer().getBannedPlayers()) { 42 | BanEntry banEntry = Bukkit.getServer().getBanList(BanList.Type.NAME).getBanEntry(offlinePlayer.getName()); 43 | if (banEntry != null) { 44 | if (controller.shouldIgnoreReason(banEntry.getReason())) { 45 | continue; 46 | } 47 | } 48 | //if (offlinePlayer.hasPlayedBefore()) { 49 | uuidSet.add(offlinePlayer.getUniqueId()); 50 | //} 51 | } 52 | } 53 | 54 | if (ThirdPartySupportConfig.AdvancedBan) { 55 | uuidSet.addAll(AdvancedBanSupport.fetchAllBanned(controller)); 56 | } 57 | // TODO Support for BungeeAdminTool 58 | /*if (ThirdPartySupportConfig.BungeeAdminTool) { 59 | uuidSet.addAll(BungeeAdminToolSupport.fetchAllBanned(controller)); 60 | }*/ 61 | if (ThirdPartySupportConfig.BungeeBan) { 62 | uuidSet.addAll(BungeeBanSupport.fetchAllBanned(controller)); 63 | } 64 | if (ThirdPartySupportConfig.LiteBans) { 65 | uuidSet.addAll(LiteBansSupport.fetchAllBanned(controller)); 66 | } 67 | if (ThirdPartySupportConfig.VanillaList) { 68 | uuidSet.addAll(VanillaListSupport.fetchAllBanned(controller)); 69 | } 70 | 71 | controller.updateLocalBanListCache(uuidSet); 72 | 73 | if (PluginConfig.ActiveMode_Enabled) { 74 | controller.sendLocalBanListToURL(); 75 | } 76 | 77 | running = false; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/listener/BukkitPlayerListener.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.listener; 2 | 3 | import cc.eumc.uniban.UniBanBukkitPlugin; 4 | import cc.eumc.uniban.config.BukkitConfig; 5 | import cc.eumc.uniban.config.Message; 6 | import cc.eumc.uniban.config.PluginConfig; 7 | import org.bukkit.Bukkit; 8 | import org.bukkit.entity.Player; 9 | import org.bukkit.event.EventHandler; 10 | import org.bukkit.event.Listener; 11 | import org.bukkit.event.player.PlayerLoginEvent; 12 | 13 | public class BukkitPlayerListener implements Listener { 14 | final UniBanBukkitPlugin plugin; 15 | public BukkitPlayerListener(UniBanBukkitPlugin instance) { 16 | this.plugin = instance; 17 | } 18 | 19 | @EventHandler 20 | public void onPlayerLogin(PlayerLoginEvent e) { 21 | if (PluginConfig.UUIDWhitelist.contains(e.getPlayer().getUniqueId().toString()) || (!e.getPlayer().isOp() && e.getPlayer().hasPermission("uniban.ignore"))) { 22 | return; 23 | } 24 | 25 | boolean warned = false; 26 | boolean banned = false; 27 | int count = plugin.getController().getBannedServerAmount(e.getPlayer().getUniqueId()); 28 | if (BukkitConfig.WarnThreshold > 0 && count >= BukkitConfig.WarnThreshold) { 29 | warned = true; 30 | if (!(e.getPlayer().isOp() && PluginConfig.IgnoreOP)) { 31 | String warningMessage = Message.MessagePrefix + Message.WarningMessage 32 | .replace("{player}", e.getPlayer().getName()) 33 | .replace("{uuid}", e.getPlayer().getUniqueId().toString()) 34 | .replace("{number}", String.valueOf(count)); 35 | plugin.getLogger().info(warningMessage); 36 | for (Player p : Bukkit.getOnlinePlayers()) { 37 | // TODO Fix: Warning spam 38 | if ((BukkitConfig.BroadcastWarning && p != e.getPlayer()) 39 | || (p.hasPermission("uniban.getnotified") || p.hasPermission("uniban.admin"))) { 40 | p.sendMessage(warningMessage); 41 | } 42 | } 43 | } 44 | } 45 | if (BukkitConfig.BanThreshold > 0 && count >= BukkitConfig.BanThreshold) { 46 | banned = true; 47 | if (!(e.getPlayer().isOp() && PluginConfig.IgnoreOP)) 48 | e.disallow(PlayerLoginEvent.Result.KICK_BANNED, Message.BannedOnlineKickMessage.replace("{number}", String.valueOf(count))); 49 | } 50 | 51 | // OP check moved here because if it is bypassed before ban check, we will not know if one of the staff/opped players are banned somewhere 52 | if (PluginConfig.IgnoreOP && e.getPlayer().isOp() && (warned || banned)) { 53 | plugin.getLogger().info(Message.MessagePrefix + String.format(Message.IgnoredOP, e.getPlayer().getName())); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/command/BukkitCommand.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.command; 2 | 3 | import cc.eumc.uniban.UniBanBukkitPlugin; 4 | import cc.eumc.uniban.controller.BukkitCommandController; 5 | import cc.eumc.uniban.exception.CommandBreakException; 6 | import cc.eumc.uniban.serverinterface.BukkitPlayerInfo; 7 | import org.bukkit.command.Command; 8 | import org.bukkit.command.CommandExecutor; 9 | import org.bukkit.command.CommandSender; 10 | import org.bukkit.command.TabExecutor; 11 | 12 | import java.util.ArrayList; 13 | import java.util.Arrays; 14 | import java.util.List; 15 | import java.util.stream.Collectors; 16 | 17 | public class BukkitCommand implements CommandExecutor, TabExecutor { 18 | UniBanBukkitPlugin plugin; 19 | BukkitCommandController commandController; 20 | private String[] commands = {"help", "check", "lookup", "subscribe", "share", "whitelist", "exempt", "reload"}; 21 | private String[] whitelistSubcommands = {"add", "remove"}; 22 | 23 | public BukkitCommand(UniBanBukkitPlugin instance) { 24 | this.plugin = instance; 25 | commandController = new BukkitCommandController(instance, plugin.getBukkitConfig()); 26 | } 27 | 28 | @Override 29 | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { 30 | if (sender.hasPermission("uniban.admin")) { 31 | /* 32 | if (args.length == 2 && args[0].equalsIgnoreCase("lookupuuid")) { 33 | sender.sendMessage(""); 34 | UniBanController.nameToUUID(args[1]); 35 | return true; 36 | } 37 | */ 38 | 39 | List msgLines = null; 40 | try { 41 | msgLines = commandController.executeCommand(args, plugin.getController(), new BukkitPlayerInfo<>(sender)); 42 | } catch (CommandBreakException ignored) { 43 | if (msgLines != null) { 44 | for (String line : msgLines) { 45 | sender.sendMessage(line); 46 | } 47 | } 48 | } 49 | } 50 | else { 51 | sender.sendMessage("[UniBan] §eSorry."); 52 | } 53 | return true; 54 | } 55 | 56 | 57 | @Override 58 | public List onTabComplete(CommandSender sender, Command command, String alias, String[] args) { 59 | // Fix: tab complete still work even if a player does not have permission "uniban.admin" 60 | if (!sender.hasPermission("uniban.admin")) return new ArrayList<>(); 61 | 62 | if (args.length > 2) 63 | return new ArrayList<>(); 64 | else if (args.length == 2) 65 | if (args[0].equalsIgnoreCase("whitelist")) 66 | // Fix: Tab complete won't work for sub-commands 67 | return Arrays.stream(whitelistSubcommands).filter(s -> s.startsWith(args[1])).collect(Collectors.toList()); 68 | else if (args[0].equalsIgnoreCase("exempt")) 69 | return Arrays.stream(plugin.getBukkitConfig().getSubscriptions()).filter(s -> s.startsWith(args[1])).collect(Collectors.toList()); 70 | else 71 | return new ArrayList<>(); 72 | else if (args.length == 1) 73 | return Arrays.stream(commands).filter(s -> s.startsWith(args[0])).collect(Collectors.toList()); 74 | else 75 | return Arrays.asList(commands); 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/listener/BungeePlayerListener.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.listener; 2 | 3 | import cc.eumc.uniban.UniBanBungeePlugin; 4 | import cc.eumc.uniban.config.BungeeConfig; 5 | import cc.eumc.uniban.config.Message; 6 | import cc.eumc.uniban.config.PluginConfig; 7 | import cc.eumc.uniban.controller.AccessController; 8 | import cc.eumc.uniban.controller.UniBanController; 9 | import net.md_5.bungee.api.ServerPing; 10 | import net.md_5.bungee.api.chat.BaseComponent; 11 | import net.md_5.bungee.api.chat.TextComponent; 12 | import net.md_5.bungee.api.event.LoginEvent; 13 | import net.md_5.bungee.api.event.ProxyPingEvent; 14 | import net.md_5.bungee.api.plugin.Listener; 15 | import net.md_5.bungee.event.EventHandler; 16 | import net.md_5.bungee.event.EventPriority; 17 | 18 | import java.net.InetSocketAddress; 19 | import java.util.UUID; 20 | 21 | public class BungeePlayerListener implements Listener { 22 | final UniBanBungeePlugin plugin; 23 | AccessController accessController = new AccessController(); 24 | 25 | public BungeePlayerListener(UniBanBungeePlugin instance) { 26 | this.plugin = instance; 27 | } 28 | 29 | @EventHandler 30 | public void onPlayerLogin(LoginEvent e) { 31 | if (!e.getConnection().isOnlineMode()) 32 | return; 33 | 34 | UUID uuid = e.getConnection().getUniqueId(); 35 | if (PluginConfig.UUIDWhitelist.contains(uuid.toString())) { 36 | return; 37 | } 38 | 39 | int count = plugin.getController().getBannedServerAmount(e.getConnection().getUniqueId()); 40 | if (BungeeConfig.WarnThreshold > 0 && count >= BungeeConfig.WarnThreshold) { 41 | String warningMessage = Message.MessagePrefix + Message.WarningMessage 42 | .replace("{player}", e.getConnection().getName()) 43 | .replace("{uuid}", e.getConnection().getUniqueId().toString()) 44 | .replace("{number}", String.valueOf(count)); 45 | plugin.getLogger().info(warningMessage); 46 | 47 | plugin.getProxy().getPlayers().forEach(proxiedPlayer -> { 48 | // TODO Fix: Warning spam 49 | if ((BungeeConfig.BroadcastWarning && proxiedPlayer.getUniqueId() != e.getConnection().getUniqueId()) 50 | || (proxiedPlayer.hasPermission("uniban.getnotified") || proxiedPlayer.hasPermission("uniban.admin"))) { 51 | proxiedPlayer.sendMessage(warningMessage); 52 | } 53 | }); 54 | } 55 | if (BungeeConfig.BanThreshold > 0 && count >= BungeeConfig.BanThreshold) { 56 | BaseComponent[] reason = TextComponent.fromLegacyText(Message.BannedOnlineKickMessage.replace("{number}", String.valueOf(count))); 57 | e.getConnection().disconnect(reason); 58 | e.setCancelled(true); 59 | e.setCancelReason(reason); 60 | } 61 | 62 | } 63 | 64 | @EventHandler(priority = EventPriority.LOWEST) 65 | public void onListPing(ProxyPingEvent e) { 66 | if (!PluginConfig.ViaServerListPing_Enabled) { 67 | return; 68 | } 69 | 70 | InetSocketAddress address = e.getConnection().getVirtualHost(); 71 | if (address == null) { 72 | return; 73 | } 74 | if (!address.getHostName().equals("UNIBAN")) { 75 | return; 76 | } 77 | 78 | String host = e.getConnection().getAddress().getHostString(); 79 | if (!accessController.canAccess(host)) { 80 | // if host was blocked 81 | return; 82 | } 83 | 84 | UniBanController controller = plugin.getController(); 85 | controller.sendInfo("Ban-list request from: " + host); 86 | ServerPing response = e.getResponse(); 87 | response.setDescriptionComponent(new TextComponent(controller.getBanListJson())); 88 | e.setResponse(response); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /src/main/resources/config.yml: -------------------------------------------------------------------------------- 1 | ConfigVersion: 7 2 | Settings: 3 | # Everyone except the target will be warned if enabled 4 | BroadcastWarning: false 5 | # Set to -1 to disable 6 | WarnThreshold: 1 7 | BanThreshold: 1 8 | IgnoreOP: true 9 | # TemporarilyPauseUpdateThreshold: 5 10 | Broadcast: 11 | Enabled: true 12 | ViaServerListPing: 13 | Enabled: true 14 | ActiveMode: 15 | Enabled: false 16 | PostUrl: https://example.com/example.php 17 | PostSecret: unibancopy 18 | LegacyWebServer: 19 | Enabled: false 20 | Host: '0.0.0.0' 21 | Port: 60009 22 | Threads: 2 23 | Password: 'UniBan' 24 | # Case-insensitive 25 | ExcludeIfReasonContain: 26 | - 'local' 27 | AccessControl: 28 | Enabled: true 29 | MinPeriodPerServer: 1.0 30 | Blacklist: 31 | Enabled: false 32 | IPList: 33 | - '*' 34 | Whitelist: 35 | Enabled: true 36 | IPList: 37 | - 'localhost' 38 | Tasks: 39 | # Unit: minute 40 | LocalBanListRefreshPeriod: 1.0 41 | SubscriptionRefreshPeriod: 10.0 42 | SubscriptionGetConnectTimeout: 5000 43 | SubscriptionGetReadTimeout: 5000 44 | 45 | Subscription: 46 | ExampleServer: 47 | Host: 'server.eumc.cc' 48 | Port: 60009 49 | Password: 'UniBan' 50 | PublicBanlistURLExample: 51 | URL: 'https://uniban.eumc.cc/public' 52 | 53 | UUIDWhitelist: 54 | - '4bac238b-806f-4bb7-be4f-00ec9923387f' 55 | 56 | Message: 57 | WarningMessage: '&bUniban &3&l> &eWarning: Player {player}({uuid}) has been banned from another {number} server(s).' 58 | BannedOnlineKickMessage: '&eSorry, you have been banned from another {number} server(s).' 59 | MessagePrefix: 'UniBan &3> &r' 60 | IgnoredOP: 'Ignored OP: %s' 61 | PlayerNotExist: 'Player %s does not exist.' 62 | PlayerState: 'Player %s state: %s' 63 | PlayerBanned: '&cBanned from: ' 64 | PlayerNormal: '&anormal' 65 | InvalidSubscriptionKey: '&eInvalid subscription key' 66 | SubscriptionKeyAdded: 'Successfully added %s to your subscription list.' 67 | YourSubscriptionKey: 'Here''s the sharing link of your server''s Subscription Key which contains your address and connection password:' 68 | SubscriptionKeyLink: 'https://uniban.eumc.cc/share.php?key=%s' 69 | SubscriptionExempted: 'Successfully exempted server %s from subscription list temporarily.' 70 | FailedExempting: 'Failed exempting %s. Does that subscription exist?' 71 | WhitelistAdded: 'Player %s has been added to whitelist' 72 | WhitelistRemoved: 'Player %s has been removed from whitelist' 73 | Reloaded: 'Reloaded.' 74 | Error: 'Error: %s' 75 | SubscriptionsHeader: 'Subscriptions [%s] -----' 76 | ThirdPartyPluginSupportHeader: 'Third-party Banning Plugin Support -----' 77 | Encrypted: 'Encrypted' 78 | PluginEnabled: '&lEnabled' 79 | PluginNotFound: '&oNot Found' 80 | BroadcastStarted: 'UniBan broadcast started on %s:%s (%s Threads)' 81 | BroadcastActiveModeEnabled: 'UniBan broadcast service is running under active mode.' 82 | BroadcastViaServerListPing: 'UniBan is delivering ban-list via server list ping.' 83 | BroadcastFailed: 'Failed starting broadcast server' 84 | UpToDate: 'You are up-to-date.' 85 | NewVersionAvailable: 'There is a newer version %s available at §n https://www.spigotmc.org/resources/74747/' 86 | InvalidSpigotResourceID: 'It looks like you are using an unsupported version of UniBan. Please manually look for update.' 87 | FailedCheckingUpdate: 'Error occurred when checking update' 88 | LoadedFromLocalCache: 'Loaded %s banned players from ban-list cache.' 89 | Processing: 'Just a sec...' 90 | HelpMessageHeader: 'Usage:' 91 | HelpMessageList: 92 | - '/uniban lookup <&lName&r>' 93 | - '/uniban check <&lPlayer/UUID&r>' 94 | - '/uniban whitelist <“&ladd&r”/“&lremove&r”> <&lPlayer/UUID>' 95 | - '/uniban share <&lYour Server Hostname&r, eg. &nexample.com&r>' 96 | - '/uniban subscribe <&lSubscription Key&r>' 97 | - '/uniban exempt <&lServer Address&r>' 98 | - '/uniban reload' 99 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/controller/UniBanBukkitController.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.controller; 2 | 3 | import cc.eumc.uniban.UniBanBukkitPlugin; 4 | import cc.eumc.uniban.config.BukkitConfig; 5 | import cc.eumc.uniban.config.Message; 6 | import cc.eumc.uniban.serverinterface.BukkitPlayerInfo; 7 | import cc.eumc.uniban.serverinterface.PlayerInfo; 8 | import org.bukkit.Bukkit; 9 | import org.bukkit.configuration.file.FileConfiguration; 10 | 11 | import java.io.File; 12 | import java.util.List; 13 | import java.util.Set; 14 | import java.util.UUID; 15 | 16 | public class UniBanBukkitController extends UniBanController { 17 | public UniBanBukkitController() { 18 | super(); 19 | //this.plugin = instance; 20 | if (super.serverStarted) { 21 | sendInfo(String.format(Message.BroadcastStarted, BukkitConfig.Legacy_Host, BukkitConfig.Legacy_Port, BukkitConfig.Legacy_Threads)); 22 | } 23 | else if (BukkitConfig.EnableBroadcast) { 24 | if (BukkitConfig.ActiveMode_Enabled) { 25 | sendInfo(Message.BroadcastActiveModeEnabled); 26 | } 27 | else if (BukkitConfig.ViaServerListPing_Enabled) { 28 | sendInfo(Message.BroadcastViaServerListPing); 29 | } 30 | else if (BukkitConfig.Legacy_Enabled) { 31 | sendSevere(Message.BroadcastFailed); 32 | } 33 | } 34 | } 35 | 36 | @Override 37 | public File getDataFolder() { 38 | return UniBanBukkitPlugin.getInstance().getDataFolder(); 39 | } 40 | 41 | @Override 42 | public void sendInfo(String message) { 43 | UniBanBukkitPlugin.getInstance().getLogger().info(message); 44 | } 45 | 46 | @Override 47 | public void sendWarning(String message) { 48 | UniBanBukkitPlugin.getInstance().getLogger().warning(message); 49 | } 50 | 51 | @Override 52 | public void sendSevere(String message) { 53 | UniBanBukkitPlugin.getInstance().getLogger().severe(message); 54 | } 55 | 56 | @Override 57 | public void saveConfig() { 58 | UniBanBukkitPlugin.getInstance().saveConfig(); 59 | } 60 | 61 | @Override 62 | PlayerInfo getPlayerInfoFromUUID(UUID uuid) { 63 | return new BukkitPlayerInfo(UniBanBukkitPlugin.getInstance().getServer().getPlayer(uuid)); 64 | } 65 | 66 | @Override 67 | public boolean configGetBoolean(String path, Boolean def) { 68 | return getConfig().getBoolean(path, def); 69 | } 70 | 71 | @Override 72 | public String configGetString(String path, String def) { 73 | return getConfig().getString(path, def); 74 | } 75 | 76 | @Override 77 | public Double configGetDouble(String path, Double def) { 78 | return getConfig().getDouble(path, def); 79 | } 80 | 81 | @Override 82 | public int configGetInt(String path, int def) { 83 | return getConfig().getInt(path, def); 84 | } 85 | 86 | public FileConfiguration getConfig() { 87 | return UniBanBukkitPlugin.getInstance().getConfig(); 88 | } 89 | 90 | @Override 91 | public List configGetStringList(String path) { 92 | return UniBanBukkitPlugin.getInstance().getConfig().getStringList(path); 93 | } 94 | 95 | @Override 96 | public boolean configIsSection(String path) { 97 | return getConfig().isConfigurationSection(path); 98 | } 99 | 100 | @Override 101 | public Set getConfigurationSectionKeys(String path) { 102 | return getConfig().getConfigurationSection(path).getKeys(false); 103 | } 104 | 105 | @Override 106 | public void configSet(String path, Object object) { 107 | UniBanBukkitPlugin.getInstance().getConfig().set(path, object); 108 | } 109 | 110 | @Override 111 | public void runTaskLater(Runnable task, int delayTick) { 112 | Bukkit.getScheduler().runTaskLaterAsynchronously(UniBanBukkitPlugin.getInstance(), task, delayTick); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/controller/UniBanBungeeController.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.controller; 2 | 3 | import cc.eumc.uniban.UniBanBungeePlugin; 4 | import cc.eumc.uniban.config.BungeeConfig; 5 | import cc.eumc.uniban.config.Message; 6 | import cc.eumc.uniban.serverinterface.BungeePlayerInfo; 7 | import cc.eumc.uniban.serverinterface.PlayerInfo; 8 | import net.md_5.bungee.api.connection.ProxiedPlayer; 9 | import net.md_5.bungee.config.Configuration; 10 | 11 | import java.io.File; 12 | import java.util.HashSet; 13 | import java.util.List; 14 | import java.util.Set; 15 | import java.util.UUID; 16 | import java.util.concurrent.TimeUnit; 17 | 18 | public class UniBanBungeeController extends UniBanController { 19 | 20 | public UniBanBungeeController() { 21 | super(); 22 | 23 | // Fix: Broadcast status will not be displayed on BungeeCord 24 | if (super.serverStarted) { 25 | sendInfo(String.format(Message.BroadcastStarted, BungeeConfig.Legacy_Host, BungeeConfig.Legacy_Port, BungeeConfig.Legacy_Threads)); 26 | } 27 | else if (BungeeConfig.EnableBroadcast) { 28 | if (BungeeConfig.ActiveMode_Enabled) { 29 | sendInfo(Message.BroadcastActiveModeEnabled); 30 | } 31 | else if (BungeeConfig.ViaServerListPing_Enabled) { 32 | sendInfo(Message.BroadcastViaServerListPing); 33 | } 34 | else if (BungeeConfig.Legacy_Enabled) { 35 | sendSevere(Message.BroadcastFailed); 36 | } 37 | } 38 | 39 | } 40 | 41 | @Override 42 | public File getDataFolder() { 43 | return UniBanBungeePlugin.getInstance().getDataFolder(); 44 | } 45 | 46 | @Override 47 | public void sendInfo(String message) { 48 | UniBanBungeePlugin.getInstance().getLogger().info(message); 49 | } 50 | 51 | @Override 52 | public void sendWarning(String message) { 53 | UniBanBungeePlugin.getInstance().getLogger().warning(message); 54 | } 55 | 56 | @Override 57 | public void sendSevere(String message) { 58 | UniBanBungeePlugin.getInstance().getLogger().severe(message); 59 | } 60 | 61 | @Override 62 | public void saveConfig() { 63 | UniBanBungeePlugin.getInstance().saveConfig(); 64 | } 65 | 66 | @Override 67 | PlayerInfo getPlayerInfoFromUUID(UUID uuid) { 68 | return new BungeePlayerInfo(UniBanBungeePlugin.getInstance().getProxy().getPlayer(uuid)); 69 | } 70 | 71 | @Override 72 | public boolean configGetBoolean(String path, Boolean def) { 73 | return getConfig().getBoolean(path, def); 74 | } 75 | 76 | @Override 77 | public String configGetString(String path, String def) { 78 | return getConfig().getString(path, def); 79 | } 80 | 81 | @Override 82 | public Double configGetDouble(String path, Double def) { 83 | return getConfig().getDouble(path, def); 84 | } 85 | 86 | @Override 87 | public int configGetInt(String path, int def) { 88 | return getConfig().getInt(path, def); 89 | } 90 | 91 | public Configuration getConfig() { 92 | return UniBanBungeePlugin.getInstance().getConfig(); 93 | } 94 | 95 | @Override 96 | public List configGetStringList(String path) { 97 | return getConfig().getStringList(path); 98 | } 99 | 100 | @Override 101 | public boolean configIsSection(String path) { 102 | return getConfig().getSection(path)!=null; 103 | } 104 | 105 | @Override 106 | public Set getConfigurationSectionKeys(String path) { 107 | return new HashSet<>(getConfig().getSection(path).getKeys()); 108 | } 109 | 110 | @Override 111 | public void configSet(String path, Object object) { 112 | getConfig().set(path, object); 113 | } 114 | 115 | @Override 116 | public void runTaskLater(Runnable task, int delayTick) { 117 | UniBanBungeePlugin.getInstance().getProxy().getScheduler().schedule(UniBanBungeePlugin.getInstance(), task, (int)((float)(delayTick)/20), TimeUnit.SECONDS); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | cc.eumc.uniban 8 | EusUniBan 9 | 1.3.3.1 10 | jar 11 | 12 | EusUniBan 13 | 14 | 15 | 1.8 16 | UTF-8 17 | 18 | 19 | 20 | clean package 21 | 22 | 23 | org.apache.maven.plugins 24 | maven-compiler-plugin 25 | 3.7.0 26 | 27 | ${java.version} 28 | ${java.version} 29 | 30 | 31 | 32 | org.apache.maven.plugins 33 | maven-shade-plugin 34 | 3.1.0 35 | 36 | 37 | package 38 | 39 | shade 40 | 41 | 42 | false 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | src/main/resources 51 | true 52 | 53 | 54 | 55 | 56 | 57 | 58 | spigotmc-repo 59 | https://hub.spigotmc.org/nexus/content/repositories/snapshots/ 60 | 61 | 62 | papermc 63 | https://papermc.io/repo/repository/maven-public/ 64 | 65 | 66 | bungeecord-repo 67 | https://oss.sonatype.org/content/repositories/snapshots 68 | 69 | 70 | sonatype 71 | https://oss.sonatype.org/content/groups/public/ 72 | 73 | 74 | central 75 | Maven Repository Switchboard 76 | https://repo1.maven.org/maven2/ 77 | 78 | false 79 | 80 | 81 | 82 | 83 | 84 | 85 | de.cgrotz 86 | kademlia 87 | 1.0.1 88 | 89 | 90 | org.jetbrains 91 | annotations 92 | 19.0.0 93 | provided 94 | 95 | 96 | org.spigotmc 97 | spigot-api 98 | 1.13.1-R0.1-SNAPSHOT 99 | provided 100 | 101 | 102 | com.destroystokyo.paper 103 | paper-api 104 | 1.13.2-R0.1-SNAPSHOT 105 | provided 106 | 107 | 108 | net.md-5 109 | bungeecord-api 110 | 1.14-SNAPSHOT 111 | jar 112 | provided 113 | 114 | 115 | net.md-5 116 | bungeecord-api 117 | 1.14-SNAPSHOT 118 | javadoc 119 | provided 120 | 121 | 122 | com.googlecode.json-simple 123 | json-simple 124 | 1.1.1 125 | 126 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/util/ServerListPing.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.util; 2 | 3 | import com.google.gson.Gson; 4 | 5 | import java.io.*; 6 | import java.net.InetSocketAddress; 7 | import java.net.Socket; 8 | 9 | /** 10 | * Simplified and fixed EOFException by Alan Richard on Jul 3, 2021 11 | * @author zh32 12 | */ 13 | public class ServerListPing { 14 | 15 | private InetSocketAddress host; 16 | private int timeout = 7000; 17 | private Gson gson = new Gson(); 18 | 19 | public void setAddress(InetSocketAddress host) { 20 | this.host = host; 21 | } 22 | 23 | public InetSocketAddress getAddress() { 24 | return this.host; 25 | } 26 | 27 | public void setTimeout(int timeout) { 28 | this.timeout = timeout; 29 | } 30 | 31 | int getTimeout() { 32 | return this.timeout; 33 | } 34 | 35 | public int readVarInt(DataInputStream in) throws IOException { 36 | int i = 0; 37 | int j = 0; 38 | while (true) { 39 | int k = in.read(); 40 | i |= (k & 0x7F) << j++ * 7; 41 | if (j > 5) throw new RuntimeException("VarInt too big"); 42 | if ((k & 0x80) != 128) break; 43 | } 44 | return i; 45 | } 46 | 47 | public void writeVarInt(DataOutputStream out, int paramInt) throws IOException { 48 | while (true) { 49 | if ((paramInt & 0xFFFFFF80) == 0) { 50 | out.writeByte(paramInt); 51 | return; 52 | } 53 | 54 | out.writeByte(paramInt & 0x7F | 0x80); 55 | paramInt >>>= 7; 56 | } 57 | } 58 | 59 | public StatusResponse fetchData(String remoteHost) throws IOException { 60 | 61 | Socket socket = new Socket(); 62 | OutputStream outputStream; 63 | DataOutputStream dataOutputStream; 64 | InputStream inputStream; 65 | InputStreamReader inputStreamReader; 66 | 67 | socket.setSoTimeout(this.timeout); 68 | 69 | socket.connect(host, timeout); 70 | 71 | outputStream = socket.getOutputStream(); 72 | dataOutputStream = new DataOutputStream(outputStream); 73 | 74 | inputStream = socket.getInputStream(); 75 | inputStreamReader = new InputStreamReader(inputStream); 76 | 77 | ByteArrayOutputStream b = new ByteArrayOutputStream(); 78 | DataOutputStream handshake = new DataOutputStream(b); 79 | handshake.writeByte(0x00); //packet id for handshake 80 | writeVarInt(handshake, 4); //protocol version 81 | String sendRemoteHost = remoteHost == null ? this.host.getHostString() : remoteHost; 82 | writeVarInt(handshake, sendRemoteHost.length()); //host length 83 | handshake.writeBytes(sendRemoteHost); //host string 84 | handshake.writeShort(host.getPort()); //port 85 | writeVarInt(handshake, 1); //state (1 for handshake) 86 | 87 | writeVarInt(dataOutputStream, b.size()); //prepend size 88 | dataOutputStream.write(b.toByteArray()); //write handshake packet 89 | 90 | 91 | dataOutputStream.writeByte(0x01); //size is only 1 92 | dataOutputStream.writeByte(0x00); //packet id for ping 93 | DataInputStream dataInputStream = new DataInputStream(inputStream); 94 | int size = readVarInt(dataInputStream); //size of packet 95 | int id = readVarInt(dataInputStream); //packet id 96 | 97 | if (id == -1) { 98 | throw new IOException("Premature end of stream."); 99 | } 100 | 101 | if (id != 0x00) { //we want a status response 102 | throw new IOException("Invalid packetID"); 103 | } 104 | int length = readVarInt(dataInputStream); //length of json string 105 | 106 | if (length == -1) { 107 | throw new IOException("Premature end of stream."); 108 | } 109 | 110 | if (length == 0) { 111 | throw new IOException("Invalid string length."); 112 | } 113 | 114 | byte[] in = new byte[length]; 115 | dataInputStream.readFully(in); //read json string 116 | String json = new String(in); 117 | // System.out.println(json); 118 | 119 | long now = System.currentTimeMillis(); 120 | dataOutputStream.writeByte(0x09); //size of packet 121 | dataOutputStream.writeByte(0x01); //0x01 for ping 122 | dataOutputStream.writeLong(now); //time!? 123 | 124 | readVarInt(dataInputStream); 125 | id = readVarInt(dataInputStream); 126 | if (id == -1) { 127 | throw new IOException("Premature end of stream."); 128 | } 129 | 130 | if (id != 0x01) { 131 | throw new IOException("Invalid packetID"); 132 | } 133 | 134 | StatusResponse response = gson.fromJson(json, StatusResponse.class); 135 | 136 | dataOutputStream.close(); 137 | outputStream.close(); 138 | inputStreamReader.close(); 139 | inputStream.close(); 140 | socket.close(); 141 | 142 | return response; 143 | } 144 | 145 | 146 | public class StatusResponse { 147 | private Description description; 148 | private String favicon; 149 | 150 | public Description getDescription() { 151 | return description; 152 | } 153 | 154 | public String getFavicon() { 155 | return favicon; 156 | } 157 | } 158 | 159 | public class Description { 160 | private String text; 161 | 162 | public String getText() { 163 | return text; 164 | } 165 | } 166 | } -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/UniBanBukkitPlugin.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban; 2 | 3 | import cc.eumc.uniban.command.BukkitCommand; 4 | import cc.eumc.uniban.config.*; 5 | import cc.eumc.uniban.controller.UniBanBukkitController; 6 | import cc.eumc.uniban.listener.BukkitPlayerListener; 7 | import cc.eumc.uniban.listener.PaperListener; 8 | import cc.eumc.uniban.task.LocalBanListRefreshTask; 9 | import cc.eumc.uniban.task.SubscriptionRefreshTask; 10 | import cc.eumc.uniban.task.UpdateCheckTask; 11 | import org.bukkit.Bukkit; 12 | import org.bukkit.plugin.java.JavaPlugin; 13 | import org.bukkit.scheduler.BukkitTask; 14 | 15 | import java.io.File; 16 | 17 | public final class UniBanBukkitPlugin extends JavaPlugin { 18 | static UniBanBukkitPlugin instance; 19 | BukkitTask Task_LocalBanListRefreshTask; 20 | BukkitTask Task_SubscriptionRefreshTask; 21 | UniBanBukkitController controller; 22 | BukkitConfig bukkitConfig; 23 | boolean isPaper = false; 24 | 25 | @Override 26 | public void onEnable() { 27 | instance = this; 28 | 29 | // Check if running Paper 30 | try { 31 | Class.forName("com.destroystokyo.paper.event.server.PaperServerListPingEvent"); 32 | isPaper = true; 33 | } catch (ClassNotFoundException ignore) { } 34 | 35 | reloadConfig(); 36 | 37 | controller = new UniBanBukkitController(); 38 | 39 | registerTask(); 40 | registerCommand(); 41 | 42 | Bukkit.getPluginManager().registerEvents(new BukkitPlayerListener(this), this); 43 | if (PluginConfig.EnableBroadcast && PluginConfig.ViaServerListPing_Enabled) { 44 | if (isPaper) { 45 | Bukkit.getPluginManager().registerEvents(new PaperListener(this), this); 46 | } else { 47 | getLogger().warning("Failed enabling ban-list delivery via server list ping: Paper server required."); 48 | } 49 | } 50 | 51 | getLogger().info("UniBan Enabled"); 52 | } 53 | 54 | @Override 55 | public void onDisable() { 56 | if (Task_LocalBanListRefreshTask != null) 57 | Task_LocalBanListRefreshTask.cancel(); 58 | if (Task_SubscriptionRefreshTask != null) 59 | Task_SubscriptionRefreshTask.cancel(); 60 | controller.destruct(); 61 | getLogger().info("UniBan Disabled"); 62 | } 63 | 64 | @Override 65 | public void reloadConfig() { 66 | File file = new File(getDataFolder(), "config.yml"); 67 | if (!file.exists()) { 68 | saveDefaultConfig(); 69 | } 70 | 71 | super.reloadConfig(); 72 | 73 | bukkitConfig = new BukkitConfig(this); 74 | 75 | showPluginInformation(); 76 | } 77 | 78 | public void showPluginInformation() { 79 | getLogger().info(String.format(Message.SubscriptionsHeader, BukkitConfig.Subscriptions.size())); 80 | for (ServerEntry serverEntry : BukkitConfig.Subscriptions.keySet()) { 81 | getLogger().info("* " + serverEntry.getAddress() + (BukkitConfig.Subscriptions.get(serverEntry.getAddress())!=null?" | "+Message.Encrypted:"")); 82 | } 83 | getLogger().info(Message.ThirdPartyPluginSupportHeader); 84 | getLogger().info("* AdvancedBan: " + (ThirdPartySupportConfig.AdvancedBan?Message.PluginEnabled:Message.PluginNotFound)); 85 | //getLogger().info(Message.MessagePrefix + "* BungeeAdminTool: " + (ThirdPartySupportConfig.BungeeAdminTool?Message.PluginEnabled:Message.PluginNotFound)); 86 | //getLogger().info(Message.MessagePrefix + "* BungeeBan: " + (ThirdPartySupportConfig.BungeeBan?Message.PluginEnabled:Message.PluginNotFound)); 87 | getLogger().info("* LiteBans: " + (ThirdPartySupportConfig.LiteBans?Message.PluginEnabled:Message.PluginNotFound)); 88 | getLogger().info("* VanillaList: " + (ThirdPartySupportConfig.VanillaList?Message.PluginEnabled:Message.PluginNotFound)); 89 | } 90 | 91 | public void reloadController() { 92 | if (controller != null) 93 | controller.destruct(); 94 | controller = new UniBanBukkitController(); 95 | } 96 | 97 | void registerCommand() { 98 | getCommand("uniban").setExecutor(new BukkitCommand(this)); 99 | } 100 | 101 | public void registerTask() { 102 | if (Task_LocalBanListRefreshTask != null) 103 | Task_LocalBanListRefreshTask.cancel(); 104 | if (PluginConfig.EnableBroadcast) 105 | Task_LocalBanListRefreshTask = Bukkit.getScheduler().runTaskTimerAsynchronously(this, new LocalBanListRefreshTask(getController(), false), 1, 106 | 20 * (int) (60 * PluginConfig.LocalBanListRefreshPeriod)); 107 | 108 | if (Task_SubscriptionRefreshTask != null) 109 | Task_SubscriptionRefreshTask.cancel(); 110 | Task_SubscriptionRefreshTask = Bukkit.getScheduler().runTaskTimerAsynchronously(this, new SubscriptionRefreshTask(getController()), 20, 111 | 20 * (int) (60 * PluginConfig.SubscriptionRefreshPeriod)); 112 | 113 | Bukkit.getScheduler().runTaskAsynchronously(this, new UpdateCheckTask(getDescription().getVersion(), 74747)); 114 | // TODO run IdentifySubscriptionTask 115 | } 116 | 117 | public UniBanBukkitController getController() { 118 | return controller; 119 | } 120 | 121 | public static UniBanBukkitPlugin getInstance() { 122 | return instance; 123 | } 124 | 125 | public BukkitConfig getBukkitConfig() { 126 | return bukkitConfig; 127 | } 128 | 129 | public boolean isPaper() { 130 | return isPaper; 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/UniBanBungeePlugin.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban; 2 | 3 | import cc.eumc.uniban.command.BungeeCommand; 4 | import cc.eumc.uniban.config.*; 5 | import cc.eumc.uniban.controller.UniBanBungeeController; 6 | import cc.eumc.uniban.listener.BungeePlayerListener; 7 | import cc.eumc.uniban.task.LocalBanListRefreshTask; 8 | import cc.eumc.uniban.task.SubscriptionRefreshTask; 9 | import cc.eumc.uniban.task.UpdateCheckTask; 10 | import com.google.common.io.ByteStreams; 11 | import net.md_5.bungee.api.plugin.Plugin; 12 | import net.md_5.bungee.api.scheduler.ScheduledTask; 13 | import net.md_5.bungee.config.Configuration; 14 | import net.md_5.bungee.config.ConfigurationProvider; 15 | import net.md_5.bungee.config.YamlConfiguration; 16 | 17 | import java.io.*; 18 | import java.util.concurrent.TimeUnit; 19 | 20 | public class UniBanBungeePlugin extends Plugin { 21 | static UniBanBungeePlugin instance; 22 | ScheduledTask Task_LocalBanListRefreshTask; 23 | ScheduledTask Task_SubscriptionRefreshTask; 24 | UniBanBungeeController controller; 25 | Configuration configuration; 26 | BungeeConfig bungeeConfig; 27 | 28 | @Override 29 | public void onEnable() { 30 | instance = this; 31 | if (!getDataFolder().exists()) { 32 | getDataFolder().mkdir(); 33 | } 34 | 35 | reloadConfig(); 36 | 37 | controller = new UniBanBungeeController(); 38 | 39 | registerTask(); 40 | registerCommand(); 41 | 42 | getProxy().getPluginManager().registerListener(this, new BungeePlayerListener(this)); 43 | 44 | getLogger().info("UniBan Enabled"); 45 | } 46 | 47 | private void saveDefaultConfig() { 48 | File configFile = new File(getDataFolder(), "config.yml"); 49 | if (!configFile.exists()) { 50 | try { 51 | configFile.createNewFile(); 52 | try (InputStream is = getResourceAsStream("config.yml"); 53 | OutputStream os = new FileOutputStream(configFile)) { 54 | ByteStreams.copy(is, os); 55 | } 56 | } catch (IOException e) { 57 | throw new RuntimeException("Unable to create config.yml", e); 58 | } 59 | } 60 | } 61 | 62 | @Override 63 | public void onDisable() { 64 | if (Task_LocalBanListRefreshTask != null) 65 | Task_LocalBanListRefreshTask.cancel(); 66 | if (Task_SubscriptionRefreshTask != null) 67 | Task_SubscriptionRefreshTask.cancel(); 68 | controller.destruct(); 69 | getLogger().info("UniBan Disabled"); 70 | } 71 | 72 | public void reloadConfig() { 73 | // Fix: Error when config was deleted before reloading 74 | File file = new File(getDataFolder(), "config.yml"); 75 | if (!file.exists()) { 76 | saveDefaultConfig(); 77 | } 78 | 79 | try { 80 | configuration = ConfigurationProvider.getProvider(YamlConfiguration.class).load(new File(getDataFolder(), "config.yml")); 81 | } catch (IOException e) { 82 | getProxy().getLogger().severe("Unable to load configuration."); 83 | } 84 | 85 | // Fix: Configuration will not be reloaded on Bungeecord 86 | bungeeConfig = new BungeeConfig(this); 87 | 88 | showPluginInformation(); 89 | } 90 | 91 | public void showPluginInformation() { 92 | getLogger().info(String.format(Message.SubscriptionsHeader, BukkitConfig.Subscriptions.size())); 93 | for (ServerEntry serverEntry : BungeeConfig.Subscriptions.keySet()) { 94 | getLogger().info("* " + serverEntry.getAddress() + (BungeeConfig.Subscriptions.get(serverEntry.getAddress())!=null?" | "+Message.Encrypted:"")); 95 | } 96 | 97 | getLogger().info(Message.ThirdPartyPluginSupportHeader); 98 | getLogger().info("* AdvancedBan: " + (ThirdPartySupportConfig.AdvancedBan?Message.PluginEnabled:Message.PluginNotFound)); 99 | //getLogger().info("* BungeeAdminTool: " + (ThirdPartySupportConfig.BungeeAdminTool?Message.PluginEnabled:Message.PluginNotFound)); 100 | getLogger().info("* BungeeBan: " + (ThirdPartySupportConfig.BungeeBan?Message.PluginEnabled: Message.PluginNotFound)); 101 | getLogger().info("* LiteBans: " + (ThirdPartySupportConfig.LiteBans?Message.PluginEnabled: Message.PluginNotFound)); 102 | getLogger().info("* VanillaList: " + (ThirdPartySupportConfig.VanillaList?Message.PluginEnabled: Message.PluginNotFound)); 103 | } 104 | 105 | public void reloadController() { 106 | if (controller != null) 107 | controller.destruct(); 108 | controller = new UniBanBungeeController(); 109 | } 110 | 111 | void registerCommand() { 112 | getProxy().getPluginManager().registerCommand(this, new BungeeCommand(this)); 113 | } 114 | 115 | public void registerTask() { 116 | // T√ODO Third-party Bungeecord ban-list plugin support 117 | if (Task_LocalBanListRefreshTask != null) 118 | Task_LocalBanListRefreshTask.cancel(); 119 | if (PluginConfig.EnableBroadcast) 120 | Task_LocalBanListRefreshTask = getProxy().getScheduler().schedule(this, new LocalBanListRefreshTask(getController(),true), 1, 121 | (int) (60 * PluginConfig.LocalBanListRefreshPeriod), TimeUnit.SECONDS); 122 | 123 | if (Task_SubscriptionRefreshTask != null) 124 | Task_SubscriptionRefreshTask.cancel(); 125 | Task_SubscriptionRefreshTask = getProxy().getScheduler().schedule(this, new SubscriptionRefreshTask(getController()), 20, 126 | (int) (60 * PluginConfig.SubscriptionRefreshPeriod), TimeUnit.SECONDS); 127 | 128 | getProxy().getScheduler().runAsync(this, new UpdateCheckTask(getDescription().getVersion(), 74747)); 129 | 130 | // TODO run IdentifySubscriptionTask 131 | } 132 | 133 | public UniBanBungeeController getController() { 134 | return controller; 135 | } 136 | 137 | public Configuration getConfig() { 138 | return configuration; 139 | } 140 | 141 | public void saveConfig() { 142 | try { 143 | ConfigurationProvider.getProvider(YamlConfiguration.class).save(configuration, new File(getDataFolder(), "config.yml")); 144 | } catch (IOException e) { 145 | e.printStackTrace(); 146 | getLogger().severe("Failed saving configuration file."); 147 | } 148 | } 149 | 150 | public static UniBanBungeePlugin getInstance() { 151 | return instance; 152 | } 153 | 154 | public BungeeConfig getBungeeConfig() { 155 | return bungeeConfig; 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EusUniBan 2 | 3 | A decentralized ban-list sharing plugin for Minecraft server. 4 | 5 | ![ScreenShot.png](https://raw.githubusercontent.com/leavessoft/EusUniBan/master/ScreenShot.png) 6 | ![Demo](https://raw.githubusercontent.com/EusMC/UniBan-Website/master/img/2_compressed.gif) 7 | 8 | ## Features 9 | 10 | * Sharing your ban-list without a central server 11 | * Benefiting from other servers without changing your own local ban-list 12 | * Subscribing servers you trust 13 | * It works with third-party banning plugins: including AdvancedBan, BungeeBan and LiteBans 14 | * Customizable warning & banning threshold 15 | * Encrypting your shared ban-list with customizable password 16 | * Extendable 17 | * Access control: 18 | * Server whitelist 19 | * Server blacklist 20 | * Request frequency controlling 21 | 22 | 23 | 24 | ## Extra Requirement 25 | 26 | * An open TCP port that is accessible by public 27 | 28 | 29 | 30 | ## Commands 31 | 32 | | Command | 33 | | ------------------------------------------------------------ | 34 | | /uniban lookup \<**Name**> | 35 | | /uniban check <**Player/UUID**> | 36 | | /uniban whitelist <"**add**"/"**remove**"> <**Player/UUID**> | 37 | | /uniban subscribe \<**Subscription Key**\> | 38 | | /uniban share \<**Your Server Hostname**, eg. example.com\> | 39 | | /uniban exempt \<**Server Address**\> | 40 | | /uniban reload | 41 | 42 | 43 | 44 | ## Permissions 45 | 46 | | Permission | Description | Default | 47 | | ------------------ | ------------------------------------------------------------ | ------- | 48 | | uniban.admin | Permission to use /uniban command | ops | 49 | | uniban.getnotified | Permission to get notified when a player who reached the warning threshold enters | ops | 50 | | uniban.ignore | Permission to bypass warning and banning | null | 51 | 52 | 53 | 54 | ## Subscription 55 | 56 | *config.yml -> Subscription* 57 | 58 | ```yaml 59 | Subscription: 60 | '0': # tag of the server, must be unique, can be customized 61 | Host: 'example.com' # Host name or IP 62 | Port: 60009 # Port of UniBan Broadcast 63 | Password: 'UniBan' # You may ask for the password from the server owner 64 | '1KBN': 65 | Host: 'www.eumc.cc/uniban' 66 | Port: 443 # Use SSL (or 80 if you want to use HTTP) 67 | #Password: '' # No password 68 | ``` 69 | 70 | 71 | 72 | ## Configuration 73 | 74 | ```yaml 75 | ConfigVersion: 3 76 | Settings: 77 | # Warn players with permission "uniban.getnotified" if they are banned by more than the value below, set to -1 to disable 78 | WarnThreshold: 1 79 | # Prevent players without permission "uniban.ignore" entering the server if they are banned by more than the value below, set to -1 to disable 80 | BanThreshold: 2 81 | # Whether an OP should be ignored by online-ban check 82 | IgnoreOP: true 83 | Broadcast: 84 | Enabled: true 85 | # 0.0.0.0 if you want other servers access your ban-list 86 | Host: 0.0.0.0 87 | Port: 60009 88 | Threads: 2 89 | # If you do not want to encrypt your shared ban-list, set it to '' 90 | Password: UniBan 91 | AccessControl: 92 | # Simple function to protect your broadcast service from CC attack 93 | Enabled: true 94 | # Unit: minute 95 | MinPeriodPerServer: 1.0 96 | Blacklist: 97 | Enabled: false 98 | IPList: 99 | # If there is a '*' in this list while whitelist is enabled, only these servers that are in the whitelist can access your ban-list 100 | - '*' 101 | Whitelist: 102 | Enabled: true 103 | IPList: 104 | # The following servers will not be limited by "MinPeriodPerServer" function 105 | - localhost 106 | # ServerID function is still under construction 107 | ServerID: 7aa71b85-8f12-4472-a34f-3f0863901035 108 | Tasks: 109 | # Interval of refreshing local ban-list (players that you banned by using /ban command), the unit is minute 110 | LocalBanListRefreshPeriod: 1.0 111 | # Interval of refreshing subscribed ban-list, the unit is minute 112 | SubscriptionRefreshPeriod: 10.0 113 | Subscription: 114 | '0': 115 | Host: example.com 116 | Port: 60009 117 | Password: UniBan 118 | # Player whitelist, defined by UUID 119 | UUIDWhitelist: [] 120 | Message: 121 | # '&' will automatically be replace by '§' 122 | WarningMessage: '&bUniban &3&l> &eWarning: Player {player}({uuid}) has been banned from another {number} server(s).' 123 | BannedOnlineKickMessage: '&eSorry, you have been banned from another {number} server(s).' 124 | MessagePrefix: 'UniBan &3> &r' 125 | IgnoredOP: 'Ignored OP: %s' 126 | PlayerNotExist: 'Player %s does not exist.' 127 | PlayerState: 'Player %s state: %s' 128 | PlayerBanned: '&cBanned from: ' 129 | PlayerNormal: '&anormal' 130 | InvalidSubscriptionKey: '&eInvalid subscription key' 131 | SubscriptionKeyAdded: 'Successfully added %s to your subscription list.' 132 | YourSubscriptionKey: 'Here''s the sharing link of your server''s Subscription Key which contains your address and connection password:' 133 | SubscriptionKeyLink: 'https://uniban.eumc.cc/share.php?key=%s' 134 | SubscriptionExempted: 'Successfully exempted server %s from subscription list temporarily.' 135 | FailedExempting: 'Failed exempting %s. Does that subscription exist?' 136 | WhitelistAdded: 'Player %s has been added to whitelist' 137 | WhitelistRemoved: 'Player %s has been removed from whitelist' 138 | Reloaded: 'Reloaded.' 139 | Error: 'Error: %s' 140 | SubscriptionsHeader: 'Subscriptions [%s] -----' 141 | ThirdPartyPluginSupportHeader: 'Third-party Banning Plugin Support -----' 142 | Encrypted: 'Encrypted' 143 | PluginEnabled: '&lEnabled' 144 | PluginNotFound: '&oNot Found' 145 | BroadcastStarted: 'UniBan broadcast started on %s:%s (%s Threads)' 146 | BroadcastActiveModeEnabled: 'UniBan broadcast service is running under active mode.' 147 | BroadcastFailed: 'Failed starting broadcast server' 148 | UpToDate: 'You are up-to-date.' 149 | NewVersionAvailable: 'There is a newer version %s available at §n https://www.spigotmc.org/resources/74747/' 150 | InvalidSpigotResourceID: 'It looks like you are using an unsupported version of UniBan. Please manually look for update.' 151 | FailedCheckingUpdate: 'Error occurred when checking update' 152 | LoadedFromLocalCache: 'Loaded %s banned players from ban-list cache.' 153 | Processing: 'Just a sec...' 154 | HelpMessageHeader: 'Usage:' 155 | HelpMessageList: 156 | - '/uniban lookup <&lName&r>' 157 | - '/uniban check <&lPlayer/UUID&r>' 158 | - '/uniban whitelist <“&ladd&r”/“&lremove&r”> <&lPlayer/UUID>' 159 | - '/uniban share <&lYour Server Hostname&r, eg. &nexample.com&r>' 160 | - '/uniban subscribe <&lSubscription Key&r>' 161 | - '/uniban exempt <&lServer Address&r>' 162 | - '/uniban reload' 163 | ``` 164 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/controller/CommandController.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.controller; 2 | 3 | import cc.eumc.uniban.config.Message; 4 | import cc.eumc.uniban.config.PluginConfig; 5 | import cc.eumc.uniban.config.ServerEntry; 6 | import cc.eumc.uniban.exception.CommandBreakException; 7 | import cc.eumc.uniban.serverinterface.PlayerInfo; 8 | import cc.eumc.uniban.util.Encryption; 9 | 10 | import java.io.UnsupportedEncodingException; 11 | import java.net.URLEncoder; 12 | import java.security.Key; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | import java.util.UUID; 16 | 17 | public abstract class CommandController { 18 | final String MSGPREFIX; 19 | public final static Key SHARING_KEY = Encryption.getKeyFromString("UniBanSubscription"); 20 | PluginConfig pluginConfig; 21 | 22 | public CommandController(PluginConfig pluginConfig) { 23 | this.pluginConfig = pluginConfig; 24 | MSGPREFIX = Message.MessagePrefix; 25 | } 26 | 27 | public List executeCommand(String[] args, UniBanController controller, PlayerInfo sender) throws CommandBreakException { 28 | List result = new ArrayList<>(); 29 | if (args.length == 0 || (args.length == 1 && args[0].equalsIgnoreCase("help"))) { 30 | sendHelp(result); 31 | } 32 | else if (args.length == 1) { 33 | if (args[0].equalsIgnoreCase("reload")) { 34 | doReload(); 35 | result.add(MSGPREFIX + Message.Reloaded); 36 | } 37 | else { 38 | sendHelp(result); 39 | } 40 | } 41 | else if (args.length == 2) { 42 | if (args[0].equalsIgnoreCase("lookup")) { 43 | sender.sendMessage(MSGPREFIX + Message.Processing); 44 | 45 | controller.runTaskLater(() -> { 46 | UUID uuid = UniBanController.nameToUUID(args[1]); 47 | if (uuid == null) { 48 | sender.sendMessage(MSGPREFIX + String.format(Message.PlayerNotExist, args[1])); 49 | } 50 | else { 51 | sender.sendMessage(MSGPREFIX + args[1] + ": " + uuid.toString()); 52 | } 53 | }, 1); 54 | 55 | throw new CommandBreakException(); 56 | } 57 | else if (args[0].equalsIgnoreCase("check")) { 58 | 59 | controller.runTaskLater(() -> { 60 | UUID uuid = null; 61 | try { 62 | uuid = UUID.fromString(args[1]); 63 | } catch (Exception e) { 64 | sender.sendMessage(MSGPREFIX + Message.Processing); 65 | uuid = UniBanController.nameToUUID(args[1]); 66 | } 67 | if (uuid == null) { 68 | sender.sendMessage(MSGPREFIX + String.format(Message.PlayerNotExist, args[1])); 69 | return; 70 | } 71 | boolean banned = isBannedOnline(uuid); 72 | sender.sendMessage(MSGPREFIX + String.format(Message.PlayerState, args[1], banned?Message.PlayerBanned:Message.PlayerNormal)); 73 | if (banned) { 74 | getBannedServerList(uuid).forEach(sender::sendMessage); 75 | } 76 | }, 1); 77 | throw new CommandBreakException(); 78 | } 79 | else if (args[0].equalsIgnoreCase("subscribe")) { 80 | // T√ODO A quick way to add subscription 81 | String subscriptionKey; 82 | // subscriptionKey: :@ 83 | if ((subscriptionKey = Encryption.decrypt(args[1], SHARING_KEY)) != null && (subscriptionKey.contains(":")&&subscriptionKey.contains("@"))) { 84 | String[] split = subscriptionKey.split("@", 2); 85 | if (split.length != 2) { 86 | result.add(MSGPREFIX + Message.InvalidSubscriptionKey); 87 | result.add(MSGPREFIX + args[1] + "->" + subscriptionKey); 88 | } 89 | else { 90 | String address = split[0]; 91 | pluginConfig.addSubscription(new ServerEntry(address), split[1], true); 92 | result.add(MSGPREFIX + String.format(Message.SubscriptionKeyAdded, address)); 93 | } 94 | } 95 | else { 96 | result.add(MSGPREFIX + Message.InvalidSubscriptionKey); 97 | } 98 | } 99 | else if (args[0].equalsIgnoreCase("share")) { 100 | String key = Encryption.encrypt(args[1] + ":" + PluginConfig.Legacy_Port + "@" + PluginConfig.Password, SHARING_KEY); 101 | if (key == null) { 102 | result.add(MSGPREFIX + String.format(Message.Error, "Failed generating Subscription Key.")); 103 | } 104 | else { 105 | result.add(MSGPREFIX + Message.YourSubscriptionKey); 106 | try { 107 | result.add(MSGPREFIX + String.format(Message.SubscriptionKeyLink, URLEncoder.encode(key, "UTF-8"))); 108 | } catch (UnsupportedEncodingException e) { 109 | result.add(MSGPREFIX + key); 110 | } 111 | } 112 | } 113 | else if (args[0].equalsIgnoreCase("exempt")) { 114 | result.add(MSGPREFIX + (pluginConfig.removeSubscription(args[1], false)?(String.format(Message.SubscriptionExempted, args[1])): String.format(Message.FailedExempting, args[1]))); 115 | } 116 | else { 117 | sendHelp(result); 118 | } 119 | } 120 | else if (args.length == 3) { 121 | if (args[0].equalsIgnoreCase("whitelist")) { 122 | if (args[1].equalsIgnoreCase("add")) { 123 | try { 124 | addWhitelist(UUID.fromString(args[2])); 125 | } catch (IllegalArgumentException e) { 126 | PlayerInfo player = controller.getPlayerInfoFromUUID(UniBanController.nameToUUID(args[2])); 127 | if (player == null) { 128 | result.add(MSGPREFIX + String.format(Message.PlayerNotExist, args[2])); 129 | throw new CommandBreakException(); 130 | } 131 | else 132 | addWhitelist(player.getUUID()); 133 | } 134 | result.add(MSGPREFIX + String.format(Message.WhitelistAdded, args[2])); 135 | } 136 | else if (args[1].equalsIgnoreCase("remove")) { 137 | try { 138 | removeWhitelist(UUID.fromString(args[2])); 139 | } catch (IllegalArgumentException e) { 140 | PlayerInfo player = controller.getPlayerInfoFromUUID(UniBanController.nameToUUID(args[2])); 141 | if (player == null) { 142 | result.add(MSGPREFIX + String.format(Message.PlayerNotExist, args[2])); 143 | throw new CommandBreakException(); 144 | } 145 | else 146 | removeWhitelist(player.getUUID()); 147 | } 148 | result.add(MSGPREFIX + String.format(Message.WhitelistRemoved, args[2])); 149 | } 150 | } 151 | else { 152 | sendHelp(result); 153 | } 154 | } 155 | return result; 156 | } 157 | 158 | void sendHelp(List result) { 159 | result.add(MSGPREFIX + Message.HelpMessageHeader); 160 | result.addAll(Message.HelpMessageList); 161 | } 162 | 163 | abstract void doReload(); 164 | abstract boolean isBannedOnline(UUID uuid); 165 | abstract List getBannedServerList(UUID uuid); 166 | abstract void addWhitelist(UUID uuid); 167 | abstract void removeWhitelist(UUID uuid); 168 | } 169 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/task/SubscriptionRefreshTask.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.task; 2 | 3 | import cc.eumc.uniban.config.PluginConfig; 4 | import cc.eumc.uniban.config.ServerEntry; 5 | import cc.eumc.uniban.controller.UniBanController; 6 | import cc.eumc.uniban.util.Encryption; 7 | import cc.eumc.uniban.util.ServerListPing; 8 | import com.google.gson.Gson; 9 | import com.google.gson.JsonSyntaxException; 10 | import com.google.gson.reflect.TypeToken; 11 | 12 | import javax.net.ssl.HttpsURLConnection; 13 | import java.io.BufferedReader; 14 | import java.io.InputStream; 15 | import java.io.InputStreamReader; 16 | import java.lang.reflect.Type; 17 | import java.net.HttpURLConnection; 18 | import java.net.InetSocketAddress; 19 | import java.net.URL; 20 | import java.util.*; 21 | 22 | public class SubscriptionRefreshTask implements Runnable { 23 | private class CoolDown { 24 | int total; 25 | int remaining; 26 | 27 | public CoolDown() { 28 | this.total = 1; 29 | this.remaining = 1; 30 | } 31 | 32 | public void next() { 33 | this.remaining --; 34 | } 35 | 36 | public void reset() { 37 | this.total ++; 38 | this.remaining = this.total; 39 | } 40 | } 41 | 42 | final UniBanController controller; 43 | boolean running = false; 44 | //Map lastUpdateCountMap = new HashMap<>(); 45 | Map coolDownMap = new HashMap<>(); 46 | 47 | public SubscriptionRefreshTask(UniBanController instance) { 48 | this.controller = instance; 49 | } 50 | 51 | @Override 52 | public void run() { 53 | if (running) { 54 | return; 55 | } 56 | running = true; 57 | 58 | if (PluginConfig.Subscriptions.size() == 0) { 59 | return; 60 | } 61 | 62 | int count = 0; 63 | for (ServerEntry serverEntry : PluginConfig.Subscriptions.keySet()) { 64 | // Check whether the server is suspended 65 | CoolDown coolDown = coolDownMap.get(serverEntry.getAddress()); 66 | if (coolDown != null && coolDown.remaining > 0) { 67 | coolDown.next(); 68 | continue; 69 | } 70 | 71 | /*if (!lastUpdateCountMap.containsKey(serverEntry.getAddress())) { 72 | // Mark as pending (update count check will not be performed this time) 73 | lastUpdateCountMap.put(serverEntry.getAddress(), -1); 74 | }*/ 75 | String host = serverEntry.host; 76 | int port = serverEntry.port; 77 | 78 | try { 79 | String result = ""; 80 | 81 | try { 82 | // New method 83 | ServerListPing serverListPing = new ServerListPing(); 84 | serverListPing.setAddress(new InetSocketAddress(host, port)); 85 | serverListPing.setTimeout(PluginConfig.SubscriptionGetReadTimeout); 86 | ServerListPing.StatusResponse responseJson = serverListPing.fetchData("UNIBAN"); 87 | if (responseJson.getDescription().getText() == null) { 88 | throw new Exception("Invalid response"); 89 | } 90 | result = responseJson.getDescription().getText(); 91 | } catch (Exception ignored) { 92 | // Legacy 93 | switch (port) { 94 | case 80: 95 | result = httpGet("http://" + host + "/get"); 96 | break; 97 | case 443: 98 | result = httpsGet("https://" + host + "/get"); 99 | break; 100 | default: 101 | result = httpGet("http://" + serverEntry.getAddress() + "/get"); 102 | } 103 | } 104 | 105 | result = Encryption.decrypt(result, PluginConfig.Subscriptions.get(serverEntry)); 106 | if (result == null) { 107 | controller.sendWarning("Failed decrypting ban-list from: " + serverEntry.getAddress() + ". Is our password correct?"); 108 | continue; 109 | } 110 | else { 111 | Type playerListType = new TypeToken>(){}.getType(); 112 | try { 113 | List banList = new Gson().fromJson(result, playerListType); 114 | if (banList == null) { 115 | controller.sendWarning(serverEntry.getAddress() + " responded with invalid data (length " + result.length() + ")"); 116 | //plugin.getLogger().warning(result); 117 | continue; 118 | } 119 | 120 | /* 121 | // Update count check 122 | if (lastUpdateCountMap.get(serverEntry.getAddress()) == -1) { 123 | lastUpdateCountMap.put(serverEntry.getAddress(), banList.size()); 124 | } 125 | else if (Math.abs(lastUpdateCountMap.get(serverEntry.getAddress()) - banList.size()) >= PluginConfig.TemporarilyPauseUpdateThreshold) { 126 | lastUpdateCountMap.put(serverEntry.getAddress(), -1); 127 | } 128 | else { 129 | lastUpdateCountMap.put(serverEntry.getAddress(), banList.size()); 130 | } 131 | */ 132 | 133 | if (banList.size() == 0) { 134 | continue; 135 | } 136 | for (String uuidStr : banList) { 137 | try { 138 | // Check if the provided UUID is valid 139 | UUID uuid = UUID.fromString(uuidStr); 140 | String validationUUID = uuid.toString(); 141 | if (validationUUID.equals(uuidStr)) { 142 | controller.addOnlineBanned(uuid, serverEntry.getAddress()); 143 | count++; 144 | } 145 | } catch (IllegalArgumentException e) { 146 | continue; 147 | } 148 | } 149 | controller.purgeOnlineBannedOfHost(serverEntry.getAddress(), banList); 150 | if (coolDown != null) { // The connection has recovered. 151 | coolDownMap.remove(serverEntry.getAddress()); 152 | } 153 | } 154 | // Fix: Misleading message when failed resolving ban-list caused by wrong password 155 | catch (JsonSyntaxException e) { 156 | controller.sendWarning("Failed resolving ban-list from: " + serverEntry.getAddress() + ". Is our password correct?"); 157 | continue; 158 | } 159 | } 160 | } 161 | catch (Exception e) { 162 | // Dynamically adjust attempting frequency on fail 163 | if (coolDown == null) { 164 | coolDown = new CoolDown(); 165 | } 166 | else { 167 | coolDown.reset(); 168 | } 169 | coolDownMap.put(serverEntry.getAddress(), coolDown); 170 | 171 | // e.printStackTrace(); 172 | controller.sendWarning("Failed pulling ban-list from: " + host+":"+port + ", we have suspended it for " + coolDown.remaining + " attempt" + (coolDown.remaining>1?"s":"") +"."); 173 | } 174 | } 175 | controller.saveBanList(); 176 | controller.sendInfo("Updated " + count + " banned players from other servers."); 177 | 178 | running = false; 179 | } 180 | 181 | static String httpGet(String urlToRead) throws Exception { 182 | StringBuilder result = new StringBuilder(); 183 | URL url = new URL(urlToRead); 184 | HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 185 | conn.setConnectTimeout(PluginConfig.SubscriptionGetConnectTimeout); 186 | conn.setReadTimeout(PluginConfig.SubscriptionGetReadTimeout); 187 | conn.setRequestMethod("GET"); 188 | BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 189 | String line; 190 | while ((line = rd.readLine()) != null) { 191 | result.append(line); 192 | } 193 | rd.close(); 194 | return result.toString(); 195 | } 196 | 197 | static String httpsGet(String urlTORead) throws Exception { 198 | URL myUrl = new URL(urlTORead); 199 | HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection(); 200 | conn.setConnectTimeout(1500); 201 | conn.setReadTimeout(3000); 202 | InputStream is = conn.getInputStream(); 203 | InputStreamReader isr = new InputStreamReader(is); 204 | BufferedReader br = new BufferedReader(isr); 205 | 206 | String inputLine; 207 | String result = ""; 208 | 209 | while ((inputLine = br.readLine()) != null) { 210 | result = result + "\n" + inputLine; 211 | } 212 | 213 | br.close(); 214 | return result; 215 | } 216 | 217 | } 218 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/util/Encryption.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.util; 2 | 3 | import org.jetbrains.annotations.Nullable; 4 | 5 | import javax.crypto.Cipher; 6 | import javax.crypto.spec.SecretKeySpec; 7 | import java.math.BigInteger; 8 | import java.nio.charset.StandardCharsets; 9 | import java.security.Key; 10 | import java.security.MessageDigest; 11 | import java.security.NoSuchAlgorithmException; 12 | import java.util.Base64; 13 | 14 | 15 | public class Encryption { 16 | public static String encrypt(String text, @Nullable Key aesKey) { 17 | if (aesKey == null) { 18 | return text; 19 | } 20 | try { 21 | // Create key and cipher 22 | Cipher cipher = Cipher.getInstance("AES"); 23 | // encrypt the text 24 | cipher.init(Cipher.ENCRYPT_MODE, aesKey); 25 | byte[] encrypted = Base64.getEncoder().encode(cipher.doFinal(text.getBytes())); 26 | return new String(encrypted); 27 | } catch (Exception e) { 28 | e.printStackTrace(); 29 | } 30 | return null; 31 | } 32 | 33 | public static @Nullable 34 | String decrypt(String text, @Nullable Key aesKey) { 35 | if (aesKey == null) { 36 | return text; 37 | } 38 | try { 39 | // Create key and cipher 40 | Cipher cipher = Cipher.getInstance("AES"); 41 | // decrypt the text 42 | cipher.init(Cipher.DECRYPT_MODE, aesKey); 43 | return new String(cipher.doFinal(Base64.getDecoder().decode(text.getBytes()))); 44 | } catch (Exception e) { 45 | e.printStackTrace(); 46 | } 47 | return null; 48 | } 49 | 50 | public static @Nullable 51 | Key getKeyFromString(String password) { 52 | if (password.length() == 0) return null; 53 | else if (password.length() < 16) { 54 | password = rightPad(password, 16, "0"); 55 | } else if (password.length() > 16 && password.length() < 24) { 56 | password = rightPad(password, 24, "0"); 57 | } else if (password.length() < 32) { 58 | password = rightPad(password, 32, "0"); 59 | } else if (password.length() > 32) { 60 | password = password.substring(0, 31); 61 | } 62 | return new SecretKeySpec(password.getBytes(), "AES"); 63 | } 64 | 65 | public static String getMd5(String input) { 66 | try { 67 | MessageDigest md = MessageDigest.getInstance("MD5"); 68 | 69 | byte[] messageDigest = md.digest(input.getBytes()); 70 | 71 | BigInteger no = new BigInteger(1, messageDigest); 72 | 73 | String hashtext = no.toString(16); 74 | while (hashtext.length() < 32) { 75 | hashtext = "0" + hashtext; 76 | } 77 | return hashtext; 78 | } 79 | 80 | // For specifying wrong message digest algorithms 81 | catch (NoSuchAlgorithmException e) { 82 | throw new RuntimeException(e); 83 | } 84 | } 85 | 86 | 87 | public static String getSha256(String input) { 88 | try { 89 | MessageDigest digest = MessageDigest.getInstance("SHA-256"); 90 | //Applies sha256 to our input, 91 | byte[] hash = digest.digest(input.getBytes(StandardCharsets.UTF_8)); 92 | StringBuilder hexString = new StringBuilder(); // This will contain hash as hexidecimal 93 | for (byte b : hash) { 94 | String hex = Integer.toHexString(0xff & b); 95 | if (hex.length() == 1) hexString.append('0'); 96 | hexString.append(hex); 97 | } 98 | return hexString.toString(); 99 | } 100 | catch(Exception e) { 101 | throw new RuntimeException(e); 102 | } 103 | } 104 | 105 | // Fix: NoClassDefFoundError on BungeeCord 106 | 107 | /** 108 | *

Returns padding using the specified delimiter repeated 109 | * to a given length.

110 | * 111 | *
112 |      * StringUtils.padding(0, 'e')  = ""
113 |      * StringUtils.padding(3, 'e')  = "eee"
114 |      * StringUtils.padding(-2, 'e') = IndexOutOfBoundsException
115 |      * 
116 | * 117 | *

Note: this method doesn't not support padding with 118 | * Unicode Supplementary Characters 119 | * as they require a pair of chars to be represented. 120 | * If you are needing to support full I18N of your applications 121 | * consider using {@link #(String, int)} instead. 122 | *

123 | * 124 | * @param repeat number of times to repeat delim 125 | * @param padChar character to repeat 126 | * @return String with repeated character 127 | * @throws IndexOutOfBoundsException if repeat < 0 128 | * @see #(String, int) 129 | */ 130 | private static String padding(int repeat, char padChar) throws IndexOutOfBoundsException { 131 | if (repeat < 0) { 132 | throw new IndexOutOfBoundsException("Cannot pad a negative amount: " + repeat); 133 | } 134 | final char[] buf = new char[repeat]; 135 | for (int i = 0; i < buf.length; i++) { 136 | buf[i] = padChar; 137 | } 138 | return new String(buf); 139 | } 140 | 141 | /** 142 | *

Right pad a String with spaces (' ').

143 | * 144 | *

The String is padded to the size of size.

145 | * 146 | *
147 |      * StringUtils.rightPad(null, *)   = null
148 |      * StringUtils.rightPad("", 3)     = "   "
149 |      * StringUtils.rightPad("bat", 3)  = "bat"
150 |      * StringUtils.rightPad("bat", 5)  = "bat  "
151 |      * StringUtils.rightPad("bat", 1)  = "bat"
152 |      * StringUtils.rightPad("bat", -1) = "bat"
153 |      * 
154 | * 155 | * @param str the String to pad out, may be null 156 | * @param size the size to pad to 157 | * @return right padded String or original String if no padding is necessary, 158 | * null if null String input 159 | */ 160 | public static String rightPad(String str, int size) { 161 | return rightPad(str, size, ' '); 162 | } 163 | 164 | /** 165 | *

Right pad a String with a specified character.

166 | * 167 | *

The String is padded to the size of size.

168 | * 169 | *
170 |      * StringUtils.rightPad(null, *, *)     = null
171 |      * StringUtils.rightPad("", 3, 'z')     = "zzz"
172 |      * StringUtils.rightPad("bat", 3, 'z')  = "bat"
173 |      * StringUtils.rightPad("bat", 5, 'z')  = "batzz"
174 |      * StringUtils.rightPad("bat", 1, 'z')  = "bat"
175 |      * StringUtils.rightPad("bat", -1, 'z') = "bat"
176 |      * 
177 | * 178 | * @param str the String to pad out, may be null 179 | * @param size the size to pad to 180 | * @param padChar the character to pad with 181 | * @return right padded String or original String if no padding is necessary, 182 | * null if null String input 183 | * @since 2.0 184 | */ 185 | public static String rightPad(String str, int size, char padChar) { 186 | if (str == null) { 187 | return null; 188 | } 189 | int pads = size - str.length(); 190 | if (pads <= 0) { 191 | return str; // returns original String when possible 192 | } 193 | if (pads > 8192) { 194 | return rightPad(str, size, String.valueOf(padChar)); 195 | } 196 | return str.concat(padding(pads, padChar)); 197 | } 198 | 199 | /** 200 | *

Right pad a String with a specified String.

201 | * 202 | *

The String is padded to the size of size.

203 | * 204 | *
205 |      * StringUtils.rightPad(null, *, *)      = null
206 |      * StringUtils.rightPad("", 3, "z")      = "zzz"
207 |      * StringUtils.rightPad("bat", 3, "yz")  = "bat"
208 |      * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
209 |      * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
210 |      * StringUtils.rightPad("bat", 1, "yz")  = "bat"
211 |      * StringUtils.rightPad("bat", -1, "yz") = "bat"
212 |      * StringUtils.rightPad("bat", 5, null)  = "bat  "
213 |      * StringUtils.rightPad("bat", 5, "")    = "bat  "
214 |      * 
215 | * 216 | * @param str the String to pad out, may be null 217 | * @param size the size to pad to 218 | * @param padStr the String to pad with, null or empty treated as single space 219 | * @return right padded String or original String if no padding is necessary, 220 | * null if null String input 221 | */ 222 | public static String rightPad(String str, int size, String padStr) { 223 | if (str == null) { 224 | return null; 225 | } 226 | if (isEmpty(padStr)) { 227 | padStr = " "; 228 | } 229 | int padLen = padStr.length(); 230 | int strLen = str.length(); 231 | int pads = size - strLen; 232 | if (pads <= 0) { 233 | return str; // returns original String when possible 234 | } 235 | if (padLen == 1 && pads <= 8192) { //PAD_LIMIT 236 | return rightPad(str, size, padStr.charAt(0)); 237 | } 238 | 239 | if (pads == padLen) { 240 | return str.concat(padStr); 241 | } else if (pads < padLen) { 242 | return str.concat(padStr.substring(0, pads)); 243 | } else { 244 | char[] padding = new char[pads]; 245 | char[] padChars = padStr.toCharArray(); 246 | for (int i = 0; i < pads; i++) { 247 | padding[i] = padChars[i % padLen]; 248 | } 249 | return str.concat(new String(padding)); 250 | } 251 | } 252 | 253 | // Empty checks 254 | //----------------------------------------------------------------------- 255 | 256 | /** 257 | *

Checks if a String is empty ("") or null.

258 | * 259 | *
260 |      * StringUtils.isEmpty(null)      = true
261 |      * StringUtils.isEmpty("")        = true
262 |      * StringUtils.isEmpty(" ")       = false
263 |      * StringUtils.isEmpty("bob")     = false
264 |      * StringUtils.isEmpty("  bob  ") = false
265 |      * 
266 | * 267 | *

NOTE: This method changed in Lang version 2.0. 268 | * It no longer trims the String. 269 | * That functionality is available in isBlank().

270 | * 271 | * @param str the String to check, may be null 272 | * @return true if the String is empty or null 273 | */ 274 | public static boolean isEmpty(String str) { 275 | return str == null || str.length() == 0; 276 | } 277 | } -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/util/HttpRequest.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.util; 2 | /* 3 | * WorldEdit, a Minecraft world manipulation toolkit 4 | * Copyright (C) sk89q 5 | * Copyright (C) WorldEdit team and contributors 6 | * 7 | * This program is free software: you can redistribute it and/or modify it 8 | * under the terms of the GNU Lesser General Public License as published by the 9 | * Free Software Foundation, either version 3 of the License, or 10 | * (at your option) any later version. 11 | * 12 | * This program is distributed in the hope that it will be useful, but WITHOUT 13 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License 15 | * for more details. 16 | * 17 | * You should have received a copy of the GNU Lesser General Public License 18 | * along with this program. If not, see . 19 | */ 20 | 21 | import com.google.common.io.Closer; 22 | 23 | import java.io.*; 24 | import java.net.*; 25 | import java.util.ArrayList; 26 | import java.util.HashMap; 27 | import java.util.List; 28 | import java.util.Map; 29 | 30 | public class HttpRequest implements Closeable { 31 | 32 | private static final int CONNECT_TIMEOUT = 1000 * 10; 33 | 34 | private static final int READ_TIMEOUT = 1000 * 17; 35 | 36 | private static final int READ_BUFFER_SIZE = 1024 * 8; 37 | 38 | private final Map headers = new HashMap<>(); 39 | 40 | private final String method; 41 | 42 | private final URL url; 43 | 44 | private String contentType; 45 | 46 | private byte[] body; 47 | 48 | private HttpURLConnection conn; 49 | 50 | private InputStream inputStream; 51 | 52 | // private long contentLength = -1; 53 | private long readBytes = 0; 54 | 55 | /** 56 | * Create a new HTTP request. 57 | * 58 | * @param method the method 59 | * @param url the URL 60 | */ 61 | private HttpRequest(String method, URL url) { 62 | this.method = method; 63 | this.url = url; 64 | } 65 | 66 | /** 67 | * Perform a GET request. 68 | * 69 | * @param url the URL 70 | * @return a new request object 71 | */ 72 | public static HttpRequest get(URL url) { 73 | return request("GET", url); 74 | } 75 | 76 | /** 77 | * Perform a request. 78 | * 79 | * @param method the method 80 | * @param url the URL 81 | * @return a new request object 82 | */ 83 | public static HttpRequest request(String method, URL url) { 84 | return new HttpRequest(method, url); 85 | } 86 | 87 | /** 88 | * Perform a POST request. 89 | * 90 | * @param url the URL 91 | * @return a new request object 92 | */ 93 | public static HttpRequest post(URL url) { 94 | return request("POST", url); 95 | } 96 | 97 | /** 98 | * Create a new {@link URL} and throw a {@link RuntimeException} if the URL is not valid. 99 | * 100 | * @param url the url 101 | * @return a URL object 102 | * @throws RuntimeException if the URL is invalid 103 | */ 104 | public static URL url(String url) { 105 | try { 106 | return new URL(url); 107 | } catch (MalformedURLException e) { 108 | throw new RuntimeException(e); 109 | } 110 | } 111 | 112 | /** 113 | * Submit data. 114 | * 115 | * @param data the data 116 | * @return this object 117 | */ 118 | public HttpRequest body(String data) { 119 | body = data.getBytes(); 120 | return this; 121 | } 122 | 123 | /** 124 | * Submit form data. 125 | * 126 | * @param form the form 127 | * @return this object 128 | */ 129 | public HttpRequest bodyForm(Form form) { 130 | contentType = "application/x-www-form-urlencoded"; 131 | body = form.toString().getBytes(); 132 | return this; 133 | } 134 | 135 | /** 136 | * Add a header. 137 | * 138 | * @param key the header key 139 | * @param value the header value 140 | * @return this object 141 | */ 142 | public HttpRequest header(String key, String value) { 143 | if ("Content-Type".equalsIgnoreCase(key)) { 144 | contentType = value; 145 | } else { 146 | headers.put(key, value); 147 | } 148 | return this; 149 | } 150 | 151 | /** 152 | * Execute the request. 153 | * 154 | *

After execution, {@link #close()} should be called. 155 | * 156 | * @return this object 157 | * @throws IOException on I/O error 158 | */ 159 | public HttpRequest execute() throws IOException { 160 | return execute(-1); 161 | } 162 | 163 | 164 | /** 165 | * Execute the request. 166 | * 167 | *

After execution, {@link #close()} should be called. 168 | * 169 | * @return this object 170 | * @throws IOException on I/O error 171 | */ 172 | public HttpRequest execute(int timeout) throws IOException { 173 | boolean successful = false; 174 | 175 | try { 176 | if (conn != null) { 177 | throw new IllegalArgumentException("Connection already executed"); 178 | } 179 | 180 | conn = (HttpURLConnection) reformat(url).openConnection(); 181 | conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Java)"); 182 | 183 | if (body != null) { 184 | conn.setRequestProperty("Content-Type", contentType); 185 | conn.setRequestProperty("Content-Length", Integer.toString(body.length)); 186 | conn.setDoInput(true); 187 | } 188 | 189 | for (Map.Entry entry : headers.entrySet()) { 190 | conn.setRequestProperty(entry.getKey(), entry.getValue()); 191 | } 192 | 193 | conn.setRequestMethod(method); 194 | conn.setUseCaches(false); 195 | conn.setDoOutput(true); 196 | conn.setConnectTimeout(CONNECT_TIMEOUT); 197 | if (timeout != -1) { 198 | conn.setReadTimeout(timeout); 199 | } else { 200 | conn.setReadTimeout(READ_TIMEOUT); 201 | } 202 | 203 | 204 | conn.connect(); 205 | 206 | if (body != null) { 207 | DataOutputStream out = new DataOutputStream(conn.getOutputStream()); 208 | out.write(body); 209 | out.flush(); 210 | out.close(); 211 | } 212 | 213 | inputStream = 214 | conn.getResponseCode() == HttpURLConnection.HTTP_OK 215 | ? conn.getInputStream() 216 | : conn.getErrorStream(); 217 | 218 | successful = true; 219 | } finally { 220 | if (!successful) { 221 | close(); 222 | } 223 | } 224 | 225 | return this; 226 | } 227 | 228 | /** 229 | * URL may contain spaces and other nasties that will cause a failure. 230 | * 231 | * @param existing the existing URL to transform 232 | * @return the new URL, or old one if there was a failure 233 | */ 234 | private static URL reformat(URL existing) { 235 | try { 236 | URL url = new URL(existing.toString()); 237 | URI uri = 238 | new URI( 239 | url.getProtocol(), 240 | url.getUserInfo(), 241 | url.getHost(), 242 | url.getPort(), 243 | url.getPath(), 244 | url.getQuery(), 245 | url.getRef()); 246 | url = uri.toURL(); 247 | return url; 248 | } catch (MalformedURLException | URISyntaxException e) { 249 | return existing; 250 | } 251 | } 252 | 253 | @Override 254 | public void close() { 255 | if (conn != null) { 256 | conn.disconnect(); 257 | } 258 | } 259 | 260 | /** 261 | * Require that the response code is one of the given response codes. 262 | * 263 | * @param codes a list of codes 264 | * @return this object 265 | * @throws IOException if there is an I/O error or the response code is not expected 266 | */ 267 | public HttpRequest expectResponseCode(int... codes) throws IOException { 268 | int responseCode = getResponseCode(); 269 | 270 | for (int code : codes) { 271 | if (code == responseCode) { 272 | return this; 273 | } 274 | } 275 | 276 | close(); 277 | throw new IOException( 278 | "Did not get expected response code, got " + responseCode + " for " + url); 279 | } 280 | 281 | /** 282 | * Get the response code. 283 | * 284 | * @return the response code 285 | * @throws IOException on I/O error 286 | */ 287 | public int getResponseCode() throws IOException { 288 | if (conn == null) { 289 | throw new IllegalArgumentException("No connection has been made"); 290 | } 291 | 292 | return conn.getResponseCode(); 293 | } 294 | 295 | /** 296 | * Get the input stream. 297 | * 298 | * @return the input stream 299 | */ 300 | public InputStream getInputStream() { 301 | return inputStream; 302 | } 303 | 304 | /** 305 | * Buffer the returned response. 306 | * 307 | * @return the buffered response 308 | * @throws IOException on I/O error 309 | */ 310 | public BufferedResponse returnContent() throws IOException { 311 | if (inputStream == null) { 312 | throw new IllegalArgumentException("No input stream available"); 313 | } 314 | 315 | try { 316 | ByteArrayOutputStream bos = new ByteArrayOutputStream(); 317 | int b; 318 | while ((b = inputStream.read()) != -1) { 319 | bos.write(b); 320 | } 321 | return new BufferedResponse(bos.toByteArray()); 322 | } finally { 323 | close(); 324 | } 325 | } 326 | 327 | /** 328 | * Save the result to a file. 329 | * 330 | * @param file the file 331 | * @return this object 332 | * @throws IOException on I/O error 333 | */ 334 | public HttpRequest saveContent(File file) throws IOException { 335 | 336 | try (Closer closer = Closer.create()) { 337 | FileOutputStream fos = closer.register(new FileOutputStream(file)); 338 | BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos)); 339 | 340 | saveContent(bos); 341 | } 342 | 343 | return this; 344 | } 345 | 346 | /** 347 | * Save the result to an output stream. 348 | * 349 | * @param out the output stream 350 | * @return this object 351 | * @throws IOException on I/O error 352 | */ 353 | public HttpRequest saveContent(OutputStream out) throws IOException { 354 | BufferedInputStream bis; 355 | 356 | try { 357 | String field = conn.getHeaderField("Content-Length"); 358 | if (field != null) { 359 | long len = Long.parseLong(field); 360 | // if (len >= 0) { // Let's just not deal with really big numbers 361 | // contentLength = len; 362 | // } 363 | } 364 | } catch (NumberFormatException ignored) { 365 | } 366 | 367 | try { 368 | bis = new BufferedInputStream(inputStream); 369 | 370 | byte[] data = new byte[READ_BUFFER_SIZE]; 371 | int len; 372 | while ((len = bis.read(data, 0, READ_BUFFER_SIZE)) >= 0) { 373 | out.write(data, 0, len); 374 | readBytes += len; 375 | } 376 | } finally { 377 | close(); 378 | } 379 | 380 | return this; 381 | } 382 | 383 | /** 384 | * Used with {@link #bodyForm(Form)}. 385 | */ 386 | public static final class Form { 387 | public final List elements = new ArrayList<>(); 388 | 389 | private Form() { 390 | } 391 | 392 | /** 393 | * Create a new form. 394 | * 395 | * @return a new form 396 | */ 397 | public static Form create() { 398 | return new Form(); 399 | } 400 | 401 | /** 402 | * Add a key/value to the form. 403 | * 404 | * @param key the key 405 | * @param value the value 406 | * @return this object 407 | */ 408 | public Form add(String key, String value) { 409 | try { 410 | elements.add(URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8")); 411 | return this; 412 | } catch (UnsupportedEncodingException e) { 413 | throw new RuntimeException(e); 414 | } 415 | } 416 | 417 | @Override 418 | public String toString() { 419 | StringBuilder builder = new StringBuilder(); 420 | boolean first = true; 421 | for (String element : elements) { 422 | if (first) { 423 | first = false; 424 | } else { 425 | builder.append("&"); 426 | } 427 | builder.append(element); 428 | } 429 | return builder.toString(); 430 | } 431 | 432 | } 433 | 434 | /** 435 | * Used to buffer the response in memory. 436 | */ 437 | public static class BufferedResponse { 438 | private final byte[] data; 439 | 440 | private BufferedResponse(byte[] data) { 441 | this.data = data; 442 | } 443 | 444 | /** 445 | * Return the result as bytes. 446 | * 447 | * @return the data 448 | */ 449 | public byte[] asBytes() { 450 | return data; 451 | } 452 | 453 | /** 454 | * Return the result as a string. 455 | * 456 | * @param encoding the encoding 457 | * @return the string 458 | * @throws IOException on I/O error 459 | */ 460 | public String asString(String encoding) throws IOException { 461 | return new String(data, encoding); 462 | } 463 | 464 | /** 465 | * Save the result to a file. 466 | * 467 | * @param file the file 468 | * @return this object 469 | * @throws IOException on I/O error 470 | */ 471 | public BufferedResponse saveContent(File file) throws IOException { 472 | 473 | try (Closer closer = Closer.create()) { 474 | file.getParentFile().mkdirs(); 475 | FileOutputStream fos = closer.register(new FileOutputStream(file)); 476 | BufferedOutputStream bos = closer.register(new BufferedOutputStream(fos)); 477 | 478 | saveContent(bos); 479 | } 480 | 481 | return this; 482 | } 483 | 484 | /** 485 | * Save the result to an output stream. 486 | * 487 | * @param out the output stream 488 | * @return this object 489 | * @throws IOException on I/O error 490 | */ 491 | public BufferedResponse saveContent(OutputStream out) throws IOException { 492 | out.write(data); 493 | 494 | return this; 495 | } 496 | 497 | } 498 | 499 | } 500 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/config/PluginConfig.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.config; 2 | 3 | import cc.eumc.uniban.util.Encryption; 4 | 5 | import java.security.Key; 6 | import java.util.*; 7 | 8 | public abstract class PluginConfig { 9 | public static boolean LiteBans; 10 | public static boolean AdvancedBan; 11 | 12 | public final static int PluginConfigVersion = 7; 13 | 14 | public static boolean BroadcastWarning; 15 | public static int ConfigVersion; 16 | public static boolean EnableBroadcast; 17 | public static boolean EnableDHT; 18 | public static double LocalBanListRefreshPeriod; 19 | public static double SubscriptionRefreshPeriod; 20 | public static int SubscriptionGetConnectTimeout; 21 | public static int SubscriptionGetReadTimeout; 22 | public static boolean ViaServerListPing_Enabled; 23 | public static boolean Legacy_Enabled; 24 | public static String Legacy_Host; 25 | public static int Legacy_Port; 26 | public static int Legacy_Threads; 27 | public static String Password; 28 | public static Key EncryptionKey; 29 | public static String NodeID; 30 | public static boolean ActiveMode_Enabled; 31 | public static String ActiveMode_PostUrl; 32 | public static String ActiveMode_PostSecret; 33 | 34 | public static boolean EnabledAccessControl; 35 | public static int MinPeriodPerServer; 36 | // TODO Change to `Blocklist` & `Allowlist` 37 | public static boolean BlacklistEnabled; 38 | public static boolean WhitelistEnabled; 39 | public static List Blacklist; 40 | public static List Whitelist; 41 | 42 | public static Map Subscriptions = new HashMap<>(); // Address - Key 43 | //public static Map SubscriptionServerHostIDMap = new HashMap<>(); 44 | public static int TemporarilyPauseUpdateThreshold; 45 | 46 | public static List UUIDWhitelist; 47 | public static List ExcludeIfReasonContain; 48 | 49 | public static int WarnThreshold; 50 | public static int BanThreshold; 51 | public static boolean IgnoreOP; 52 | 53 | public PluginConfig() { 54 | ConfigVersion = configGetInt("ConfigVersion", -1); 55 | EnableBroadcast = configGetBoolean("Settings.Broadcast.Enabled", true); 56 | // Fix: SubscriptionRefreshPeriod will not be loaded when broadcast is disabled 57 | SubscriptionRefreshPeriod = configGetDouble("Settings.Tasks.SubscriptionRefreshPeriod", 10.0); 58 | SubscriptionGetConnectTimeout = configGetInt("Settings.Tasks.SubscriptionGetConnectTimeout", 5000); 59 | SubscriptionGetReadTimeout = configGetInt("Settings.Tasks.SubscriptionGetReadTimeout", 5000); 60 | if (EnableBroadcast) { 61 | EnableDHT = configGetBoolean("Settings.Broadcast.EnableDHT", false); 62 | LocalBanListRefreshPeriod = configGetDouble("Settings.Tasks.LocalBanListRefreshPeriod", 1.0); 63 | 64 | ActiveMode_Enabled = configGetBoolean("Settings.Broadcast.ActiveMode.Enabled", false); 65 | if (ActiveMode_Enabled) { 66 | ActiveMode_PostUrl = configGetString("Settings.Broadcast.ActiveMode.PostUrl", ""); 67 | ActiveMode_PostSecret = configGetString("Settings.Broadcast.ActiveMode.PostSecret", ""); 68 | } 69 | 70 | Password = configGetString("Settings.Broadcast.Password", ""); 71 | EncryptionKey = Encryption.getKeyFromString(Password); 72 | 73 | ViaServerListPing_Enabled = configGetBoolean("Settings.Broadcast.ViaServerListPing.Enabled", false); 74 | 75 | Legacy_Enabled = configGetBoolean("Settings.Broadcast.LegacyWebServer.Enabled", false); 76 | if (Legacy_Enabled) { 77 | Legacy_Host = configGetString("Settings.Broadcast.LegacyWebServer.Host", "0.0.0.0"); 78 | Legacy_Port = configGetInt("Settings.Broadcast.LegacyWebServer.Port", 60009); 79 | Legacy_Threads = configGetInt("Settings.Broadcast.LegacyWebServer.Threads", 2); 80 | } 81 | 82 | ExcludeIfReasonContain = new ArrayList<>(configGetStringList("Settings.Broadcast.ExcludeIfReasonContain")); 83 | } 84 | NodeID = configGetString("Settings.Broadcast.NodeID", ""); 85 | if (NodeID.equals("")) { 86 | NodeID = de.cgrotz.kademlia.node.Key.random().toString(); 87 | configSet("Settings.Broadcast.NodeID", NodeID); 88 | saveConfig(); 89 | } 90 | 91 | // Fix: Subscriptions will not be cleaned when reloading 92 | Subscriptions = new HashMap<>(); 93 | if (configIsSection("Subscription")) { 94 | for (String key : getConfigurationSectionKeys("Subscription")) { 95 | String host = configGetString("Subscription." + key + ".Host", ""); 96 | int port; 97 | if (host.equals("")) { 98 | if (!(host = configGetString("Subscription." + key + ".URL", "")).equals("")) { 99 | if (host.startsWith("https://")) { 100 | port = 443; 101 | host = host.replace("https://", ""); 102 | } else { 103 | port = 80; 104 | host = host.replace("http://", ""); 105 | } 106 | } else { 107 | continue; 108 | } 109 | } else { 110 | port = configGetInt("Subscription." + key + ".Port", 60009); 111 | } 112 | String password = configGetString("Subscription." + key + ".Password", ""); 113 | Key decryptionKey = null; 114 | if (!password.equals("")) { 115 | decryptionKey = Encryption.getKeyFromString(password); 116 | } 117 | 118 | Subscriptions.put(new ServerEntry(host, port), decryptionKey); 119 | 120 | // TODO run IdentifySubscriptionTask 121 | //Bukkit.getScheduler().runTaskLater(instance, new IdentifySubscriptionTask(instance), 1); 122 | } 123 | } 124 | 125 | //TemporarilyPauseUpdateThreshold = configGetInt("Settings.TemporarilyPauseUpdateThreshold", 10); 126 | 127 | EnabledAccessControl = configGetBoolean("Settings.Broadcast.AccessControl.Enabled", true); 128 | if (EnabledAccessControl) { 129 | MinPeriodPerServer = (int) (60 * configGetDouble("Settings.Broadcast.AccessControl.MinPeriodPerServer", 1.0)); 130 | 131 | BlacklistEnabled = configGetBoolean("Settings.Broadcast.AccessControl.Blacklist.Enabled", false); 132 | if (BlacklistEnabled) { 133 | Blacklist = new ArrayList<>(configGetStringList("Settings.Broadcast.AccessControl.Blacklist.IPList")); 134 | } 135 | 136 | WhitelistEnabled = configGetBoolean("Settings.Broadcast.AccessControl.Whitelist.Enabled", false); 137 | if (WhitelistEnabled) { 138 | Whitelist = new ArrayList<>(configGetStringList("Settings.Broadcast.AccessControl.Whitelist.IPList")); 139 | } 140 | } 141 | 142 | UUIDWhitelist = configGetStringList("UUIDWhitelist"); 143 | 144 | BroadcastWarning = configGetBoolean("Settings.BroadcastWarning", false); 145 | WarnThreshold = configGetInt("Settings.WarnThreshold", 1); 146 | BanThreshold = configGetInt("Settings.BanThreshold", 1); 147 | IgnoreOP = configGetBoolean("Settings.IgnoreOP", true); 148 | 149 | // Resolve #2 150 | Message.WarningMessage = Message.replace(configGetString("Message.WarningMessage", "&bUniban &3&l> &eWarning: Player {player}({uuid}) has been banned from another {number} server(s).")); 151 | Message.BannedOnlineKickMessage = Message.replace(configGetString("Message.BannedOnlineKickMessage", "§eSorry, you have been banned from another server.")); 152 | Message.IgnoredOP = Message.replace(configGetString("Message.IgnoredOP", "Ignored OP: %s")); 153 | Message.MessagePrefix = Message.replace(configGetString("Message.MessagePrefix", "UniBan &3> &r")); 154 | Message.Error = Message.replace(configGetString("Message.Error", "Error: %s")); 155 | Message.Reloaded = Message.replace(configGetString("Message.Reloaded", "Reloaded.")); 156 | Message.PlayerNotExist = Message.replace(configGetString("Message.PlayerNotExist", "Player %s does not exist.")); 157 | Message.PlayerState = Message.replace(configGetString("Message.PlayerState", "Player %s state: %s")); 158 | Message.PlayerBanned = Message.replace(configGetString("Message.PlayerBanned", "&cBanned by at least 1 server")); 159 | Message.PlayerNormal = Message.replace(configGetString("Message.PlayerNormal", "&anormal")); 160 | Message.InvalidSubscriptionKey = Message.replace(configGetString("Message.InvalidSubscriptionKey", "&eInvalid subscription key")); 161 | Message.SubscriptionKeyAdded = Message.replace(configGetString("Message.SubscriptionKeyAdded", "Successfully added %s to your subscription list.")); 162 | Message.YourSubscriptionKey = Message.replace(configGetString("Message.YourSubscriptionKey", "Here's the sharing link of your server's Subscription Key which contains your address and connection password:")); 163 | Message.SubscriptionKeyLink = Message.replace(configGetString("Message.SubscriptionKeyLink", "https://uniban.eumc.cc/share.php?key=%s")); 164 | Message.SubscriptionExempted = Message.replace(configGetString("Message.SubscriptionExempted", "Successfully exempted server %s from subscription list temporarily.")); 165 | Message.FailedExempting = Message.replace(configGetString("Message.FailedExempting", "Failed exempting %s. Does that subscription exist?")); 166 | Message.WhitelistAdded = Message.replace(configGetString("Message.WhitelistAdded", "Player %s has been added to whitelist")); 167 | Message.WhitelistRemoved = Message.replace(configGetString("Message.WhitelistRemoved", "Player %s has been removed from whitelist")); 168 | Message.SubscriptionsHeader = Message.replace(configGetString("Message.SubscriptionsHeader", "Subscriptions [%s] -----")); 169 | Message.ThirdPartyPluginSupportHeader = Message.replace(configGetString("Message.ThirdPartyPluginSupportHeader", "Third-party Banning Plugin Support -----")); 170 | Message.Encrypted = Message.replace(configGetString("Message.Encrypted", "Encrypted")); 171 | Message.PluginEnabled = Message.replace(configGetString("Message.PluginEnabled", "&lEnabled")); 172 | Message.PluginNotFound = Message.replace(configGetString("Message.PluginNotFound", "&oNot Found")); 173 | Message.Encrypted = Message.replace(configGetString("Message.Encrypted", "Encrypted")); 174 | Message.BroadcastActiveModeEnabled = Message.replace(configGetString("Message.BroadcastActiveModeEnabled", "UniBan broadcast service is running under active mode.")); 175 | Message.BroadcastViaServerListPing = Message.replace(configGetString("Message.BroadcastViaServerListPing", "UniBan broadcast is delivering ban-list via server list ping.")); 176 | Message.BroadcastStarted = Message.replace(configGetString("Message.BroadcastStarted", "UniBan broadcast started on %s:%s (%s Threads)")); 177 | Message.BroadcastFailed = Message.replace(configGetString("Message.BroadcastFailed", "Failed starting broadcast server")); 178 | Message.UpToDate = Message.replace(configGetString("Message.UpToDate", "You are up-to-date.")); 179 | Message.NewVersionAvailable = Message.replace(configGetString("Message.NewVersionAvailable", "There is a newer version %s available at §n https://www.spigotmc.org/resources/74747/")); 180 | Message.InvalidSpigotResourceID = Message.replace(configGetString("Message.InvalidSpigotResourceID", "It looks like you are using an unsupported version of UniBan. Please manually look for update.")); 181 | Message.FailedCheckingUpdate = Message.replace(configGetString("Message.FailedCheckingUpdate", "Error occurred when checking update")); 182 | Message.LoadedFromLocalCache = Message.replace(configGetString("Message.LoadedFromLocalCache", "Loaded %s banned players from ban-list cache.")); 183 | Message.HelpMessageHeader = Message.replace(configGetString("Message.HelpMessageHeader", "Usage:")); 184 | Message.Processing = Message.replace(configGetString("Message.Processing", "Just a sec...")); 185 | Message.HelpMessageList = Message.replace(configGetStringList("Message.HelpMessageList")); 186 | if (Message.HelpMessageList.size() == 0) { 187 | Message.HelpMessageList = Arrays.asList("/uniban check <§lPlayer/UUID§r>", 188 | "/uniban whitelist <“§ladd§r”/“§lremove§r”> <§lPlayer/UUID>", 189 | "/uniban share <§lYour Server Hostname§r, eg. §nexample.com§r>", 190 | "/uniban subscribe <§lSubscription Key§r>", 191 | "/uniban exempt <§lServer Address§r>", 192 | "/uniban reload"); 193 | } 194 | } 195 | 196 | 197 | public void addSubscription(ServerEntry serverEntry, String password, boolean save) { 198 | Subscriptions.put(serverEntry, Encryption.getKeyFromString(password)); 199 | 200 | if (save) { 201 | String key = String.valueOf(System.currentTimeMillis()); 202 | configSet("Subscription." + key + ".Host", serverEntry.host); 203 | configSet("Subscription." + key + ".Port", serverEntry.port); 204 | configSet("Subscription." + key + ".Password", password); 205 | saveConfig(); 206 | } 207 | } 208 | 209 | public boolean removeSubscription(String address, boolean save) { 210 | ServerEntry serverEntry = new ServerEntry(address); 211 | boolean isRemoved = false; 212 | 213 | for (ServerEntry listedServerEntry : Subscriptions.keySet()) { 214 | if (listedServerEntry.host.equals(serverEntry.host) 215 | && (serverEntry.port == -1 || (serverEntry.port == listedServerEntry.port))) { 216 | Subscriptions.remove(listedServerEntry); 217 | isRemoved = true; 218 | break; 219 | } 220 | } 221 | 222 | if (save) { 223 | boolean isSaved = false; 224 | for (String key : getConfigurationSectionKeys("Subscription")) { 225 | if (configGetString("Subscription." + key + ".Host", "").equals(serverEntry.host) 226 | && configGetInt("Subscription." + key + ".Port", 0) == (serverEntry.port)) { 227 | configSet("Subscription." + key, null); 228 | saveConfig(); 229 | isSaved = true; 230 | break; 231 | } 232 | } 233 | return isSaved; 234 | } 235 | 236 | return isRemoved; 237 | } 238 | 239 | public String[] getSubscriptions() { 240 | // TODO Performance optimization 241 | List addressList = new ArrayList<>(); 242 | for (ServerEntry serverEntry : PluginConfig.Subscriptions.keySet()) { 243 | addressList.add(serverEntry.host + ":" + serverEntry.port); 244 | } 245 | return addressList.toArray(new String[0]); 246 | } 247 | 248 | abstract boolean configGetBoolean(String path, Boolean def); 249 | 250 | abstract String configGetString(String path, String def); 251 | 252 | abstract Double configGetDouble(String path, Double def); 253 | 254 | abstract int configGetInt(String path, int def); 255 | 256 | abstract List configGetStringList(String path); 257 | 258 | abstract boolean configIsSection(String path); 259 | 260 | abstract Set getConfigurationSectionKeys(String path); 261 | 262 | abstract void configSet(String path, Object object); 263 | 264 | abstract void saveConfig(); 265 | 266 | } 267 | -------------------------------------------------------------------------------- /src/main/java/cc/eumc/uniban/controller/UniBanController.java: -------------------------------------------------------------------------------- 1 | package cc.eumc.uniban.controller; 2 | 3 | import cc.eumc.uniban.config.Message; 4 | import cc.eumc.uniban.config.PluginConfig; 5 | import cc.eumc.uniban.extension.HttpService; 6 | import cc.eumc.uniban.extension.UniBanExtension; 7 | import cc.eumc.uniban.handler.BanListRequestHandler; 8 | import cc.eumc.uniban.handler.IDRequestHandler; 9 | import cc.eumc.uniban.serverinterface.PlayerInfo; 10 | import cc.eumc.uniban.util.Encryption; 11 | import cc.eumc.uniban.util.HttpRequest; 12 | import com.google.gson.Gson; 13 | import com.google.gson.GsonBuilder; 14 | import com.sun.istack.internal.NotNull; 15 | import com.sun.net.httpserver.HttpContext; 16 | import com.sun.net.httpserver.HttpHandler; 17 | import com.sun.net.httpserver.HttpServer; 18 | import de.cgrotz.kademlia.node.Key; 19 | import org.json.simple.JSONArray; 20 | import org.json.simple.JSONObject; 21 | import org.json.simple.parser.JSONParser; 22 | 23 | import java.io.File; 24 | import java.io.FileReader; 25 | import java.io.FileWriter; 26 | import java.io.IOException; 27 | import java.net.InetSocketAddress; 28 | import java.net.URL; 29 | import java.util.*; 30 | import java.util.concurrent.Executors; 31 | import java.util.concurrent.atomic.AtomicInteger; 32 | 33 | public abstract class UniBanController { 34 | HttpServer server; 35 | DeliveryController deliveryController; 36 | boolean serverStarted; 37 | List extensions = new ArrayList<>(); 38 | 39 | final String banListFilename = "banlist.json"; 40 | 41 | String banJson = ""; 42 | Set localBanned = new HashSet<>(); 43 | 44 | Map> bannedPlayerOnline = new HashMap<>(); 45 | 46 | public UniBanController () { 47 | serverStarted = false; 48 | loadBanListFromDisk(); 49 | 50 | if (PluginConfig.EnableBroadcast) { 51 | if (PluginConfig.Legacy_Enabled) { 52 | try { 53 | server = HttpServer.create(new InetSocketAddress(PluginConfig.Legacy_Host, PluginConfig.Legacy_Port), 0); 54 | server.createContext("/get", new BanListRequestHandler(this)); 55 | // experiential 56 | server.createContext("/identify", new IDRequestHandler(this)); 57 | server.setExecutor(Executors.newFixedThreadPool(PluginConfig.Legacy_Threads)); 58 | server.start(); 59 | serverStarted = true; 60 | } catch (IOException e) { 61 | e.printStackTrace(); 62 | serverStarted = false; 63 | } 64 | } 65 | 66 | // if (PluginConfig.EnableDHT) { 67 | // deliveryController = new DeliveryController(this); 68 | // } 69 | } 70 | 71 | } 72 | 73 | public void destruct() { 74 | unloadExtensions(); 75 | if (server != null) { 76 | server.stop(0); 77 | } 78 | } 79 | 80 | public HttpContext createHttpContent(String path, HttpHandler handler) { 81 | if (server == null) return null; 82 | 83 | return server.createContext(path, handler); 84 | } 85 | 86 | public boolean removeHttpContent(HttpContext httpContext) { 87 | if (server == null) return false; 88 | 89 | server.removeContext(httpContext); 90 | return true; 91 | } 92 | 93 | public void registerExtension(UniBanExtension extension) { 94 | extensions.add(extension); 95 | loadExtension(extension); 96 | } 97 | 98 | void loadExtension(UniBanExtension extension) { 99 | try { 100 | sendInfo("Loading extension: " + extension.getName() + "(" + extension.getVersion() + ")@" + extension.getAuthor()); 101 | extension.onExtensionLoad(); 102 | 103 | HttpService httpService; 104 | if ((httpService = extension.getHttpService()) != null) { 105 | HttpContext httpContext; 106 | if ((httpContext = createHttpContent(httpService.path, httpService.handler)) != null) { 107 | extension.getHttpService().setContext(httpContext); 108 | sendInfo("HTTPContent registered for extension: " + extension.getName()); 109 | } 110 | else { 111 | sendWarning("Failed registering HTTPContent for extension: " + extension.getName()); 112 | } 113 | } 114 | 115 | } catch (Exception e) { 116 | e.printStackTrace(); 117 | } 118 | } 119 | 120 | void unloadExtensions() { 121 | try { 122 | extensions.forEach(UniBanExtension::onExtensionUnload); 123 | } catch (Exception e) { 124 | e.printStackTrace(); 125 | } 126 | } 127 | 128 | public abstract File getDataFolder(); 129 | public abstract void saveConfig(); 130 | 131 | public void loadBanListFromDisk() { 132 | File file = new File(getDataFolder(), banListFilename); 133 | if (!file.exists()) { 134 | try { 135 | file.createNewFile(); 136 | return; 137 | } catch (IOException e) { 138 | e.printStackTrace(); 139 | return; 140 | } 141 | } 142 | 143 | JSONParser jsonParser = new JSONParser(); 144 | 145 | try { 146 | FileReader reader = new FileReader(file); 147 | Object obj = null; 148 | obj = jsonParser.parse(reader); 149 | JSONArray uuidhostArray = (JSONArray) obj; 150 | 151 | //Map> map = new HashMap<>(); 152 | 153 | AtomicInteger count = new AtomicInteger(); 154 | 155 | uuidhostArray.forEach( object -> { 156 | JSONObject playerObject = (JSONObject) object; 157 | 158 | String uuidStr = playerObject.get("uuid").toString(); 159 | UUID uuid = UUID.fromString(uuidStr); 160 | String validationUUID = uuid.toString(); 161 | if (validationUUID.equals(uuidStr)) { 162 | JSONArray hostArray = (JSONArray) playerObject.get("server"); 163 | List hostList = new ArrayList<>(); 164 | for (int i=0; i { 176 | JSONObject object = (JSONObject) uuidListArray. 177 | 178 | String uuidStr = .toString(); 179 | UUID uuid = UUID.fromString(uuidStr); 180 | String validationUUID = uuid.toString(); 181 | if (validationUUID.equals(uuidStr)) { 182 | JSONObject hostObject = (JSONObject) (uuidhostObject); 183 | for (Object key : hostObject.keySet()) { 184 | String host = ((JSONObject)key).toString(); 185 | addOnlineBanned(uuid, host); 186 | count.getAndIncrement(); 187 | } 188 | } 189 | else { 190 | sendSevere("Invalid UUID: " + uuidStr); 191 | } 192 | });*/ 193 | 194 | sendInfo(String.format(Message.LoadedFromLocalCache, count)); 195 | } catch (Exception e) { 196 | e.printStackTrace(); 197 | return; 198 | } 199 | 200 | /* 201 | FileConfiguration banListConfig = YamlConfiguration.loadConfiguration(file); 202 | if (banListConfig.isConfigurationSection("UniBanList")) { 203 | for (String uuidStr : banListConfig.getConfigurationSection("UniBanList").getKeys(false)) { 204 | try { 205 | // Check if the provided UUID is valid 206 | UUID uuid = UUID.fromString(uuidStr); 207 | String validationUUID = uuid.toString(); 208 | if (validationUUID.equals(uuidStr)) { 209 | if (banListConfig.isConfigurationSection("UniBanList." + uuidStr)) 210 | for (String host : banListConfig.getConfigurationSection("UniBanList." + uuidStr).getKeys(false)) { 211 | addOnlineBanned(uuid, host); 212 | } 213 | } 214 | } catch (IllegalArgumentException e) { 215 | sendWarning("Invalid UUID: " + uuidStr); 216 | continue; 217 | } 218 | } 219 | }*/ 220 | } 221 | 222 | public void saveBanList() { 223 | File file = new File(getDataFolder(), banListFilename); 224 | if (!file.exists()) { 225 | try { 226 | file.createNewFile(); 227 | } catch (IOException e) { 228 | e.printStackTrace(); 229 | return; 230 | } 231 | } 232 | 233 | JSONArray banListArray = new JSONArray(); 234 | for (UUID uuid : bannedPlayerOnline.keySet()) { 235 | JSONObject playerObject = new JSONObject(); 236 | JSONArray hostArray = new JSONArray(); 237 | 238 | playerObject.put("uuid", uuid.toString()); 239 | hostArray.addAll(bannedPlayerOnline.get(uuid)); 240 | playerObject.put("server", hostArray); 241 | 242 | banListArray.add(playerObject); 243 | } 244 | 245 | try (FileWriter fw = new FileWriter(file)) { 246 | Gson gson = new GsonBuilder().setPrettyPrinting().create(); 247 | fw.write(gson.toJson(banListArray)); 248 | fw.flush(); 249 | } catch (IOException e) { 250 | e.printStackTrace(); 251 | sendSevere("Failed saving ban-list to " + banListFilename); 252 | } 253 | 254 | /* 255 | FileConfiguration banListConfig = YamlConfiguration.loadConfiguration(file); 256 | for (UUID uuid : bannedPlayerOnline.keySet()) { 257 | List hosts = bannedPlayerOnline.get(uuid); 258 | banListConfig.set("UniBanList."+uuid.toString(), hosts); 259 | } 260 | try { 261 | banListConfig.save(file); 262 | } catch (IOException e) { 263 | sendSevere("Failed saving " + banListFilename); 264 | }*/ 265 | } 266 | 267 | public void addWhitelist(UUID uuid) { 268 | PluginConfig.UUIDWhitelist.add(uuid.toString()); 269 | List whitelist = configGetStringList("UUIDWhitelist"); 270 | whitelist.add(uuid.toString()); 271 | configSet("UUIDWhitelist", whitelist); 272 | saveConfig(); 273 | } 274 | 275 | public void removeWhitelist(UUID uuid) { 276 | PluginConfig.UUIDWhitelist.remove(uuid.toString()); 277 | List whitelist = configGetStringList("UUIDWhitelist"); 278 | whitelist.remove(uuid.toString()); 279 | configSet("UUIDWhitelist", whitelist); 280 | saveConfig(); 281 | } 282 | 283 | public void addOnlineBanned(UUID uuid, String fromServer) { 284 | if (bannedPlayerOnline.containsKey(uuid)) { 285 | List serverList = new ArrayList<>(bannedPlayerOnline.get(uuid)); 286 | if (!serverList.contains(fromServer)) { // Fix duplication 287 | serverList.add(fromServer); 288 | bannedPlayerOnline.put(uuid, serverList); 289 | } 290 | } 291 | else { 292 | bannedPlayerOnline.put(uuid, Collections.singletonList(fromServer)); 293 | } 294 | } 295 | 296 | public void purgeOnlineBannedOfHost(String address, List banList) { 297 | //List banList = new ArrayList(Arrays.asList(list)); 298 | for (UUID uuid : bannedPlayerOnline.keySet()) { 299 | // Fix: the player would not be removed even if he/she is unbanned from all subscribed servers 300 | if (bannedPlayerOnline.get(uuid).contains(address) && !banList.contains(uuid.toString()) ) { 301 | removeOnlineBanned(uuid, address); 302 | break; 303 | } 304 | } 305 | } 306 | 307 | public void removeOnlineBanned(UUID uuid, String fromServer) { 308 | if (bannedPlayerOnline.containsKey(uuid)) { 309 | List serverList = new ArrayList<>(bannedPlayerOnline.get(uuid)); 310 | 311 | if (serverList.size() == 1 && serverList.get(0).equals(fromServer)) { // The player was only banned from this server 312 | bannedPlayerOnline.remove(uuid); 313 | } 314 | // Fix: the player would not be removed even if he/she is unbanned from all subscribed servers 315 | else { 316 | serverList.remove(fromServer); 317 | bannedPlayerOnline.put(uuid, serverList); 318 | } 319 | } 320 | } 321 | 322 | public Boolean isBannedOnline(UUID uuid) { 323 | // NOT_TODO Display bannedFrom. 324 | return bannedPlayerOnline.containsKey(uuid); 325 | } 326 | 327 | public int getBannedServerAmount(@NotNull UUID uuid) { 328 | // Fix: Null pointer exception 329 | List fromServer = bannedPlayerOnline.get(uuid); 330 | if (fromServer == null) 331 | return 0; 332 | else 333 | return fromServer.size(); 334 | } 335 | 336 | public List getBannedServerList(UUID uuid) { 337 | return bannedPlayerOnline.get(uuid); 338 | } 339 | 340 | public void addLocalBan(UUID uuid) { 341 | localBanned.add(uuid); 342 | updateLocalBanListCache(localBanned, false); 343 | } 344 | 345 | public void removeLocalBan(UUID uuid) { 346 | localBanned.remove(uuid); 347 | updateLocalBanListCache(localBanned, false); 348 | } 349 | 350 | public void updateLocalBanListCache(Set uuidSet) { 351 | updateLocalBanListCache(uuidSet, true); 352 | } 353 | 354 | public void updateLocalBanListCache(Set uuidSet, boolean updateBanSetCache) { 355 | if (localBanned.equals(uuidSet)) return; 356 | 357 | if (updateBanSetCache) localBanned = uuidSet; 358 | 359 | List uuidStringList = new ArrayList<>(); 360 | for (UUID uuid : uuidSet) { 361 | uuidStringList.add(uuid.toString()); 362 | } 363 | String json = Encryption.encrypt(new Gson().toJson(uuidStringList), PluginConfig.EncryptionKey); 364 | if (json == null) { 365 | sendSevere("§cFailed encrypting ban-list."); 366 | json = ""; 367 | } 368 | this.banJson = json; 369 | 370 | sendLocalBanListToDHT(); 371 | } 372 | 373 | public String getBanListJson() { 374 | return banJson; 375 | } 376 | 377 | public void sendLocalBanListToDHT() { 378 | if (!DeliveryController.isReady()) return; 379 | 380 | deliveryController.put(Key.build(""), "{{banList}}" + getBanListJson() + "{{/banList}}"); 381 | } 382 | 383 | public void sendLocalBanListToURL() { 384 | try { 385 | HttpRequest.post(new URL(PluginConfig.ActiveMode_PostUrl)) 386 | .bodyForm(HttpRequest.Form.create().add("list", getBanListJson()).add("secret", PluginConfig.ActiveMode_PostSecret)) 387 | .execute() 388 | .expectResponseCode(200); 389 | } catch (IOException e) { 390 | sendWarning("Error posting ban-list to remote url:"); 391 | e.printStackTrace(); 392 | } 393 | } 394 | 395 | public boolean shouldIgnoreReason(String reason) { 396 | if (PluginConfig.ExcludeIfReasonContain.size() == 0 || reason == null) { 397 | return false; 398 | } 399 | 400 | final String reasonLowerCase = reason.toLowerCase(); 401 | 402 | for (String keyword : PluginConfig.ExcludeIfReasonContain) { 403 | if (reasonLowerCase.contains(keyword.toLowerCase())) { 404 | return true; 405 | } 406 | } 407 | return false; 408 | } 409 | 410 | abstract PlayerInfo getPlayerInfoFromUUID(UUID uuid); 411 | 412 | private class NameUid { 413 | String name; 414 | String id; 415 | } 416 | 417 | public static UUID nameToUUID(String name) { 418 | try { 419 | Gson g = new Gson(); 420 | String jsonText = HttpRequest.get(new URL("https://api.mojang.com/users/profiles/minecraft/" + name)) 421 | .execute() 422 | .expectResponseCode(200) 423 | .returnContent() 424 | .asString("UTF-8").trim(); 425 | NameUid nameUid = g.fromJson(jsonText, NameUid.class); 426 | //System.out.println(jsonText); 427 | if (nameUid == null) { 428 | return null; 429 | } 430 | else { 431 | //System.out.println(nameUid.id); 432 | return UUID.fromString(nameUid.id.replaceFirst( 433 | "(\\p{XDigit}{8})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}{4})(\\p{XDigit}+)", "$1-$2-$3-$4-$5" 434 | )); 435 | } 436 | } catch (Exception e) { 437 | e.printStackTrace(); 438 | return null; 439 | } 440 | } 441 | 442 | public abstract void sendInfo(String message); 443 | public abstract void sendWarning(String message); 444 | public abstract void sendSevere(String message); 445 | 446 | public abstract boolean configGetBoolean(String path, Boolean def); 447 | public abstract String configGetString(String path, String def); 448 | public abstract Double configGetDouble(String path, Double def); 449 | public abstract int configGetInt(String path, int def); 450 | public abstract List configGetStringList(String path); 451 | public abstract boolean configIsSection(String path); 452 | public abstract Set getConfigurationSectionKeys(String path); 453 | 454 | public abstract void configSet(String path, Object object); 455 | 456 | public abstract void runTaskLater(Runnable task, int delayTick); 457 | 458 | } 459 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------