2
0

GameServerTable.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. /*
  2. * Copyright (C) 2004-2015 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.loginserver;
  20. import java.math.BigInteger;
  21. import java.net.InetAddress;
  22. import java.net.UnknownHostException;
  23. import java.security.KeyPair;
  24. import java.security.KeyPairGenerator;
  25. import java.security.spec.RSAKeyGenParameterSpec;
  26. import java.sql.Connection;
  27. import java.sql.PreparedStatement;
  28. import java.sql.ResultSet;
  29. import java.sql.Statement;
  30. import java.util.ArrayList;
  31. import java.util.HashMap;
  32. import java.util.Map;
  33. import org.w3c.dom.Document;
  34. import org.w3c.dom.NodeList;
  35. import com.l2jserver.commons.database.pool.impl.ConnectionFactory;
  36. import com.l2jserver.loginserver.network.gameserverpackets.ServerStatus;
  37. import com.l2jserver.util.IPSubnet;
  38. import com.l2jserver.util.Rnd;
  39. import com.l2jserver.util.data.xml.IXmlReader;
  40. /**
  41. * The Class GameServerTable loads the game server names and initialize the game server tables.
  42. * @author KenM, Zoey76
  43. */
  44. public final class GameServerTable implements IXmlReader
  45. {
  46. // Server Names
  47. private static final Map<Integer, String> SERVER_NAMES = new HashMap<>();
  48. // Game Server Table
  49. private static final Map<Integer, GameServerInfo> GAME_SERVER_TABLE = new HashMap<>();
  50. // RSA Config
  51. private static final int KEYS_SIZE = 10;
  52. private KeyPair[] _keyPairs;
  53. /**
  54. * Instantiates a new game server table.
  55. */
  56. public GameServerTable()
  57. {
  58. load();
  59. loadRegisteredGameServers();
  60. LOGGER.info("{}: Loaded {} registered Game Servers.", getClass().getSimpleName(), GAME_SERVER_TABLE.size());
  61. initRSAKeys();
  62. LOGGER.info("{}: Cached {} RSA keys for Game Server communication.", getClass().getSimpleName(), _keyPairs.length);
  63. }
  64. @Override
  65. public void load()
  66. {
  67. SERVER_NAMES.clear();
  68. parseDatapackFile("data/servername.xml");
  69. LOGGER.info("{}: Loaded {} server names.", getClass().getSimpleName(), SERVER_NAMES.size());
  70. }
  71. @Override
  72. public void parseDocument(Document doc)
  73. {
  74. final NodeList servers = doc.getElementsByTagName("server");
  75. for (int s = 0; s < servers.getLength(); s++)
  76. {
  77. SERVER_NAMES.put(parseInteger(servers.item(s).getAttributes(), "id"), parseString(servers.item(s).getAttributes(), "name"));
  78. }
  79. }
  80. /**
  81. * Inits the RSA keys.
  82. */
  83. private void initRSAKeys()
  84. {
  85. try
  86. {
  87. final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
  88. keyGen.initialize(new RSAKeyGenParameterSpec(512, RSAKeyGenParameterSpec.F4));
  89. _keyPairs = new KeyPair[KEYS_SIZE];
  90. for (int i = 0; i < KEYS_SIZE; i++)
  91. {
  92. _keyPairs[i] = keyGen.genKeyPair();
  93. }
  94. }
  95. catch (Exception e)
  96. {
  97. LOGGER.error("{}: Error loading RSA keys for Game Server communication!", getClass().getSimpleName(), e);
  98. }
  99. }
  100. /**
  101. * Load registered game servers.
  102. */
  103. private void loadRegisteredGameServers()
  104. {
  105. try (Connection con = ConnectionFactory.getInstance().getConnection();
  106. Statement ps = con.createStatement();
  107. ResultSet rs = ps.executeQuery("SELECT * FROM gameservers"))
  108. {
  109. int id;
  110. while (rs.next())
  111. {
  112. id = rs.getInt("server_id");
  113. GAME_SERVER_TABLE.put(id, new GameServerInfo(id, stringToHex(rs.getString("hexid"))));
  114. }
  115. }
  116. catch (Exception e)
  117. {
  118. LOGGER.error("{}: Error loading registered game servers!", getClass().getSimpleName(), e);
  119. }
  120. }
  121. /**
  122. * Gets the registered game servers.
  123. * @return the registered game servers
  124. */
  125. public Map<Integer, GameServerInfo> getRegisteredGameServers()
  126. {
  127. return GAME_SERVER_TABLE;
  128. }
  129. /**
  130. * Gets the registered game server by id.
  131. * @param id the game server Id
  132. * @return the registered game server by id
  133. */
  134. public GameServerInfo getRegisteredGameServerById(int id)
  135. {
  136. return GAME_SERVER_TABLE.get(id);
  137. }
  138. /**
  139. * Checks for registered game server on id.
  140. * @param id the id
  141. * @return true, if successful
  142. */
  143. public boolean hasRegisteredGameServerOnId(int id)
  144. {
  145. return GAME_SERVER_TABLE.containsKey(id);
  146. }
  147. /**
  148. * Register with first available id.
  149. * @param gsi the game server information DTO
  150. * @return true, if successful
  151. */
  152. public boolean registerWithFirstAvailableId(GameServerInfo gsi)
  153. {
  154. // avoid two servers registering with the same "free" id
  155. synchronized (GAME_SERVER_TABLE)
  156. {
  157. for (Integer serverId : SERVER_NAMES.keySet())
  158. {
  159. if (!GAME_SERVER_TABLE.containsKey(serverId))
  160. {
  161. GAME_SERVER_TABLE.put(serverId, gsi);
  162. gsi.setId(serverId);
  163. return true;
  164. }
  165. }
  166. }
  167. return false;
  168. }
  169. /**
  170. * Register a game server.
  171. * @param id the id
  172. * @param gsi the gsi
  173. * @return true, if successful
  174. */
  175. public boolean register(int id, GameServerInfo gsi)
  176. {
  177. // avoid two servers registering with the same id
  178. synchronized (GAME_SERVER_TABLE)
  179. {
  180. if (!GAME_SERVER_TABLE.containsKey(id))
  181. {
  182. GAME_SERVER_TABLE.put(id, gsi);
  183. return true;
  184. }
  185. }
  186. return false;
  187. }
  188. /**
  189. * Wrapper method.
  190. * @param gsi the game server info DTO.
  191. */
  192. public void registerServerOnDB(GameServerInfo gsi)
  193. {
  194. registerServerOnDB(gsi.getHexId(), gsi.getId(), gsi.getExternalHost());
  195. }
  196. /**
  197. * Register server on db.
  198. * @param hexId the hex id
  199. * @param id the id
  200. * @param externalHost the external host
  201. */
  202. public void registerServerOnDB(byte[] hexId, int id, String externalHost)
  203. {
  204. register(id, new GameServerInfo(id, hexId));
  205. try (Connection con = ConnectionFactory.getInstance().getConnection();
  206. PreparedStatement ps = con.prepareStatement("INSERT INTO gameservers (hexid,server_id,host) values (?,?,?)"))
  207. {
  208. ps.setString(1, hexToString(hexId));
  209. ps.setInt(2, id);
  210. ps.setString(3, externalHost);
  211. ps.executeUpdate();
  212. }
  213. catch (Exception e)
  214. {
  215. LOGGER.error("{}: Error while saving gameserver!", getClass().getSimpleName(), e);
  216. }
  217. }
  218. /**
  219. * Gets the server name by id.
  220. * @param id the id
  221. * @return the server name by id
  222. */
  223. public String getServerNameById(int id)
  224. {
  225. return SERVER_NAMES.get(id);
  226. }
  227. /**
  228. * Gets the server names.
  229. * @return the game server names map.
  230. */
  231. public Map<Integer, String> getServerNames()
  232. {
  233. return SERVER_NAMES;
  234. }
  235. /**
  236. * Gets the key pair.
  237. * @return a random key pair.
  238. */
  239. public KeyPair getKeyPair()
  240. {
  241. return _keyPairs[Rnd.nextInt(10)];
  242. }
  243. /**
  244. * String to hex.
  245. * @param string the string to convert.
  246. * @return return the hex representation.
  247. */
  248. private byte[] stringToHex(String string)
  249. {
  250. return new BigInteger(string, 16).toByteArray();
  251. }
  252. /**
  253. * Hex to string.
  254. * @param hex the hex value to convert.
  255. * @return the string representation.
  256. */
  257. private String hexToString(byte[] hex)
  258. {
  259. if (hex == null)
  260. {
  261. return "null";
  262. }
  263. return new BigInteger(hex).toString(16);
  264. }
  265. /**
  266. * The Class GameServerInfo.
  267. */
  268. public static class GameServerInfo
  269. {
  270. // auth
  271. private int _id;
  272. private final byte[] _hexId;
  273. private boolean _isAuthed;
  274. // status
  275. private GameServerThread _gst;
  276. private int _status;
  277. // network
  278. private final ArrayList<GameServerAddress> _addrs = new ArrayList<>(5);
  279. private int _port;
  280. // config
  281. private final boolean _isPvp = true;
  282. private int _serverType;
  283. private int _ageLimit;
  284. private boolean _isShowingBrackets;
  285. private int _maxPlayers;
  286. /**
  287. * Instantiates a new game server info.
  288. * @param id the id
  289. * @param hexId the hex id
  290. * @param gst the gst
  291. */
  292. public GameServerInfo(int id, byte[] hexId, GameServerThread gst)
  293. {
  294. _id = id;
  295. _hexId = hexId;
  296. _gst = gst;
  297. _status = ServerStatus.STATUS_DOWN;
  298. }
  299. /**
  300. * Instantiates a new game server info.
  301. * @param id the id
  302. * @param hexId the hex id
  303. */
  304. public GameServerInfo(int id, byte[] hexId)
  305. {
  306. this(id, hexId, null);
  307. }
  308. /**
  309. * Sets the id.
  310. * @param id the new id
  311. */
  312. public void setId(int id)
  313. {
  314. _id = id;
  315. }
  316. /**
  317. * Gets the id.
  318. * @return the id
  319. */
  320. public int getId()
  321. {
  322. return _id;
  323. }
  324. /**
  325. * Gets the hex id.
  326. * @return the hex id
  327. */
  328. public byte[] getHexId()
  329. {
  330. return _hexId;
  331. }
  332. public String getName()
  333. {
  334. // this value can't be stored in a private variable because the ID can be changed by setId()
  335. return GameServerTable.getInstance().getServerNameById(_id);
  336. }
  337. /**
  338. * Sets the authed.
  339. * @param isAuthed the new authed
  340. */
  341. public void setAuthed(boolean isAuthed)
  342. {
  343. _isAuthed = isAuthed;
  344. }
  345. /**
  346. * Checks if is authed.
  347. * @return true, if is authed
  348. */
  349. public boolean isAuthed()
  350. {
  351. return _isAuthed;
  352. }
  353. /**
  354. * Sets the game server thread.
  355. * @param gst the new game server thread
  356. */
  357. public void setGameServerThread(GameServerThread gst)
  358. {
  359. _gst = gst;
  360. }
  361. /**
  362. * Gets the game server thread.
  363. * @return the game server thread
  364. */
  365. public GameServerThread getGameServerThread()
  366. {
  367. return _gst;
  368. }
  369. /**
  370. * Sets the status.
  371. * @param status the new status
  372. */
  373. public void setStatus(int status)
  374. {
  375. _status = status;
  376. }
  377. /**
  378. * Gets the status.
  379. * @return the status
  380. */
  381. public int getStatus()
  382. {
  383. return _status;
  384. }
  385. public String getStatusName()
  386. {
  387. switch (_status)
  388. {
  389. case 0:
  390. return "Auto";
  391. case 1:
  392. return "Good";
  393. case 2:
  394. return "Normal";
  395. case 3:
  396. return "Full";
  397. case 4:
  398. return "Down";
  399. case 5:
  400. return "GM Only";
  401. default:
  402. return "Unknown";
  403. }
  404. }
  405. /**
  406. * Gets the current player count.
  407. * @return the current player count
  408. */
  409. public int getCurrentPlayerCount()
  410. {
  411. if (_gst == null)
  412. {
  413. return 0;
  414. }
  415. return _gst.getPlayerCount();
  416. }
  417. /**
  418. * Gets the external host.
  419. * @return the external host
  420. */
  421. public String getExternalHost()
  422. {
  423. try
  424. {
  425. return getServerAddress(InetAddress.getByName("0.0.0.0"));
  426. }
  427. catch (Exception e)
  428. {
  429. }
  430. return null;
  431. }
  432. /**
  433. * Gets the port.
  434. * @return the port
  435. */
  436. public int getPort()
  437. {
  438. return _port;
  439. }
  440. /**
  441. * Sets the port.
  442. * @param port the new port
  443. */
  444. public void setPort(int port)
  445. {
  446. _port = port;
  447. }
  448. /**
  449. * Sets the max players.
  450. * @param maxPlayers the new max players
  451. */
  452. public void setMaxPlayers(int maxPlayers)
  453. {
  454. _maxPlayers = maxPlayers;
  455. }
  456. /**
  457. * Gets the max players.
  458. * @return the max players
  459. */
  460. public int getMaxPlayers()
  461. {
  462. return _maxPlayers;
  463. }
  464. /**
  465. * Checks if is pvp.
  466. * @return true, if is pvp
  467. */
  468. public boolean isPvp()
  469. {
  470. return _isPvp;
  471. }
  472. /**
  473. * Sets the age limit.
  474. * @param val the new age limit
  475. */
  476. public void setAgeLimit(int val)
  477. {
  478. _ageLimit = val;
  479. }
  480. /**
  481. * Gets the age limit.
  482. * @return the age limit
  483. */
  484. public int getAgeLimit()
  485. {
  486. return _ageLimit;
  487. }
  488. /**
  489. * Sets the server type.
  490. * @param val the new server type
  491. */
  492. public void setServerType(int val)
  493. {
  494. _serverType = val;
  495. }
  496. /**
  497. * Gets the server type.
  498. * @return the server type
  499. */
  500. public int getServerType()
  501. {
  502. return _serverType;
  503. }
  504. /**
  505. * Sets the showing brackets.
  506. * @param val the new showing brackets
  507. */
  508. public void setShowingBrackets(boolean val)
  509. {
  510. _isShowingBrackets = val;
  511. }
  512. /**
  513. * Checks if is showing brackets.
  514. * @return true, if is showing brackets
  515. */
  516. public boolean isShowingBrackets()
  517. {
  518. return _isShowingBrackets;
  519. }
  520. /**
  521. * Sets the down.
  522. */
  523. public void setDown()
  524. {
  525. setAuthed(false);
  526. setPort(0);
  527. setGameServerThread(null);
  528. setStatus(ServerStatus.STATUS_DOWN);
  529. }
  530. /**
  531. * Adds the server address.
  532. * @param subnet the subnet
  533. * @param addr the addr
  534. * @throws UnknownHostException the unknown host exception
  535. */
  536. public void addServerAddress(String subnet, String addr) throws UnknownHostException
  537. {
  538. _addrs.add(new GameServerAddress(subnet, addr));
  539. }
  540. /**
  541. * Gets the server address.
  542. * @param addr the addr
  543. * @return the server address
  544. */
  545. public String getServerAddress(InetAddress addr)
  546. {
  547. for (GameServerAddress a : _addrs)
  548. {
  549. if (a.equals(addr))
  550. {
  551. return a.getServerAddress();
  552. }
  553. }
  554. return null; // should not happens
  555. }
  556. /**
  557. * Gets the server addresses.
  558. * @return the server addresses
  559. */
  560. public String[] getServerAddresses()
  561. {
  562. String[] result = new String[_addrs.size()];
  563. for (int i = 0; i < result.length; i++)
  564. {
  565. result[i] = _addrs.get(i).toString();
  566. }
  567. return result;
  568. }
  569. /**
  570. * Clear server addresses.
  571. */
  572. public void clearServerAddresses()
  573. {
  574. _addrs.clear();
  575. }
  576. /**
  577. * The Class GameServerAddress.
  578. */
  579. private class GameServerAddress extends IPSubnet
  580. {
  581. private final String _serverAddress;
  582. /**
  583. * Instantiates a new game server address.
  584. * @param subnet the subnet
  585. * @param address the address
  586. * @throws UnknownHostException the unknown host exception
  587. */
  588. public GameServerAddress(String subnet, String address) throws UnknownHostException
  589. {
  590. super(subnet);
  591. _serverAddress = address;
  592. }
  593. /**
  594. * Gets the server address.
  595. * @return the server address
  596. */
  597. public String getServerAddress()
  598. {
  599. return _serverAddress;
  600. }
  601. @Override
  602. public String toString()
  603. {
  604. return _serverAddress + super.toString();
  605. }
  606. }
  607. }
  608. /**
  609. * Gets the single instance of GameServerTable.
  610. * @return single instance of GameServerTable
  611. */
  612. public static GameServerTable getInstance()
  613. {
  614. return SingletonHolder._instance;
  615. }
  616. /**
  617. * The Class SingletonHolder.
  618. */
  619. private static class SingletonHolder
  620. {
  621. protected static final GameServerTable _instance = new GameServerTable();
  622. }
  623. }