001 package org.bukkit.command.defaults; 002 003 import java.util.List; 004 import java.util.regex.Pattern; 005 006 import org.apache.commons.lang.StringUtils; 007 import org.apache.commons.lang.Validate; 008 import org.bukkit.BanList; 009 import org.bukkit.Bukkit; 010 import org.bukkit.ChatColor; 011 import org.bukkit.command.Command; 012 import org.bukkit.command.CommandSender; 013 import org.bukkit.entity.Player; 014 015 import com.google.common.collect.ImmutableList; 016 017 public class BanIpCommand extends VanillaCommand { 018 public static final Pattern ipValidity = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); 019 020 public BanIpCommand() { 021 super("ban-ip"); 022 this.description = "Prevents the specified IP address from using this server"; 023 this.usageMessage = "/ban-ip <address|player> [reason ...]"; 024 this.setPermission("bukkit.command.ban.ip"); 025 } 026 027 @Override 028 public boolean execute(CommandSender sender, String currentAlias, String[] args) { 029 if (!testPermission(sender)) return true; 030 if (args.length < 1) { 031 sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); 032 return false; 033 } 034 035 String reason = args.length > 0 ? StringUtils.join(args, ' ', 1, args.length) : null; 036 037 if (ipValidity.matcher(args[0]).matches()) { 038 processIPBan(args[0], sender, reason); 039 } else { 040 Player player = Bukkit.getPlayer(args[0]); 041 042 if (player == null) { 043 sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); 044 return false; 045 } 046 047 processIPBan(player.getAddress().getAddress().getHostAddress(), sender, reason); 048 } 049 050 return true; 051 } 052 053 private void processIPBan(String ip, CommandSender sender, String reason) { 054 Bukkit.getBanList(BanList.Type.IP).addBan(ip, reason, null, sender.getName()); 055 056 // Find all matching players and kick 057 for (Player player : Bukkit.getOnlinePlayers()) { 058 if (player.getAddress().getAddress().getHostAddress().equals(ip)) { 059 player.kickPlayer("You have been IP banned."); 060 } 061 } 062 063 Command.broadcastCommandMessage(sender, "Banned IP Address " + ip); 064 } 065 066 @Override 067 public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException { 068 Validate.notNull(sender, "Sender cannot be null"); 069 Validate.notNull(args, "Arguments cannot be null"); 070 Validate.notNull(alias, "Alias cannot be null"); 071 072 if (args.length == 1) { 073 return super.tabComplete(sender, alias, args); 074 } 075 return ImmutableList.of(); 076 } 077 }