BaseGameServerRegister.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. /*
  2. * Copyright (C) 2004-2014 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.tools.gsregistering;
  20. import java.awt.HeadlessException;
  21. import java.io.File;
  22. import java.io.FileOutputStream;
  23. import java.io.IOException;
  24. import java.io.OutputStream;
  25. import java.math.BigInteger;
  26. import java.sql.Connection;
  27. import java.sql.PreparedStatement;
  28. import java.sql.SQLException;
  29. import java.sql.Statement;
  30. import java.util.Locale;
  31. import java.util.Map.Entry;
  32. import java.util.Properties;
  33. import java.util.ResourceBundle;
  34. import javax.swing.SwingUtilities;
  35. import javax.swing.UIManager;
  36. import com.l2jserver.Config;
  37. import com.l2jserver.L2DatabaseFactory;
  38. import com.l2jserver.Server;
  39. import com.l2jserver.loginserver.GameServerTable;
  40. import com.l2jserver.tools.i18n.LanguageControl;
  41. import com.l2jserver.util.Util;
  42. /**
  43. * The Class BaseGameServerRegister.
  44. * @author KenM
  45. */
  46. public abstract class BaseGameServerRegister
  47. {
  48. private boolean _loaded = false;
  49. private ResourceBundle _bundle;
  50. /**
  51. * The main method.
  52. * @param args the arguments
  53. */
  54. public static void main(String[] args)
  55. {
  56. Locale locale = null;
  57. boolean gui = true;
  58. boolean interactive = true;
  59. boolean force = false;
  60. boolean fallback = false;
  61. BaseTask task = null;
  62. ResourceBundle bundle = null;
  63. try
  64. {
  65. locale = Locale.getDefault();
  66. bundle = ResourceBundle.getBundle("gsregister.GSRegister", locale, LanguageControl.INSTANCE);
  67. }
  68. catch (Throwable t)
  69. {
  70. System.out.println("FATAL: Failed to load default translation.");
  71. System.exit(666);
  72. }
  73. String arg;
  74. for (int i = 0; i < args.length; i++)
  75. {
  76. arg = args[i];
  77. // --cmd : no gui
  78. if (arg.equals("-c") || arg.equals("--cmd"))
  79. {
  80. gui = false;
  81. }
  82. // --force : Forces GameServer register operations to overwrite a server if necessary
  83. else if (arg.equals("-f") || arg.equals("--force"))
  84. {
  85. force = true;
  86. }
  87. // --fallback : If an register operation fails due to ID already being in use it will then try to register first available ID
  88. else if (arg.equals("-b") || arg.equals("--fallback"))
  89. {
  90. fallback = true;
  91. }
  92. // --register <id> <hexid_dest_dir> : Register GameServer with ID <id> and output hexid on <hexid_dest_dir>
  93. // Fails if <id> already in use, unless -force is used (overwrites)
  94. else if (arg.equals("-r") || arg.equals("--register"))
  95. {
  96. gui = false;
  97. interactive = false;
  98. int id = Integer.parseInt(args[++i]);
  99. String dir = args[++i];
  100. task = new RegisterTask(id, dir, force, fallback);
  101. }
  102. // --unregister <id> : Removes GameServer denoted by <id>
  103. else if (arg.equals("-u") || arg.equals("--unregister"))
  104. {
  105. gui = false;
  106. interactive = false;
  107. String gsId = args[++i];
  108. if (gsId.equalsIgnoreCase("all"))
  109. {
  110. task = new UnregisterAllTask();
  111. }
  112. else
  113. {
  114. try
  115. {
  116. int id = Integer.parseInt(gsId);
  117. task = new UnregisterTask(id);
  118. }
  119. catch (NumberFormatException e)
  120. {
  121. if (bundle != null)
  122. {
  123. System.out.printf(bundle.getString("wrongUnregisterArg") + Config.EOL, gsId);
  124. }
  125. System.exit(1);
  126. }
  127. }
  128. }
  129. // --language <locale> : Sets the app to use the specified locale, overriding auto-detection
  130. else if (arg.equals("-l") || arg.equals("--language"))
  131. {
  132. String loc = args[++i];
  133. Locale[] availableLocales = Locale.getAvailableLocales();
  134. Locale l;
  135. for (int j = 0; (j < availableLocales.length) && (locale == null); j++)
  136. {
  137. l = availableLocales[j];
  138. if (l.toString().equals(loc))
  139. {
  140. locale = l;
  141. }
  142. }
  143. if (locale == null)
  144. {
  145. System.out.println("Specified locale '" + loc + "' was not found, using default behaviour.");
  146. }
  147. else
  148. {
  149. try
  150. {
  151. bundle = ResourceBundle.getBundle("gsregister.GSRegister", locale, LanguageControl.INSTANCE);
  152. }
  153. catch (Throwable t)
  154. {
  155. System.out.println("Failed to load translation ''");
  156. }
  157. }
  158. }
  159. // --help : Prints usage/arguments/credits
  160. else if (arg.equals("-h") || arg.equals("--help"))
  161. {
  162. gui = false;
  163. interactive = false;
  164. BaseGameServerRegister.printHelp(bundle);
  165. }
  166. }
  167. try
  168. {
  169. if (gui)
  170. {
  171. BaseGameServerRegister.startGUI(bundle);
  172. }
  173. else
  174. {
  175. if (interactive)
  176. {
  177. BaseGameServerRegister.startCMD(bundle);
  178. }
  179. else
  180. {
  181. // if there is a task, do it, else the app has already finished
  182. if (task != null)
  183. {
  184. task.setBundle(bundle);
  185. task.run();
  186. }
  187. }
  188. }
  189. }
  190. catch (HeadlessException e)
  191. {
  192. BaseGameServerRegister.startCMD(bundle);
  193. }
  194. }
  195. /**
  196. * Prints the help.
  197. * @param bundle the bundle
  198. */
  199. private static void printHelp(ResourceBundle bundle)
  200. {
  201. String[] help =
  202. {
  203. bundle.getString("purpose"),
  204. "",
  205. bundle.getString("options"),
  206. "-b, --fallback\t\t\t\t" + bundle.getString("fallbackOpt"),
  207. "-c, --cmd\t\t\t\t" + bundle.getString("cmdOpt"),
  208. "-f, --force\t\t\t\t" + bundle.getString("forceOpt"),
  209. "-h, --help\t\t\t\t" + bundle.getString("helpOpt"),
  210. "-l, --language\t\t\t\t" + bundle.getString("languageOpt"),
  211. "-r, --register <id> <hexid_dest_dir>\t" + bundle.getString("registerOpt1"),
  212. "\t\t\t\t\t" + bundle.getString("registerOpt2"),
  213. "\t\t\t\t\t" + bundle.getString("registerOpt3"),
  214. "",
  215. "-u, --unregister <id>|all\t\t" + bundle.getString("unregisterOpt"),
  216. "",
  217. bundle.getString("credits"),
  218. bundle.getString("bugReports") + " http://www.l2jserver.com"
  219. /*
  220. * "-b, --fallback\t\t\t\tIf an register operation fails due to ID already being in use it will then try to register first available ID", "-c, --cmd\t\t\t\tForces application to run in command-line mode even if the GUI is supported.",
  221. * "-f, --force\t\t\t\tForces GameServer register operations to overwrite a server if necessary", "-h, --help\t\t\t\tPrints this help message", "-l, --language <locale>\t\t\t\tAsks the application to use the specified locale, overriding auto-detection",
  222. * "-r, --register <id> <hexid_dest_dir>\tRegister GameServer with ID <id> and output hexid on <hexid_dest_dir>", "\t\t\t\t\tUse a negative value on <id> to register the first available ID", "\t\t\t\t\tFails if <id> already in use, unless --force is used (overwrites)", "",
  223. * "-u, --unregister <id>|all\t\tRemoves GameServer denoted by <id>, use \"all\" for removing all registered GameServers", "", "Copyright (C) L2J Team 2008-2012.", "Report bugs: http://www.l2jserver.com"
  224. */
  225. };
  226. for (String str : help)
  227. {
  228. System.out.println(str);
  229. }
  230. }
  231. /**
  232. * Start the GUI.
  233. * @param bundle the bundle.
  234. */
  235. private static void startGUI(final ResourceBundle bundle)
  236. {
  237. try
  238. {
  239. // avoid that ugly Metal LaF
  240. UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  241. }
  242. catch (Exception e)
  243. {
  244. // couldn't care less
  245. }
  246. SwingUtilities.invokeLater(() ->
  247. {
  248. GUserInterface gui = new GUserInterface(bundle);
  249. gui.getFrame().setVisible(true);
  250. });
  251. }
  252. /**
  253. * Start the CMD.
  254. * @param bundle the bundle.
  255. */
  256. private static void startCMD(final ResourceBundle bundle)
  257. {
  258. GameServerRegister cmdUi = new GameServerRegister(bundle);
  259. try
  260. {
  261. cmdUi.consoleUI();
  262. }
  263. catch (IOException e)
  264. {
  265. cmdUi.showError("I/O exception trying to get input from keyboard.", e);
  266. }
  267. }
  268. /**
  269. * Instantiates a new base game server register.
  270. * @param bundle the bundle.
  271. */
  272. public BaseGameServerRegister(ResourceBundle bundle)
  273. {
  274. setBundle(bundle);
  275. }
  276. /**
  277. * Load.
  278. */
  279. public void load()
  280. {
  281. Server.serverMode = Server.MODE_LOGINSERVER;
  282. Config.load();
  283. GameServerTable.getInstance();
  284. _loaded = true;
  285. }
  286. /**
  287. * Checks if is loaded.
  288. * @return true, if is loaded
  289. */
  290. public boolean isLoaded()
  291. {
  292. return _loaded;
  293. }
  294. /**
  295. * Sets the bundle.
  296. * @param bundle the bundle to set.
  297. */
  298. public void setBundle(ResourceBundle bundle)
  299. {
  300. _bundle = bundle;
  301. }
  302. /**
  303. * Gets the bundle.
  304. * @return the bundle.
  305. */
  306. public ResourceBundle getBundle()
  307. {
  308. return _bundle;
  309. }
  310. /**
  311. * Show the error.
  312. * @param msg the msg.
  313. * @param t the t.
  314. */
  315. public abstract void showError(String msg, Throwable t);
  316. /**
  317. * Unregister the game server.
  318. * @param id the game server id.
  319. * @throws SQLException the SQL exception.
  320. */
  321. public static void unregisterGameServer(int id) throws SQLException
  322. {
  323. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  324. PreparedStatement ps = con.prepareStatement("DELETE FROM gameservers WHERE server_id = ?"))
  325. {
  326. ps.setInt(1, id);
  327. ps.executeUpdate();
  328. }
  329. GameServerTable.getInstance().getRegisteredGameServers().remove(id);
  330. }
  331. /**
  332. * Unregister all game servers.
  333. * @throws SQLException the SQL exception
  334. */
  335. public static void unregisterAllGameServers() throws SQLException
  336. {
  337. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  338. Statement s = con.createStatement())
  339. {
  340. s.executeUpdate("DELETE FROM gameservers");
  341. }
  342. GameServerTable.getInstance().getRegisteredGameServers().clear();
  343. }
  344. /**
  345. * Register a game server.
  346. * @param id the id of the game server.
  347. * @param outDir the out dir.
  348. * @throws IOException Signals that an I/O exception has occurred.
  349. */
  350. public static void registerGameServer(int id, String outDir) throws IOException
  351. {
  352. byte[] hexId = Util.generateHex(16);
  353. GameServerTable.getInstance().registerServerOnDB(hexId, id, "");
  354. Properties hexSetting = new Properties();
  355. File file = new File(outDir, "hexid.txt");
  356. // Create a new empty file only if it doesn't exist
  357. file.createNewFile();
  358. try (OutputStream out = new FileOutputStream(file))
  359. {
  360. hexSetting.setProperty("ServerID", String.valueOf(id));
  361. hexSetting.setProperty("HexID", new BigInteger(hexId).toString(16));
  362. hexSetting.store(out, "The HexId to Auth into LoginServer");
  363. }
  364. }
  365. /**
  366. * Register first available.
  367. * @param outDir the out dir
  368. * @return the int
  369. * @throws IOException Signals that an I/O exception has occurred.
  370. */
  371. public static int registerFirstAvailable(String outDir) throws IOException
  372. {
  373. for (Entry<Integer, String> e : GameServerTable.getInstance().getServerNames().entrySet())
  374. {
  375. if (!GameServerTable.getInstance().hasRegisteredGameServerOnId(e.getKey()))
  376. {
  377. BaseGameServerRegister.registerGameServer(e.getKey(), outDir);
  378. return e.getKey();
  379. }
  380. }
  381. return -1;
  382. }
  383. /**
  384. * The Class BaseTask.
  385. */
  386. protected static abstract class BaseTask implements Runnable
  387. {
  388. private ResourceBundle _bundle;
  389. /**
  390. * Sets the bundle.
  391. * @param bundle The bundle to set.
  392. */
  393. public void setBundle(ResourceBundle bundle)
  394. {
  395. _bundle = bundle;
  396. }
  397. /**
  398. * Gets the bundle.
  399. * @return Returns the bundle.
  400. */
  401. public ResourceBundle getBundle()
  402. {
  403. return _bundle;
  404. }
  405. /**
  406. * Show the error.
  407. * @param msg the msg
  408. * @param t the t
  409. */
  410. public void showError(String msg, Throwable t)
  411. {
  412. String title;
  413. if (getBundle() != null)
  414. {
  415. title = getBundle().getString("error");
  416. msg += Config.EOL + getBundle().getString("reason") + ' ' + t.getLocalizedMessage();
  417. }
  418. else
  419. {
  420. title = "Error";
  421. msg += Config.EOL + "Cause: " + t.getLocalizedMessage();
  422. }
  423. System.out.println(title + ": " + msg);
  424. }
  425. }
  426. /**
  427. * The Class RegisterTask.
  428. */
  429. private static class RegisterTask extends BaseTask
  430. {
  431. private final int _id;
  432. private final String _outDir;
  433. private boolean _force;
  434. private boolean _fallback;
  435. /**
  436. * Instantiates a new register task.
  437. * @param id the id.
  438. * @param outDir the out dir.
  439. * @param force the force.
  440. * @param fallback the fallback.
  441. */
  442. public RegisterTask(int id, String outDir, boolean force, boolean fallback)
  443. {
  444. _id = id;
  445. _outDir = outDir;
  446. _force = force;
  447. _fallback = fallback;
  448. }
  449. /**
  450. * Sets the actions.
  451. * @param force the force.
  452. * @param fallback the fallback.
  453. */
  454. @SuppressWarnings("unused")
  455. public void setActions(boolean force, boolean fallback)
  456. {
  457. _force = force;
  458. _fallback = fallback;
  459. }
  460. @Override
  461. public void run()
  462. {
  463. try
  464. {
  465. if (_id < 0)
  466. {
  467. int registeredId = BaseGameServerRegister.registerFirstAvailable(_outDir);
  468. if (registeredId < 0)
  469. {
  470. System.out.println(getBundle().getString("noFreeId"));
  471. }
  472. else
  473. {
  474. System.out.printf(getBundle().getString("registrationOk") + Config.EOL, registeredId);
  475. }
  476. }
  477. else
  478. {
  479. System.out.printf(getBundle().getString("checkingIdInUse") + Config.EOL, _id);
  480. if (GameServerTable.getInstance().hasRegisteredGameServerOnId(_id))
  481. {
  482. System.out.println(getBundle().getString("yes"));
  483. if (_force)
  484. {
  485. System.out.printf(getBundle().getString("forcingRegistration") + Config.EOL, _id);
  486. BaseGameServerRegister.unregisterGameServer(_id);
  487. BaseGameServerRegister.registerGameServer(_id, _outDir);
  488. System.out.printf(getBundle().getString("registrationOk") + Config.EOL, _id);
  489. }
  490. else if (_fallback)
  491. {
  492. System.out.println(getBundle().getString("fallingBack"));
  493. int registeredId = BaseGameServerRegister.registerFirstAvailable(_outDir);
  494. if (registeredId < 0)
  495. {
  496. System.out.println(getBundle().getString("noFreeId"));
  497. }
  498. else
  499. {
  500. System.out.printf(getBundle().getString("registrationOk") + Config.EOL, registeredId);
  501. }
  502. }
  503. else
  504. {
  505. System.out.println(getBundle().getString("noAction"));
  506. }
  507. }
  508. else
  509. {
  510. System.out.println(getBundle().getString("no"));
  511. BaseGameServerRegister.registerGameServer(_id, _outDir);
  512. }
  513. }
  514. }
  515. catch (SQLException e)
  516. {
  517. showError(getBundle().getString("sqlErrorRegister"), e);
  518. }
  519. catch (IOException e)
  520. {
  521. showError(getBundle().getString("ioErrorRegister"), e);
  522. }
  523. }
  524. }
  525. /**
  526. * The Class UnregisterTask.
  527. */
  528. private static class UnregisterTask extends BaseTask
  529. {
  530. private final int _id;
  531. /**
  532. * Instantiates a new unregister task.
  533. * @param id the task id.
  534. */
  535. public UnregisterTask(int id)
  536. {
  537. _id = id;
  538. }
  539. @Override
  540. public void run()
  541. {
  542. System.out.printf(getBundle().getString("removingGsId") + Config.EOL, _id);
  543. try
  544. {
  545. BaseGameServerRegister.unregisterGameServer(_id);
  546. }
  547. catch (SQLException e)
  548. {
  549. showError(getBundle().getString("sqlErrorRegister"), e);
  550. }
  551. }
  552. }
  553. /**
  554. * The Class UnregisterAllTask.
  555. */
  556. protected static class UnregisterAllTask extends BaseTask
  557. {
  558. @Override
  559. public void run()
  560. {
  561. try
  562. {
  563. BaseGameServerRegister.unregisterAllGameServers();
  564. }
  565. catch (SQLException e)
  566. {
  567. showError(getBundle().getString("sqlErrorUnregisterAll"), e);
  568. }
  569. }
  570. }
  571. }