PageRenderTime 36ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/sk89q/commandbook/bans/FlatFileBanDatabase.java

https://github.com/rcwidower/commandbook
Java | 277 lines | 244 code | 10 blank | 23 comment | 2 complexity | 6571f603f3f2d5b789e58ebfc593e741 MD5 | raw file
  1. // $Id$
  2. /*
  3. * Copyright (C) 2010, 2011 sk89q <http://www.sk89q.com>
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. package com.sk89q.commandbook.bans;
  19. import java.io.BufferedReader;
  20. import java.io.BufferedWriter;
  21. import java.io.File;
  22. import java.io.FileInputStream;
  23. import java.io.FileNotFoundException;
  24. import java.io.FileOutputStream;
  25. import java.io.IOException;
  26. import java.io.InputStreamReader;
  27. import java.io.OutputStreamWriter;
  28. import java.io.UnsupportedEncodingException;
  29. import java.net.InetAddress;
  30. import java.text.SimpleDateFormat;
  31. import java.util.Date;
  32. import java.util.HashSet;
  33. import java.util.Set;
  34. import java.util.logging.FileHandler;
  35. import java.util.logging.Formatter;
  36. import java.util.logging.Level;
  37. import java.util.logging.LogRecord;
  38. import java.util.logging.Logger;
  39. import org.bukkit.command.CommandSender;
  40. import org.bukkit.entity.Player;
  41. import com.sk89q.commandbook.CommandBookPlugin;
  42. /**
  43. * Flat file ban database.
  44. *
  45. * @author sk89q
  46. */
  47. public class FlatFileBanDatabase implements BanDatabase {
  48. protected static final Logger logger = Logger.getLogger("Minecraft.CommandBook");
  49. protected final Logger auditLogger
  50. = Logger.getLogger("Minecraft.CommandBook.Bans");
  51. protected CommandBookPlugin plugin;
  52. protected File dataDirectory;
  53. protected File namesFile;
  54. protected File ipFile;
  55. protected Set<String> bannedNames;
  56. protected Set<String> bannedIP;
  57. public FlatFileBanDatabase(File dataDirectory, CommandBookPlugin plugin) {
  58. this.dataDirectory = dataDirectory;
  59. this.plugin = plugin;
  60. namesFile = new File(dataDirectory, "banned_names.txt");
  61. ipFile = new File(dataDirectory, "banned_ip.txt");
  62. // Set up an audit trail
  63. try {
  64. FileHandler handler = new FileHandler(
  65. (new File(dataDirectory, "bans.%g.%u.log")).getAbsolutePath()
  66. .replace("\\", "/"));
  67. handler.setFormatter(new Formatter() {
  68. private SimpleDateFormat dateFormat =
  69. new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  70. @Override
  71. public String format(LogRecord record) {
  72. return "[" + dateFormat.format(new Date())
  73. + "] " + record.getMessage() + "\r\n";
  74. }
  75. });
  76. auditLogger.addHandler(handler);
  77. } catch (SecurityException e) {
  78. logger.warning("CommandBook: Failed to setup audit log for the "
  79. + "flat file ban database: " + e.getMessage());
  80. } catch (IOException e) {
  81. logger.warning("CommandBook: Failed to setup audit log for the "
  82. + "flat file ban database: " + e.getMessage());
  83. }
  84. }
  85. public synchronized boolean load() {
  86. boolean successful = true;
  87. try {
  88. bannedNames = readLowercaseList(namesFile);
  89. logger.info("CommandBook: " + bannedNames.size() + " banned name(s) loaded.");
  90. } catch (IOException e) {
  91. bannedNames = new HashSet<String>();
  92. logger.warning("CommandBook: Failed to load " + namesFile.getAbsolutePath()
  93. + ": " + e.getMessage());
  94. successful = false;
  95. }
  96. /*
  97. try {
  98. bannedIP = readList(ipFile);
  99. logger.info("CommandBook: " + bannedIP.size() + " banned IP(s) loaded.");
  100. } catch (IOException e) {
  101. bannedIP = new HashSet<String>();
  102. logger.warning("CommandBook: Failed to load " + ipFile.getAbsolutePath()
  103. + ": " + e.getMessage());
  104. successful = false;
  105. }
  106. */
  107. return successful;
  108. }
  109. /**
  110. * Read a list from file. Each line is trimmed and made lower case.
  111. *
  112. * @param file
  113. * @return
  114. * @throws IOException
  115. */
  116. protected synchronized Set<String> readLowercaseList(File file) throws IOException {
  117. FileInputStream input = null;
  118. Set<String> list = new HashSet<String>();
  119. try {
  120. input = new FileInputStream(file);
  121. InputStreamReader streamReader = new InputStreamReader(input, "utf-8");
  122. BufferedReader reader = new BufferedReader(streamReader);
  123. String line;
  124. while ((line = reader.readLine()) != null) {
  125. line = line.trim();
  126. if (line.length() > 0) {
  127. list.add(line.toLowerCase().trim());
  128. }
  129. }
  130. } catch (FileNotFoundException e) {
  131. } finally {
  132. if (input != null) {
  133. try {
  134. input.close();
  135. } catch (IOException e) {
  136. }
  137. }
  138. }
  139. return list;
  140. }
  141. public synchronized boolean save() {
  142. boolean successful = true;
  143. try {
  144. writeList(namesFile, bannedNames);
  145. //logger.info("CommandBook: " + bannedNames.size() + " banned names written.");
  146. } catch (IOException e) {
  147. logger.warning("CommandBook: Failed to write " + namesFile.getAbsolutePath()
  148. + ": " + e.getMessage());
  149. successful = false;
  150. }
  151. /*
  152. try {
  153. writeList(ipFile, bannedIP);
  154. //logger.info("CommandBook: " + bannedIP.size() + " banned IPs written.");
  155. } catch (IOException e) {
  156. logger.warning("CommandBook: Failed to write " + ipFile.getAbsolutePath()
  157. + ": " + e.getMessage());
  158. successful = false;
  159. }
  160. */
  161. return successful;
  162. }
  163. protected synchronized void writeList(File file, Set<String> list)
  164. throws IOException {
  165. FileOutputStream output = null;
  166. try {
  167. output = new FileOutputStream(file);
  168. OutputStreamWriter streamWriter = new OutputStreamWriter(output, "utf-8");
  169. BufferedWriter writer = new BufferedWriter(streamWriter);
  170. for (String line : list) {
  171. writer.write(line + "\r\n");
  172. }
  173. writer.close();
  174. } catch (FileNotFoundException e) {
  175. } catch (UnsupportedEncodingException e) {
  176. logger.log(Level.WARNING, "Failed to write list", e);
  177. } finally {
  178. if (output != null) {
  179. try {
  180. output.close();
  181. } catch (IOException e) {
  182. }
  183. }
  184. }
  185. }
  186. public synchronized boolean isBannedName(String name) {
  187. return bannedNames.contains(name.toLowerCase().trim());
  188. }
  189. public synchronized boolean isBannedAddress(InetAddress address) {
  190. return bannedIP.contains(address.getHostAddress());
  191. }
  192. public synchronized void banName(String name, CommandSender source, String reason) {
  193. auditLogger.info(String.format("BAN: %s (%s) banned name '%s': %s",
  194. plugin.toUniqueName(source),
  195. plugin.toInetAddressString(source),
  196. name,
  197. reason));
  198. bannedNames.add(name.toLowerCase());
  199. }
  200. public synchronized void banAddress(String address, CommandSender source, String reason) {
  201. auditLogger.info(String.format("BAN: %s (%s) banned address '%s': %s",
  202. plugin.toUniqueName(source),
  203. plugin.toInetAddressString(source),
  204. address,
  205. reason));
  206. bannedIP.add(address);
  207. }
  208. public boolean unbanName(String name, CommandSender source, String reason) {
  209. boolean removed = bannedNames.remove(name.toLowerCase());
  210. if (removed) {
  211. auditLogger.info(String.format("UNBAN: %s (%s) unbanned name '%s': %s",
  212. plugin.toUniqueName(source),
  213. plugin.toInetAddressString(source),
  214. name,
  215. reason));
  216. }
  217. return removed;
  218. }
  219. public boolean unbanAddress(String address, CommandSender source, String reason) {
  220. boolean removed = bannedIP.remove(address);
  221. if (removed) {
  222. auditLogger.info(String.format("UNBAN: %s (%s) unbanned ADDRESS '%s'",
  223. plugin.toUniqueName(source),
  224. plugin.toInetAddressString(source),
  225. address,
  226. reason));
  227. }
  228. return removed;
  229. }
  230. public void logKick(Player player, CommandSender source, String reason) {
  231. auditLogger.info(String.format("KICKED: %s (%s) kicked player '%s': %s",
  232. plugin.toUniqueName(source),
  233. plugin.toInetAddressString(source),
  234. player.getName(),
  235. reason));
  236. }
  237. }