LoginServerThread.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /*
  2. * This program is free software; you can redistribute it and/or modify
  3. * it under the terms of the GNU General Public License as published by
  4. * the Free Software Foundation; either version 2, or (at your option)
  5. * any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program; if not, write to the Free Software
  14. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
  15. * 02111-1307, USA.
  16. *
  17. * http://www.gnu.org/copyleft/gpl.html
  18. */
  19. package net.sf.l2j.gameserver;
  20. import java.io.BufferedOutputStream;
  21. import java.io.IOException;
  22. import java.io.InputStream;
  23. import java.io.OutputStream;
  24. import java.math.BigInteger;
  25. import java.net.Socket;
  26. import java.net.UnknownHostException;
  27. import java.security.GeneralSecurityException;
  28. import java.security.KeyFactory;
  29. import java.security.interfaces.RSAPublicKey;
  30. import java.security.spec.RSAKeyGenParameterSpec;
  31. import java.security.spec.RSAPublicKeySpec;
  32. import java.util.List;
  33. import java.util.Map;
  34. import java.util.logging.Logger;
  35. import javolution.util.FastList;
  36. import javolution.util.FastMap;
  37. import net.sf.l2j.Config;
  38. import net.sf.l2j.gameserver.gameserverpackets.AuthRequest;
  39. import net.sf.l2j.gameserver.gameserverpackets.BlowFishKey;
  40. import net.sf.l2j.gameserver.gameserverpackets.ChangeAccessLevel;
  41. import net.sf.l2j.gameserver.gameserverpackets.GameServerBasePacket;
  42. import net.sf.l2j.gameserver.gameserverpackets.PlayerAuthRequest;
  43. import net.sf.l2j.gameserver.gameserverpackets.PlayerInGame;
  44. import net.sf.l2j.gameserver.gameserverpackets.PlayerLogout;
  45. import net.sf.l2j.gameserver.gameserverpackets.ServerStatus;
  46. import net.sf.l2j.gameserver.loginserverpackets.AuthResponse;
  47. import net.sf.l2j.gameserver.loginserverpackets.InitLS;
  48. import net.sf.l2j.gameserver.loginserverpackets.KickPlayer;
  49. import net.sf.l2j.gameserver.loginserverpackets.LoginServerFail;
  50. import net.sf.l2j.gameserver.loginserverpackets.PlayerAuthResponse;
  51. import net.sf.l2j.gameserver.model.L2World;
  52. import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
  53. import net.sf.l2j.gameserver.network.L2GameClient;
  54. import net.sf.l2j.gameserver.network.L2GameClient.GameClientState;
  55. import net.sf.l2j.gameserver.serverpackets.LoginFail;
  56. import net.sf.l2j.gameserver.serverpackets.CharSelectionInfo;
  57. import net.sf.l2j.loginserver.crypt.NewCrypt;
  58. import net.sf.l2j.util.Rnd;
  59. import net.sf.l2j.util.Util;
  60. public class LoginServerThread extends Thread
  61. {
  62. protected static final Logger _log = Logger.getLogger(LoginServerThread.class.getName());
  63. /** The LoginServerThread singleton */
  64. private static LoginServerThread _instance;
  65. /** {@see net.sf.l2j.loginserver.LoginServer#PROTOCOL_REV } */
  66. private static final int REVISION = 0x0102;
  67. private RSAPublicKey _publicKey;
  68. private String _hostname;
  69. private int _port;
  70. private int _gamePort;
  71. private Socket _loginSocket;
  72. private InputStream _in;
  73. private OutputStream _out;
  74. /**
  75. * The BlowFish engine used to encrypt packets<br>
  76. * It is first initialized with a unified key:<br>
  77. * "_;v.]05-31!|+-%xT!^[$\00"<br>
  78. * <br>
  79. * and then after handshake, with a new key sent by<br>
  80. * loginserver during the handshake. This new key is stored<br>
  81. * in {@link #_blowfishKey}
  82. */
  83. private NewCrypt _blowfish;
  84. private byte[] _blowfishKey;
  85. private byte[] _hexID;
  86. private boolean _acceptAlternate;
  87. private int _requestID;
  88. private int _serverID;
  89. private boolean _reserveHost;
  90. private int _maxPlayer;
  91. private List<WaitingClient> _waitingClients;
  92. private Map<String, L2GameClient> _accountsInGameServer;
  93. private int _status;
  94. private String _serverName;
  95. private String _gameExternalHost;
  96. private String _gameInternalHost;
  97. public LoginServerThread()
  98. {
  99. super("LoginServerThread");
  100. _port = Config.GAME_SERVER_LOGIN_PORT;
  101. _gamePort = Config.PORT_GAME;
  102. _hostname = Config.GAME_SERVER_LOGIN_HOST;
  103. _hexID = Config.HEX_ID;
  104. if(_hexID == null)
  105. {
  106. _requestID = Config.REQUEST_ID;
  107. _hexID = generateHex(16);
  108. }
  109. else
  110. {
  111. _requestID = Config.SERVER_ID;
  112. }
  113. _acceptAlternate = Config.ACCEPT_ALTERNATE_ID;
  114. _reserveHost = Config.RESERVE_HOST_ON_LOGIN;
  115. _gameExternalHost = Config.EXTERNAL_HOSTNAME;
  116. _gameInternalHost = Config.INTERNAL_HOSTNAME;
  117. _waitingClients = new FastList<WaitingClient>();
  118. _accountsInGameServer = new FastMap<String, L2GameClient>().setShared(true);
  119. _maxPlayer = Config.MAXIMUM_ONLINE_USERS;
  120. }
  121. public static LoginServerThread getInstance()
  122. {
  123. if(_instance == null)
  124. {
  125. _instance = new LoginServerThread();
  126. }
  127. return _instance;
  128. }
  129. @Override
  130. public void run()
  131. {
  132. while(true)
  133. {
  134. int lengthHi =0;
  135. int lengthLo =0;
  136. int length = 0;
  137. boolean checksumOk = false;
  138. try
  139. {
  140. // Connection
  141. _log.info("Connecting to login on "+_hostname+":"+_port);
  142. _loginSocket = new Socket(_hostname,_port);
  143. _in = _loginSocket.getInputStream();
  144. _out = new BufferedOutputStream(_loginSocket.getOutputStream());
  145. //init Blowfish
  146. _blowfishKey = generateHex(40);
  147. _blowfish = new NewCrypt("_;v.]05-31!|+-%xT!^[$\00");
  148. while (true)
  149. {
  150. lengthLo = _in.read();
  151. lengthHi = _in.read();
  152. length= lengthHi*256 + lengthLo;
  153. if (lengthHi < 0 )
  154. {
  155. _log.finer("LoginServerThread: Login terminated the connection.");
  156. break;
  157. }
  158. byte[] incoming = new byte[length];
  159. incoming[0] = (byte) lengthLo;
  160. incoming[1] = (byte) lengthHi;
  161. int receivedBytes = 0;
  162. int newBytes = 0;
  163. while (newBytes != -1 && receivedBytes<length-2)
  164. {
  165. newBytes = _in.read(incoming, 2, length-2);
  166. receivedBytes = receivedBytes + newBytes;
  167. }
  168. if (receivedBytes != length-2)
  169. {
  170. _log.warning("Incomplete Packet is sent to the server, closing connection.(LS)");
  171. break;
  172. }
  173. byte[] decrypt = new byte[length - 2];
  174. System.arraycopy(incoming, 2, decrypt, 0, decrypt.length);
  175. // decrypt if we have a key
  176. decrypt = _blowfish.decrypt(decrypt);
  177. checksumOk = NewCrypt.verifyChecksum(decrypt);
  178. if (!checksumOk)
  179. {
  180. _log.warning("Incorrect packet checksum, ignoring packet (LS)");
  181. break;
  182. }
  183. if (Config.DEBUG)
  184. _log.warning("[C]\n"+Util.printData(decrypt));
  185. int packetType = decrypt[0]&0xff;
  186. switch (packetType)
  187. {
  188. case 00:
  189. InitLS init = new InitLS(decrypt);
  190. if (Config.DEBUG) _log.info("Init received");
  191. if(init.getRevision() != REVISION)
  192. {
  193. //TODO: revision mismatch
  194. _log.warning("/!\\ Revision mismatch between LS and GS /!\\");
  195. break;
  196. }
  197. try
  198. {
  199. KeyFactory kfac = KeyFactory.getInstance("RSA");
  200. BigInteger modulus = new BigInteger(init.getRSAKey());
  201. RSAPublicKeySpec kspec1 = new RSAPublicKeySpec(modulus, RSAKeyGenParameterSpec.F4);
  202. _publicKey = (RSAPublicKey)kfac.generatePublic(kspec1);
  203. if (Config.DEBUG) _log.info("RSA key set up");
  204. }
  205. catch (GeneralSecurityException e)
  206. {
  207. _log.warning("Troubles while init the public key send by login");
  208. break;
  209. }
  210. //send the blowfish key through the rsa encryption
  211. BlowFishKey bfk = new BlowFishKey(_blowfishKey,_publicKey);
  212. sendPacket(bfk);
  213. if (Config.DEBUG)_log.info("Sent new blowfish key");
  214. //now, only accept paket with the new encryption
  215. _blowfish = new NewCrypt(_blowfishKey);
  216. if (Config.DEBUG)_log.info("Changed blowfish key");
  217. AuthRequest ar = new AuthRequest(_requestID, _acceptAlternate, _hexID, _gameExternalHost, _gameInternalHost, _gamePort, _reserveHost, _maxPlayer);
  218. sendPacket(ar);
  219. if (Config.DEBUG)_log.info("Sent AuthRequest to login");
  220. break;
  221. case 01:
  222. LoginServerFail lsf = new LoginServerFail(decrypt);
  223. _log.info("Damn! Registeration Failed: "+lsf.getReasonString());
  224. // login will close the connection here
  225. break;
  226. case 02:
  227. AuthResponse aresp = new AuthResponse(decrypt);
  228. _serverID = aresp.getServerId();
  229. _serverName = aresp.getServerName();
  230. Config.saveHexid(_serverID, hexToString(_hexID));
  231. _log.info("Registered on login as Server "+_serverID+" : "+_serverName);
  232. ServerStatus st = new ServerStatus();
  233. if(Config.SERVER_LIST_BRACKET)
  234. {
  235. st.addAttribute(ServerStatus.SERVER_LIST_SQUARE_BRACKET,ServerStatus.ON);
  236. }
  237. else
  238. {
  239. st.addAttribute(ServerStatus.SERVER_LIST_SQUARE_BRACKET,ServerStatus.OFF);
  240. }
  241. if(Config.SERVER_LIST_CLOCK)
  242. {
  243. st.addAttribute(ServerStatus.SERVER_LIST_CLOCK,ServerStatus.ON);
  244. }
  245. else
  246. {
  247. st.addAttribute(ServerStatus.SERVER_LIST_CLOCK,ServerStatus.OFF);
  248. }
  249. if(Config.SERVER_LIST_TESTSERVER)
  250. {
  251. st.addAttribute(ServerStatus.TEST_SERVER,ServerStatus.ON);
  252. }
  253. else
  254. {
  255. st.addAttribute(ServerStatus.TEST_SERVER,ServerStatus.OFF);
  256. }
  257. if(Config.SERVER_GMONLY)
  258. {
  259. st.addAttribute(ServerStatus.SERVER_LIST_STATUS,ServerStatus.STATUS_GM_ONLY);
  260. }
  261. else
  262. {
  263. st.addAttribute(ServerStatus.SERVER_LIST_STATUS,ServerStatus.STATUS_AUTO);
  264. }
  265. sendPacket(st);
  266. if(L2World.getInstance().getAllPlayersCount() > 0)
  267. {
  268. FastList<String> playerList = new FastList<String>();
  269. for(L2PcInstance player : L2World.getInstance().getAllPlayers())
  270. {
  271. playerList.add(player.getAccountName());
  272. }
  273. PlayerInGame pig = new PlayerInGame(playerList);
  274. sendPacket(pig);
  275. }
  276. break;
  277. case 03:
  278. PlayerAuthResponse par = new PlayerAuthResponse(decrypt);
  279. String account = par.getAccount();
  280. WaitingClient wcToRemove = null;
  281. synchronized(_waitingClients)
  282. {
  283. for(WaitingClient wc : _waitingClients)
  284. {
  285. if(wc.account.equals(account))
  286. {
  287. wcToRemove = wc;
  288. }
  289. }
  290. }
  291. if(wcToRemove != null)
  292. {
  293. if (par.isAuthed())
  294. {
  295. if (Config.DEBUG)_log.info("Login accepted player "+wcToRemove.account+" waited("+(GameTimeController.getGameTicks()-wcToRemove.timestamp)+"ms)");
  296. PlayerInGame pig = new PlayerInGame(par.getAccount());
  297. sendPacket(pig);
  298. wcToRemove.gameClient.setState(GameClientState.AUTHED);
  299. wcToRemove.gameClient.setSessionId(wcToRemove.session);
  300. CharSelectionInfo cl = new CharSelectionInfo(wcToRemove.account, wcToRemove.gameClient.getSessionId().playOkID1);
  301. wcToRemove.gameClient.getConnection().sendPacket(cl);
  302. wcToRemove.gameClient.setCharSelection(cl.getCharInfo());
  303. }
  304. else
  305. {
  306. _log.warning("session key is not correct. closing connection");
  307. wcToRemove.gameClient.getConnection().sendPacket(new LoginFail(1));
  308. wcToRemove.gameClient.closeNow();
  309. }
  310. _waitingClients.remove(wcToRemove);
  311. }
  312. break;
  313. case 04:
  314. KickPlayer kp = new KickPlayer(decrypt);
  315. doKickPlayer(kp.getAccount());
  316. break;
  317. }
  318. }
  319. }
  320. catch (UnknownHostException e)
  321. {
  322. if (Config.DEBUG) e.printStackTrace();
  323. }
  324. catch (IOException e)
  325. {
  326. _log.info("Deconnected from Login, Trying to reconnect:");
  327. _log.info(e.toString());
  328. }
  329. finally
  330. {
  331. try { _loginSocket.close(); } catch (Exception e) {}
  332. }
  333. try
  334. {
  335. Thread.sleep(5000); // 5 seconds tempo.
  336. }
  337. catch(InterruptedException e)
  338. {
  339. //
  340. }
  341. }
  342. }
  343. public void addWaitingClientAndSendRequest(String acc, L2GameClient client, SessionKey key)
  344. {
  345. if(Config.DEBUG) System.out.println(key);
  346. WaitingClient wc = new WaitingClient(acc, client, key);
  347. synchronized(_waitingClients)
  348. {
  349. _waitingClients.add(wc);
  350. }
  351. PlayerAuthRequest par = new PlayerAuthRequest(acc,key);
  352. try
  353. {
  354. sendPacket(par);
  355. }
  356. catch (IOException e)
  357. {
  358. _log.warning("Error while sending player auth request");
  359. if (Config.DEBUG) e.printStackTrace();
  360. }
  361. }
  362. public void removeWaitingClient(L2GameClient client)
  363. {
  364. WaitingClient toRemove = null;
  365. synchronized(_waitingClients)
  366. {
  367. for(WaitingClient c :_waitingClients)
  368. {
  369. if(c.gameClient == client)
  370. {
  371. toRemove = c;
  372. }
  373. }
  374. if(toRemove != null)
  375. _waitingClients.remove(toRemove);
  376. }
  377. }
  378. public void sendLogout(String account)
  379. {
  380. PlayerLogout pl = new PlayerLogout(account);
  381. try
  382. {
  383. sendPacket(pl);
  384. }
  385. catch (IOException e)
  386. {
  387. _log.warning("Error while sending logout packet to login");
  388. if (Config.DEBUG) e.printStackTrace();
  389. }
  390. }
  391. public void addGameServerLogin(String account, L2GameClient client)
  392. {
  393. _accountsInGameServer.put(account, client);
  394. }
  395. public void sendAccessLevel(String account, int level)
  396. {
  397. ChangeAccessLevel cal = new ChangeAccessLevel(account, level);
  398. try
  399. {
  400. sendPacket(cal);
  401. }
  402. catch (IOException e)
  403. {
  404. if (Config.DEBUG)
  405. e.printStackTrace();
  406. }
  407. }
  408. private String hexToString(byte[] hex)
  409. {
  410. return new BigInteger(hex).toString(16);
  411. }
  412. public void doKickPlayer(String account)
  413. {
  414. if(_accountsInGameServer.get(account) != null)
  415. {
  416. _accountsInGameServer.get(account).closeNow();
  417. LoginServerThread.getInstance().sendLogout(account);
  418. }
  419. }
  420. public static byte[] generateHex(int size)
  421. {
  422. byte [] array = new byte[size];
  423. Rnd.nextBytes(array);
  424. if (Config.DEBUG)_log.fine("Generated random String: \""+array+"\"");
  425. return array;
  426. }
  427. /**
  428. * @param sl
  429. * @throws IOException
  430. */
  431. private void sendPacket(GameServerBasePacket sl) throws IOException
  432. {
  433. byte[] data = sl.getContent();
  434. NewCrypt.appendChecksum(data);
  435. if (Config.DEBUG) _log.finest("[S]\n"+Util.printData(data));
  436. data = _blowfish.crypt(data);
  437. int len = data.length+2;
  438. synchronized (_out) //avoids tow threads writing in the mean time
  439. {
  440. _out.write(len & 0xff);
  441. _out.write(len >> 8 &0xff);
  442. _out.write(data);
  443. _out.flush();
  444. }
  445. }
  446. /**
  447. * @param maxPlayer The maxPlayer to set.
  448. */
  449. public void setMaxPlayer(int maxPlayer)
  450. {
  451. sendServerStatus(ServerStatus.MAX_PLAYERS,maxPlayer);
  452. _maxPlayer = maxPlayer;
  453. }
  454. /**
  455. * @return Returns the maxPlayer.
  456. */
  457. public int getMaxPlayer()
  458. {
  459. return _maxPlayer;
  460. }
  461. /**
  462. * @param server_gm_only
  463. */
  464. public void sendServerStatus(int id, int value)
  465. {
  466. ServerStatus ss = new ServerStatus();
  467. ss.addAttribute(id,value);
  468. try
  469. {
  470. sendPacket(ss);
  471. }
  472. catch (IOException e)
  473. {
  474. if (Config.DEBUG) e.printStackTrace();
  475. }
  476. }
  477. /**
  478. * @return
  479. */
  480. public String getStatusString()
  481. {
  482. return ServerStatus.STATUS_STRING[_status];
  483. }
  484. /**
  485. * @return
  486. */
  487. public boolean isClockShown()
  488. {
  489. return Config.SERVER_LIST_CLOCK;
  490. }
  491. /**
  492. * @return
  493. */
  494. public boolean isBracketShown()
  495. {
  496. return Config.SERVER_LIST_BRACKET;
  497. }
  498. /**
  499. * @return Returns the serverName.
  500. */
  501. public String getServerName()
  502. {
  503. return _serverName;
  504. }
  505. public void setServerStatus(int status)
  506. {
  507. switch(status)
  508. {
  509. case ServerStatus.STATUS_AUTO:
  510. sendServerStatus(ServerStatus.SERVER_LIST_STATUS,ServerStatus.STATUS_AUTO);
  511. _status = status;
  512. break;
  513. case ServerStatus.STATUS_DOWN:
  514. sendServerStatus(ServerStatus.SERVER_LIST_STATUS,ServerStatus.STATUS_DOWN);
  515. _status = status;
  516. break;
  517. case ServerStatus.STATUS_FULL:
  518. sendServerStatus(ServerStatus.SERVER_LIST_STATUS,ServerStatus.STATUS_FULL);
  519. _status = status;
  520. break;
  521. case ServerStatus.STATUS_GM_ONLY:
  522. sendServerStatus(ServerStatus.SERVER_LIST_STATUS,ServerStatus.STATUS_GM_ONLY);
  523. _status = status;
  524. break;
  525. case ServerStatus.STATUS_GOOD:
  526. sendServerStatus(ServerStatus.SERVER_LIST_STATUS,ServerStatus.STATUS_GOOD);
  527. _status = status;
  528. break;
  529. case ServerStatus.STATUS_NORMAL:
  530. sendServerStatus(ServerStatus.SERVER_LIST_STATUS,ServerStatus.STATUS_NORMAL);
  531. _status = status;
  532. break;
  533. default:
  534. throw new IllegalArgumentException("Status does not exists:"+status);
  535. }
  536. }
  537. public static class SessionKey
  538. {
  539. public int playOkID1;
  540. public int playOkID2;
  541. public int loginOkID1;
  542. public int loginOkID2;
  543. public SessionKey(int loginOK1, int loginOK2, int playOK1, int playOK2)
  544. {
  545. playOkID1 = playOK1;
  546. playOkID2 = playOK2;
  547. loginOkID1 = loginOK1;
  548. loginOkID2 = loginOK2;
  549. }
  550. @Override
  551. public String toString()
  552. {
  553. return "PlayOk: "+playOkID1+" "+playOkID2+" LoginOk:"+loginOkID1+" "+loginOkID2;
  554. }
  555. }
  556. private class WaitingClient
  557. {
  558. public int timestamp;
  559. public String account;
  560. public L2GameClient gameClient;
  561. public SessionKey session;
  562. public WaitingClient(String acc, L2GameClient client, SessionKey key)
  563. {
  564. account = acc;
  565. timestamp = GameTimeController.getGameTicks();
  566. gameClient = client;
  567. session = key;
  568. }
  569. }
  570. }