GameServerTable.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package com.l2jserver.loginserver;
  16. import java.io.File;
  17. import java.io.FileInputStream;
  18. import java.io.FileNotFoundException;
  19. import java.io.InputStream;
  20. import java.math.BigInteger;
  21. import java.net.InetAddress;
  22. import java.net.UnknownHostException;
  23. import java.security.GeneralSecurityException;
  24. import java.security.InvalidAlgorithmParameterException;
  25. import java.security.KeyPair;
  26. import java.security.KeyPairGenerator;
  27. import java.security.NoSuchAlgorithmException;
  28. import java.security.spec.RSAKeyGenParameterSpec;
  29. import java.sql.Connection;
  30. import java.sql.PreparedStatement;
  31. import java.sql.ResultSet;
  32. import java.sql.SQLException;
  33. import java.util.ArrayList;
  34. import java.util.Map;
  35. import java.util.Map.Entry;
  36. import java.util.logging.Level;
  37. import java.util.logging.Logger;
  38. import javolution.io.UTF8StreamReader;
  39. import javolution.util.FastMap;
  40. import javolution.xml.stream.XMLStreamConstants;
  41. import javolution.xml.stream.XMLStreamException;
  42. import javolution.xml.stream.XMLStreamReaderImpl;
  43. import com.l2jserver.Config;
  44. import com.l2jserver.L2DatabaseFactory;
  45. import com.l2jserver.loginserver.network.gameserverpackets.ServerStatus;
  46. import com.l2jserver.util.IPSubnet;
  47. import com.l2jserver.util.Rnd;
  48. /**
  49. *
  50. * @author KenM
  51. */
  52. public class GameServerTable
  53. {
  54. private static Logger _log = Logger.getLogger(GameServerTable.class.getName());
  55. private static GameServerTable _instance;
  56. // Server Names Config
  57. private static Map<Integer, String> _serverNames = new FastMap<Integer, String>();
  58. // Game Server Table
  59. private Map<Integer, GameServerInfo> _gameServerTable = new FastMap<Integer, GameServerInfo>().shared();
  60. // RSA Config
  61. private static final int KEYS_SIZE = 10;
  62. private KeyPair[] _keyPairs;
  63. public static void load() throws SQLException, GeneralSecurityException
  64. {
  65. synchronized (GameServerTable.class)
  66. {
  67. if (_instance == null)
  68. {
  69. _instance = new GameServerTable();
  70. }
  71. else
  72. {
  73. throw new IllegalStateException("Load can only be invoked a single time.");
  74. }
  75. }
  76. }
  77. public static GameServerTable getInstance()
  78. {
  79. return _instance;
  80. }
  81. public GameServerTable() throws SQLException, NoSuchAlgorithmException, InvalidAlgorithmParameterException
  82. {
  83. loadServerNames();
  84. _log.info("Loaded " + _serverNames.size() + " server names");
  85. loadRegisteredGameServers();
  86. _log.info("Loaded " + _gameServerTable.size() + " registered Game Servers");
  87. loadRSAKeys();
  88. _log.info("Cached " + _keyPairs.length + " RSA keys for Game Server communication.");
  89. }
  90. private void loadRSAKeys() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException
  91. {
  92. KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  93. RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(512, RSAKeyGenParameterSpec.F4);
  94. keyGen.initialize(spec);
  95. _keyPairs = new KeyPair[KEYS_SIZE];
  96. for (int i = 0; i < KEYS_SIZE; i++)
  97. {
  98. _keyPairs[i] = keyGen.genKeyPair();
  99. }
  100. }
  101. private void loadServerNames()
  102. {
  103. InputStream in = null;
  104. try
  105. {
  106. in = new FileInputStream(new File(Config.DATAPACK_ROOT, "data/servername.xml"));
  107. XMLStreamReaderImpl xpp = new XMLStreamReaderImpl();
  108. xpp.setInput(new UTF8StreamReader().setInput(in));
  109. for (int e = xpp.getEventType(); e != XMLStreamConstants.END_DOCUMENT; e = xpp.next())
  110. {
  111. if (e == XMLStreamConstants.START_ELEMENT)
  112. {
  113. if (xpp.getLocalName().toString().equals("server"))
  114. {
  115. Integer id = Integer.valueOf(xpp.getAttributeValue(null, "id").toString());
  116. String name = xpp.getAttributeValue(null, "name").toString();
  117. _serverNames.put(id, name);
  118. }
  119. }
  120. }
  121. }
  122. catch (FileNotFoundException e)
  123. {
  124. _log.warning("servername.xml could not be loaded: file not found");
  125. }
  126. catch (XMLStreamException xppe)
  127. {
  128. _log.warning(getClass().getSimpleName() + ": " + xppe.getMessage());
  129. }
  130. finally
  131. {
  132. try
  133. {
  134. in.close();
  135. }
  136. catch (Exception e)
  137. {
  138. _log.warning(getClass().getSimpleName() + ": " + e.getMessage());
  139. }
  140. }
  141. }
  142. private void loadRegisteredGameServers() throws SQLException
  143. {
  144. Connection con = null;
  145. PreparedStatement statement = null;
  146. int id;
  147. con = L2DatabaseFactory.getInstance().getConnection();
  148. statement = con.prepareStatement("SELECT * FROM gameservers");
  149. ResultSet rset = statement.executeQuery();
  150. GameServerInfo gsi;
  151. while (rset.next())
  152. {
  153. id = rset.getInt("server_id");
  154. gsi = new GameServerInfo(id, stringToHex(rset.getString("hexid")));
  155. _gameServerTable.put(id, gsi);
  156. }
  157. rset.close();
  158. statement.close();
  159. L2DatabaseFactory.close(con);
  160. }
  161. public Map<Integer, GameServerInfo> getRegisteredGameServers()
  162. {
  163. return _gameServerTable;
  164. }
  165. public GameServerInfo getRegisteredGameServerById(int id)
  166. {
  167. return _gameServerTable.get(id);
  168. }
  169. public boolean hasRegisteredGameServerOnId(int id)
  170. {
  171. return _gameServerTable.containsKey(id);
  172. }
  173. public boolean registerWithFirstAvaliableId(GameServerInfo gsi)
  174. {
  175. // avoid two servers registering with the same "free" id
  176. synchronized (_gameServerTable)
  177. {
  178. for (Entry<Integer, String> entry : _serverNames.entrySet())
  179. {
  180. if (!_gameServerTable.containsKey(entry.getKey()))
  181. {
  182. _gameServerTable.put(entry.getKey(), gsi);
  183. gsi.setId(entry.getKey());
  184. return true;
  185. }
  186. }
  187. }
  188. return false;
  189. }
  190. public boolean register(int id, GameServerInfo gsi)
  191. {
  192. // avoid two servers registering with the same id
  193. synchronized (_gameServerTable)
  194. {
  195. if (!_gameServerTable.containsKey(id))
  196. {
  197. _gameServerTable.put(id, gsi);
  198. gsi.setId(id);
  199. return true;
  200. }
  201. }
  202. return false;
  203. }
  204. public void registerServerOnDB(GameServerInfo gsi)
  205. {
  206. this.registerServerOnDB(gsi.getHexId(), gsi.getId(), gsi.getExternalHost());
  207. }
  208. public void registerServerOnDB(byte[] hexId, int id, String externalHost)
  209. {
  210. Connection con = null;
  211. PreparedStatement statement = null;
  212. try
  213. {
  214. con = L2DatabaseFactory.getInstance().getConnection();
  215. statement = con.prepareStatement("INSERT INTO gameservers (hexid,server_id,host) values (?,?,?)");
  216. statement.setString(1, hexToString(hexId));
  217. statement.setInt(2, id);
  218. statement.setString(3, externalHost);
  219. statement.executeUpdate();
  220. statement.close();
  221. this.register(id, new GameServerInfo(id, hexId));
  222. }
  223. catch (SQLException e)
  224. {
  225. _log.log(Level.SEVERE, "SQL error while saving gameserver.", e);
  226. }
  227. finally
  228. {
  229. L2DatabaseFactory.close(con);
  230. }
  231. }
  232. public String getServerNameById(int id)
  233. {
  234. return getServerNames().get(id);
  235. }
  236. public Map<Integer, String> getServerNames()
  237. {
  238. return _serverNames;
  239. }
  240. public KeyPair getKeyPair()
  241. {
  242. return _keyPairs[Rnd.nextInt(10)];
  243. }
  244. private byte[] stringToHex(String string)
  245. {
  246. return new BigInteger(string, 16).toByteArray();
  247. }
  248. private String hexToString(byte[] hex)
  249. {
  250. if (hex == null)
  251. {
  252. return "null";
  253. }
  254. return new BigInteger(hex).toString(16);
  255. }
  256. public static class GameServerInfo
  257. {
  258. // auth
  259. private int _id;
  260. private byte[] _hexId;
  261. private boolean _isAuthed;
  262. // status
  263. private GameServerThread _gst;
  264. private int _status;
  265. // network
  266. private ArrayList<GameServerAddress> _addrs = new ArrayList<GameServerAddress>(5);
  267. private int _port;
  268. // config
  269. private boolean _isPvp = true;
  270. private int _serverType;
  271. private int _ageLimit;
  272. private boolean _isShowingBrackets;
  273. private int _maxPlayers;
  274. public GameServerInfo(int id, byte[] hexId, GameServerThread gst)
  275. {
  276. _id = id;
  277. _hexId = hexId;
  278. _gst = gst;
  279. _status = ServerStatus.STATUS_DOWN;
  280. }
  281. public GameServerInfo(int id, byte[] hexId)
  282. {
  283. this(id, hexId, null);
  284. }
  285. public void setId(int id)
  286. {
  287. _id = id;
  288. }
  289. public int getId()
  290. {
  291. return _id;
  292. }
  293. public byte[] getHexId()
  294. {
  295. return _hexId;
  296. }
  297. public void setAuthed(boolean isAuthed)
  298. {
  299. _isAuthed = isAuthed;
  300. }
  301. public boolean isAuthed()
  302. {
  303. return _isAuthed;
  304. }
  305. public void setGameServerThread(GameServerThread gst)
  306. {
  307. _gst = gst;
  308. }
  309. public GameServerThread getGameServerThread()
  310. {
  311. return _gst;
  312. }
  313. public void setStatus(int status)
  314. {
  315. _status = status;
  316. }
  317. public int getStatus()
  318. {
  319. return _status;
  320. }
  321. public int getCurrentPlayerCount()
  322. {
  323. if (_gst == null)
  324. return 0;
  325. return _gst.getPlayerCount();
  326. }
  327. public String getExternalHost()
  328. {
  329. try
  330. {
  331. return getServerAddress(InetAddress.getByName("0.0.0.0"));
  332. }
  333. catch (Exception e)
  334. {
  335. }
  336. return null;
  337. }
  338. public int getPort()
  339. {
  340. return _port;
  341. }
  342. public void setPort(int port)
  343. {
  344. _port = port;
  345. }
  346. public void setMaxPlayers(int maxPlayers)
  347. {
  348. _maxPlayers = maxPlayers;
  349. }
  350. public int getMaxPlayers()
  351. {
  352. return _maxPlayers;
  353. }
  354. public boolean isPvp()
  355. {
  356. return _isPvp;
  357. }
  358. public void setAgeLimit(int val)
  359. {
  360. _ageLimit = val;
  361. }
  362. public int getAgeLimit()
  363. {
  364. return _ageLimit;
  365. }
  366. public void setServerType(int val)
  367. {
  368. _serverType = val;
  369. }
  370. public int getServerType()
  371. {
  372. return _serverType;
  373. }
  374. public void setShowingBrackets(boolean val)
  375. {
  376. _isShowingBrackets = val;
  377. }
  378. public boolean isShowingBrackets()
  379. {
  380. return _isShowingBrackets;
  381. }
  382. public void setDown()
  383. {
  384. setAuthed(false);
  385. setPort(0);
  386. setGameServerThread(null);
  387. setStatus(ServerStatus.STATUS_DOWN);
  388. }
  389. public void addServerAddress(String subnet, String addr) throws UnknownHostException
  390. {
  391. _addrs.add(new GameServerAddress(subnet, addr));
  392. }
  393. public String getServerAddress(InetAddress addr)
  394. {
  395. for (GameServerAddress a : _addrs)
  396. {
  397. if (a.equals(addr))
  398. return a.getServerAddress();
  399. }
  400. return null; // should not happens
  401. }
  402. public String[] getServerAddresses()
  403. {
  404. String[] result = new String[_addrs.size()];
  405. for (int i = 0; i < result.length; i++)
  406. result[i] = _addrs.get(i).toString();
  407. return result;
  408. }
  409. public void clearServerAddresses()
  410. {
  411. _addrs.clear();
  412. }
  413. private class GameServerAddress extends IPSubnet
  414. {
  415. private String _serverAddress;
  416. public GameServerAddress(String subnet, String address) throws UnknownHostException
  417. {
  418. super(subnet);
  419. _serverAddress = address;
  420. }
  421. public String getServerAddress()
  422. {
  423. return _serverAddress;
  424. }
  425. @Override
  426. public String toString()
  427. {
  428. return _serverAddress + super.toString();
  429. }
  430. }
  431. }
  432. }