GameServerTable.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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 = L2DatabaseFactory.getInstance().getConnection();
  145. PreparedStatement statement = con.prepareStatement("SELECT * FROM gameservers");
  146. ResultSet rset = statement.executeQuery();
  147. int id;
  148. while (rset.next())
  149. {
  150. id = rset.getInt("server_id");
  151. _gameServerTable.put(id, new GameServerInfo(id, stringToHex(rset.getString("hexid"))));
  152. }
  153. rset.close();
  154. statement.close();
  155. L2DatabaseFactory.close(con);
  156. }
  157. public Map<Integer, GameServerInfo> getRegisteredGameServers()
  158. {
  159. return _gameServerTable;
  160. }
  161. public GameServerInfo getRegisteredGameServerById(int id)
  162. {
  163. return _gameServerTable.get(id);
  164. }
  165. public boolean hasRegisteredGameServerOnId(int id)
  166. {
  167. return _gameServerTable.containsKey(id);
  168. }
  169. public boolean registerWithFirstAvaliableId(GameServerInfo gsi)
  170. {
  171. // avoid two servers registering with the same "free" id
  172. synchronized (_gameServerTable)
  173. {
  174. for (Entry<Integer, String> entry : _serverNames.entrySet())
  175. {
  176. if (!_gameServerTable.containsKey(entry.getKey()))
  177. {
  178. _gameServerTable.put(entry.getKey(), gsi);
  179. gsi.setId(entry.getKey());
  180. return true;
  181. }
  182. }
  183. }
  184. return false;
  185. }
  186. public boolean register(int id, GameServerInfo gsi)
  187. {
  188. // avoid two servers registering with the same id
  189. synchronized (_gameServerTable)
  190. {
  191. if (!_gameServerTable.containsKey(id))
  192. {
  193. _gameServerTable.put(id, gsi);
  194. gsi.setId(id);
  195. return true;
  196. }
  197. }
  198. return false;
  199. }
  200. public void registerServerOnDB(GameServerInfo gsi)
  201. {
  202. this.registerServerOnDB(gsi.getHexId(), gsi.getId(), gsi.getExternalHost());
  203. }
  204. public void registerServerOnDB(byte[] hexId, int id, String externalHost)
  205. {
  206. Connection con = null;
  207. try
  208. {
  209. con = L2DatabaseFactory.getInstance().getConnection();
  210. PreparedStatement statement = con.prepareStatement("INSERT INTO gameservers (hexid,server_id,host) values (?,?,?)");
  211. statement.setString(1, hexToString(hexId));
  212. statement.setInt(2, id);
  213. statement.setString(3, externalHost);
  214. statement.executeUpdate();
  215. statement.close();
  216. this.register(id, new GameServerInfo(id, hexId));
  217. }
  218. catch (SQLException e)
  219. {
  220. _log.log(Level.SEVERE, "SQL error while saving gameserver.", e);
  221. }
  222. finally
  223. {
  224. L2DatabaseFactory.close(con);
  225. }
  226. }
  227. public String getServerNameById(int id)
  228. {
  229. return getServerNames().get(id);
  230. }
  231. public Map<Integer, String> getServerNames()
  232. {
  233. return _serverNames;
  234. }
  235. public KeyPair getKeyPair()
  236. {
  237. return _keyPairs[Rnd.nextInt(10)];
  238. }
  239. private byte[] stringToHex(String string)
  240. {
  241. return new BigInteger(string, 16).toByteArray();
  242. }
  243. private String hexToString(byte[] hex)
  244. {
  245. if (hex == null)
  246. {
  247. return "null";
  248. }
  249. return new BigInteger(hex).toString(16);
  250. }
  251. public static class GameServerInfo
  252. {
  253. // auth
  254. private int _id;
  255. private byte[] _hexId;
  256. private boolean _isAuthed;
  257. // status
  258. private GameServerThread _gst;
  259. private int _status;
  260. // network
  261. private ArrayList<GameServerAddress> _addrs = new ArrayList<GameServerAddress>(5);
  262. private int _port;
  263. // config
  264. private boolean _isPvp = true;
  265. private int _serverType;
  266. private int _ageLimit;
  267. private boolean _isShowingBrackets;
  268. private int _maxPlayers;
  269. public GameServerInfo(int id, byte[] hexId, GameServerThread gst)
  270. {
  271. _id = id;
  272. _hexId = hexId;
  273. _gst = gst;
  274. _status = ServerStatus.STATUS_DOWN;
  275. }
  276. public GameServerInfo(int id, byte[] hexId)
  277. {
  278. this(id, hexId, null);
  279. }
  280. public void setId(int id)
  281. {
  282. _id = id;
  283. }
  284. public int getId()
  285. {
  286. return _id;
  287. }
  288. public byte[] getHexId()
  289. {
  290. return _hexId;
  291. }
  292. public void setAuthed(boolean isAuthed)
  293. {
  294. _isAuthed = isAuthed;
  295. }
  296. public boolean isAuthed()
  297. {
  298. return _isAuthed;
  299. }
  300. public void setGameServerThread(GameServerThread gst)
  301. {
  302. _gst = gst;
  303. }
  304. public GameServerThread getGameServerThread()
  305. {
  306. return _gst;
  307. }
  308. public void setStatus(int status)
  309. {
  310. _status = status;
  311. }
  312. public int getStatus()
  313. {
  314. return _status;
  315. }
  316. public int getCurrentPlayerCount()
  317. {
  318. if (_gst == null)
  319. return 0;
  320. return _gst.getPlayerCount();
  321. }
  322. public String getExternalHost()
  323. {
  324. try
  325. {
  326. return getServerAddress(InetAddress.getByName("0.0.0.0"));
  327. }
  328. catch (Exception e)
  329. {
  330. }
  331. return null;
  332. }
  333. public int getPort()
  334. {
  335. return _port;
  336. }
  337. public void setPort(int port)
  338. {
  339. _port = port;
  340. }
  341. public void setMaxPlayers(int maxPlayers)
  342. {
  343. _maxPlayers = maxPlayers;
  344. }
  345. public int getMaxPlayers()
  346. {
  347. return _maxPlayers;
  348. }
  349. public boolean isPvp()
  350. {
  351. return _isPvp;
  352. }
  353. public void setAgeLimit(int val)
  354. {
  355. _ageLimit = val;
  356. }
  357. public int getAgeLimit()
  358. {
  359. return _ageLimit;
  360. }
  361. public void setServerType(int val)
  362. {
  363. _serverType = val;
  364. }
  365. public int getServerType()
  366. {
  367. return _serverType;
  368. }
  369. public void setShowingBrackets(boolean val)
  370. {
  371. _isShowingBrackets = val;
  372. }
  373. public boolean isShowingBrackets()
  374. {
  375. return _isShowingBrackets;
  376. }
  377. public void setDown()
  378. {
  379. setAuthed(false);
  380. setPort(0);
  381. setGameServerThread(null);
  382. setStatus(ServerStatus.STATUS_DOWN);
  383. }
  384. public void addServerAddress(String subnet, String addr) throws UnknownHostException
  385. {
  386. _addrs.add(new GameServerAddress(subnet, addr));
  387. }
  388. public String getServerAddress(InetAddress addr)
  389. {
  390. for (GameServerAddress a : _addrs)
  391. {
  392. if (a.equals(addr))
  393. return a.getServerAddress();
  394. }
  395. return null; // should not happens
  396. }
  397. public String[] getServerAddresses()
  398. {
  399. String[] result = new String[_addrs.size()];
  400. for (int i = 0; i < result.length; i++)
  401. result[i] = _addrs.get(i).toString();
  402. return result;
  403. }
  404. public void clearServerAddresses()
  405. {
  406. _addrs.clear();
  407. }
  408. private class GameServerAddress extends IPSubnet
  409. {
  410. private String _serverAddress;
  411. public GameServerAddress(String subnet, String address) throws UnknownHostException
  412. {
  413. super(subnet);
  414. _serverAddress = address;
  415. }
  416. public String getServerAddress()
  417. {
  418. return _serverAddress;
  419. }
  420. @Override
  421. public String toString()
  422. {
  423. return _serverAddress + super.toString();
  424. }
  425. }
  426. }
  427. }