LoginServerThread.java 17 KB

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