L2GameClient.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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.network;
  16. import java.net.InetAddress;
  17. import java.nio.ByteBuffer;
  18. import java.sql.PreparedStatement;
  19. import java.sql.ResultSet;
  20. import java.util.List;
  21. import java.util.concurrent.RejectedExecutionException;
  22. import java.util.concurrent.ScheduledFuture;
  23. import java.util.concurrent.locks.ReentrantLock;
  24. import java.util.logging.Level;
  25. import java.util.logging.Logger;
  26. import javolution.util.FastList;
  27. import net.sf.l2j.Config;
  28. import net.sf.l2j.L2DatabaseFactory;
  29. import net.sf.l2j.gameserver.LoginServerThread;
  30. import net.sf.l2j.gameserver.ThreadPoolManager;
  31. import net.sf.l2j.gameserver.LoginServerThread.SessionKey;
  32. import net.sf.l2j.gameserver.communitybbs.Manager.RegionBBSManager;
  33. import net.sf.l2j.gameserver.datatables.ClanTable;
  34. import net.sf.l2j.gameserver.datatables.SkillTable;
  35. import net.sf.l2j.gameserver.model.CharSelectInfoPackage;
  36. import net.sf.l2j.gameserver.model.L2Clan;
  37. import net.sf.l2j.gameserver.model.L2World;
  38. import net.sf.l2j.gameserver.model.actor.instance.L2PcInstance;
  39. import net.sf.l2j.gameserver.model.entity.L2Event;
  40. import net.sf.l2j.gameserver.network.serverpackets.L2GameServerPacket;
  41. import net.sf.l2j.util.EventData;
  42. import org.mmocore.network.MMOClient;
  43. import org.mmocore.network.MMOConnection;
  44. /**
  45. * Represents a client connected on Game Server
  46. * @author KenM
  47. */
  48. public final class L2GameClient extends MMOClient<MMOConnection<L2GameClient>>
  49. {
  50. protected static final Logger _log = Logger.getLogger(L2GameClient.class.getName());
  51. /**
  52. * CONNECTED - client has just connected
  53. * AUTHED - client has authed but doesnt has character attached to it yet
  54. * IN_GAME - client has selected a char and is in game
  55. * @author KenM
  56. */
  57. public static enum GameClientState { CONNECTED, AUTHED, IN_GAME }
  58. public GameClientState state;
  59. // Info
  60. private String _accountName;
  61. private SessionKey _sessionId;
  62. private L2PcInstance _activeChar;
  63. private ReentrantLock _activeCharLock = new ReentrantLock();
  64. private boolean _isAuthedGG;
  65. private long _connectionStartTime;
  66. private List<Integer> _charSlotMapping = new FastList<Integer>();
  67. // Task
  68. protected final ScheduledFuture<?> _autoSaveInDB;
  69. protected ScheduledFuture<?> _cleanupTask = null;
  70. // Crypt
  71. private GameCrypt _crypt;
  72. // Flood protection
  73. public byte packetsSentInSec = 0;
  74. public int packetsSentStartTick = 0;
  75. private boolean _isDetached = false;
  76. private boolean _protocol;
  77. public L2GameClient(MMOConnection<L2GameClient> con)
  78. {
  79. super(con);
  80. state = GameClientState.CONNECTED;
  81. _connectionStartTime = System.currentTimeMillis();
  82. _crypt = new GameCrypt();
  83. if (Config.CHAR_STORE_INTERVAL > 0)
  84. {
  85. _autoSaveInDB = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(
  86. new AutoSaveTask(), 300000L, (Config.CHAR_STORE_INTERVAL*60000L)
  87. );
  88. }
  89. else
  90. {
  91. _autoSaveInDB = null;
  92. }
  93. }
  94. public byte[] enableCrypt()
  95. {
  96. byte[] key = BlowFishKeygen.getRandomKey();
  97. _crypt.setKey(key);
  98. return key;
  99. }
  100. public GameClientState getState()
  101. {
  102. return state;
  103. }
  104. public void setState(GameClientState pState)
  105. {
  106. state = pState;
  107. }
  108. public long getConnectionStartTime()
  109. {
  110. return _connectionStartTime;
  111. }
  112. @Override
  113. public boolean decrypt(ByteBuffer buf, int size)
  114. {
  115. _crypt.decrypt(buf.array(), buf.position(), size);
  116. return true;
  117. }
  118. @Override
  119. public boolean encrypt(final ByteBuffer buf, final int size)
  120. {
  121. _crypt.encrypt(buf.array(), buf.position(), size);
  122. buf.position(buf.position() + size);
  123. return true;
  124. }
  125. public L2PcInstance getActiveChar()
  126. {
  127. return _activeChar;
  128. }
  129. public void setActiveChar(L2PcInstance pActiveChar)
  130. {
  131. _activeChar = pActiveChar;
  132. if (_activeChar != null)
  133. {
  134. L2World.getInstance().storeObject(getActiveChar());
  135. }
  136. }
  137. public ReentrantLock getActiveCharLock()
  138. {
  139. return _activeCharLock;
  140. }
  141. public void setGameGuardOk(boolean val)
  142. {
  143. _isAuthedGG = val;
  144. }
  145. public boolean isAuthedGG()
  146. {
  147. return _isAuthedGG;
  148. }
  149. public void setAccountName(String pAccountName)
  150. {
  151. _accountName = pAccountName;
  152. }
  153. public String getAccountName()
  154. {
  155. return _accountName;
  156. }
  157. public void setSessionId(SessionKey sk)
  158. {
  159. _sessionId = sk;
  160. }
  161. public SessionKey getSessionId()
  162. {
  163. return _sessionId;
  164. }
  165. public void sendPacket(L2GameServerPacket gsp)
  166. {
  167. if (_isDetached) return;
  168. getConnection().sendPacket(gsp);
  169. gsp.runImpl();
  170. }
  171. public boolean isDetached()
  172. {
  173. return _isDetached;
  174. }
  175. public void isDetached(boolean b)
  176. {
  177. _isDetached = b;
  178. }
  179. /**
  180. * Method to handle character deletion
  181. *
  182. * @return a byte:
  183. * <li>-1: Error: No char was found for such charslot, caught exception, etc...
  184. * <li> 0: character is not member of any clan, proceed with deletion
  185. * <li> 1: character is member of a clan, but not clan leader
  186. * <li> 2: character is clan leader
  187. */
  188. public byte markToDeleteChar(int charslot)
  189. {
  190. int objid = getObjectIdForSlot(charslot);
  191. if (objid < 0)
  192. return -1;
  193. java.sql.Connection con = null;
  194. try
  195. {
  196. con = L2DatabaseFactory.getInstance().getConnection();
  197. PreparedStatement statement = con.prepareStatement("SELECT clanId from characters WHERE charId=?");
  198. statement.setInt(1, objid);
  199. ResultSet rs = statement.executeQuery();
  200. rs.next();
  201. int clanId = rs.getInt(1);
  202. byte answer = 0;
  203. if (clanId != 0)
  204. {
  205. L2Clan clan = ClanTable.getInstance().getClan(clanId);
  206. if (clan == null)
  207. answer = 0; // jeezes!
  208. else if (clan.getLeaderId() == objid)
  209. answer = 2;
  210. else
  211. answer = 1;
  212. }
  213. // Setting delete time
  214. if (answer == 0)
  215. {
  216. if (Config.DELETE_DAYS == 0)
  217. deleteCharByObjId(objid);
  218. else
  219. {
  220. statement = con.prepareStatement("UPDATE characters SET deletetime=? WHERE charId=?");
  221. statement.setLong(1, System.currentTimeMillis() + Config.DELETE_DAYS*86400000L); // 24*60*60*1000 = 86400000
  222. statement.setInt(2, objid);
  223. statement.execute();
  224. statement.close();
  225. }
  226. }
  227. return answer;
  228. }
  229. catch (Exception e)
  230. {
  231. _log.log(Level.SEVERE, "Error updating delete time of character.", e);
  232. return -1;
  233. }
  234. finally
  235. {
  236. try { con.close(); } catch (Exception e) {}
  237. }
  238. }
  239. /**
  240. * Save the L2PcInstance to the database.
  241. */
  242. public static void saveCharToDisk(L2PcInstance cha)
  243. {
  244. try
  245. {
  246. cha.store();
  247. if (Config.UPDATE_ITEMS_ON_CHAR_STORE)
  248. {
  249. cha.getInventory().updateDatabase();
  250. }
  251. }
  252. catch(Exception e)
  253. {
  254. _log.log(Level.SEVERE, "Error saving character..", e);
  255. }
  256. }
  257. public void markRestoredChar(int charslot) throws Exception
  258. {
  259. //have to make sure active character must be nulled
  260. /*if (getActiveChar() != null)
  261. {
  262. saveCharToDisk (getActiveChar());
  263. if (Config.DEBUG) _log.fine("active Char saved");
  264. this.setActiveChar(null);
  265. }*/
  266. int objid = getObjectIdForSlot(charslot);
  267. if (objid < 0)
  268. return;
  269. java.sql.Connection con = null;
  270. try
  271. {
  272. con = L2DatabaseFactory.getInstance().getConnection();
  273. PreparedStatement statement = con.prepareStatement("UPDATE characters SET deletetime=0 WHERE charId=?");
  274. statement.setInt(1, objid);
  275. statement.execute();
  276. statement.close();
  277. }
  278. catch (Exception e)
  279. {
  280. _log.log(Level.SEVERE, "Error restoring character.", e);
  281. }
  282. finally
  283. {
  284. try { con.close(); } catch (Exception e) {}
  285. }
  286. }
  287. public static void deleteCharByObjId(int objid)
  288. {
  289. if (objid < 0)
  290. return;
  291. java.sql.Connection con = null;
  292. try
  293. {
  294. con = L2DatabaseFactory.getInstance().getConnection();
  295. PreparedStatement statement ;
  296. statement = con.prepareStatement("DELETE FROM character_friends WHERE charId=? OR friendId=?");
  297. statement.setInt(1, objid);
  298. statement.setInt(2, objid);
  299. statement.execute();
  300. statement.close();
  301. statement = con.prepareStatement("DELETE FROM character_hennas WHERE charId=?");
  302. statement.setInt(1, objid);
  303. statement.execute();
  304. statement.close();
  305. statement = con.prepareStatement("DELETE FROM character_macroses WHERE charId=?");
  306. statement.setInt(1, objid);
  307. statement.execute();
  308. statement.close();
  309. statement = con.prepareStatement("DELETE FROM character_quests WHERE charId=?");
  310. statement.setInt(1, objid);
  311. statement.execute();
  312. statement.close();
  313. statement = con.prepareStatement("DELETE FROM character_recipebook WHERE charId=?");
  314. statement.setInt(1, objid);
  315. statement.execute();
  316. statement.close();
  317. statement = con.prepareStatement("DELETE FROM character_shortcuts WHERE charId=?");
  318. statement.setInt(1, objid);
  319. statement.execute();
  320. statement.close();
  321. statement = con.prepareStatement("DELETE FROM character_skills WHERE charId=?");
  322. statement.setInt(1, objid);
  323. statement.execute();
  324. statement.close();
  325. statement = con.prepareStatement("DELETE FROM character_skills_save WHERE charId=?");
  326. statement.setInt(1, objid);
  327. statement.execute();
  328. statement.close();
  329. statement = con.prepareStatement("DELETE FROM character_subclasses WHERE charId=?");
  330. statement.setInt(1, objid);
  331. statement.execute();
  332. statement.close();
  333. statement = con.prepareStatement("DELETE FROM heroes WHERE charId=?");
  334. statement.setInt(1, objid);
  335. statement.execute();
  336. statement.close();
  337. statement = con.prepareStatement("DELETE FROM olympiad_nobles WHERE charId=?");
  338. statement.setInt(1, objid);
  339. statement.execute();
  340. statement.close();
  341. statement = con.prepareStatement("DELETE FROM seven_signs WHERE charId=?");
  342. statement.setInt(1, objid);
  343. statement.execute();
  344. statement.close();
  345. statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id IN (SELECT object_id FROM items WHERE items.owner_id=?)");
  346. statement.setInt(1, objid);
  347. statement.execute();
  348. statement.close();
  349. statement = con.prepareStatement("DELETE FROM item_attributes WHERE itemId IN (SELECT object_id FROM items WHERE items.owner_id=?)");
  350. statement.setInt(1, objid);
  351. statement.execute();
  352. statement.close();
  353. statement = con.prepareStatement("DELETE FROM items WHERE owner_id=?");
  354. statement.setInt(1, objid);
  355. statement.execute();
  356. statement.close();
  357. statement = con.prepareStatement("DELETE FROM merchant_lease WHERE player_id=?");
  358. statement.setInt(1, objid);
  359. statement.execute();
  360. statement.close();
  361. statement = con.prepareStatement("DELETE FROM character_raid_points WHERE charId=?");
  362. statement.setInt(1, objid);
  363. statement.execute();
  364. statement.close();
  365. statement = con.prepareStatement("DELETE FROM character_recommends WHERE charId=? OR target_id=?");
  366. statement.setInt(1, objid);
  367. statement.setInt(2, objid);
  368. statement.execute();
  369. statement.close();
  370. statement = con.prepareStatement("DELETE FROM characters WHERE charId=?");
  371. statement.setInt(1, objid);
  372. statement.execute();
  373. statement.close();
  374. }
  375. catch (Exception e)
  376. {
  377. _log.log(Level.SEVERE, "Error deleting character.", e);
  378. }
  379. finally
  380. {
  381. try { con.close(); } catch (Exception e) {}
  382. }
  383. }
  384. public L2PcInstance loadCharFromDisk(int charslot)
  385. {
  386. L2PcInstance character = L2PcInstance.load(getObjectIdForSlot(charslot));
  387. if (character != null)
  388. {
  389. // preinit some values for each login
  390. character.setRunning(); // running is default
  391. character.standUp(); // standing is default
  392. character.refreshOverloaded();
  393. character.refreshExpertisePenalty();
  394. character.setOnlineStatus(true);
  395. }
  396. else
  397. {
  398. _log.severe("could not restore in slot: "+ charslot);
  399. }
  400. //setCharacter(character);
  401. return character;
  402. }
  403. /**
  404. * @param chars
  405. */
  406. public void setCharSelection(CharSelectInfoPackage[] chars)
  407. {
  408. _charSlotMapping.clear();
  409. for (int i = 0; i < chars.length; i++)
  410. {
  411. int objectId = chars[i].getObjectId();
  412. _charSlotMapping.add(Integer.valueOf(objectId));
  413. }
  414. }
  415. public void close(L2GameServerPacket gsp)
  416. {
  417. getConnection().close(gsp);
  418. }
  419. /**
  420. * @param charslot
  421. * @return
  422. */
  423. private int getObjectIdForSlot(int charslot)
  424. {
  425. if (charslot < 0 || charslot >= _charSlotMapping.size())
  426. {
  427. _log.warning(toString()+" tried to delete Character in slot "+charslot+" but no characters exits at that slot.");
  428. return -1;
  429. }
  430. Integer objectId = _charSlotMapping.get(charslot);
  431. return objectId.intValue();
  432. }
  433. @Override
  434. protected void onForcedDisconnection()
  435. {
  436. _log.info("Client "+toString()+" disconnected abnormally.");
  437. }
  438. @Override
  439. protected void onDisconnection()
  440. {
  441. // no long running tasks here, do it async
  442. try
  443. {
  444. ThreadPoolManager.getInstance().executeTask(new DisconnectTask());
  445. }
  446. catch (RejectedExecutionException e)
  447. {
  448. // server is closing
  449. }
  450. }
  451. @Override
  452. public void closeNow()
  453. {
  454. super.closeNow();
  455. cleanMe(true);
  456. }
  457. /**
  458. * Produces the best possible string representation of this client.
  459. */
  460. @Override
  461. public String toString()
  462. {
  463. try
  464. {
  465. InetAddress address = getConnection().getSocket().getInetAddress();
  466. switch (getState())
  467. {
  468. case CONNECTED:
  469. return "[IP: "+(address == null ? "disconnected" : address.getHostAddress())+"]";
  470. case AUTHED:
  471. return "[Account: "+getAccountName()+" - IP: "+(address == null ? "disconnected" : address.getHostAddress())+"]";
  472. case IN_GAME:
  473. return "[Character: "+(getActiveChar() == null ? "disconnected" : getActiveChar().getName())+" - Account: "+getAccountName()+" - IP: "+(address == null ? "disconnected" : address.getHostAddress())+"]";
  474. default:
  475. throw new IllegalStateException("Missing state on switch");
  476. }
  477. }
  478. catch (NullPointerException e)
  479. {
  480. return "[Character read failed due to disconnect]";
  481. }
  482. }
  483. class DisconnectTask implements Runnable
  484. {
  485. /**
  486. * @see java.lang.Runnable#run()
  487. */
  488. public void run()
  489. {
  490. boolean fast = true;
  491. try
  492. {
  493. isDetached(true);
  494. L2PcInstance player = L2GameClient.this.getActiveChar();
  495. if (player != null && player.isInCombat())
  496. {
  497. fast = false;
  498. }
  499. cleanMe(fast);
  500. }
  501. catch (Exception e1)
  502. {
  503. _log.log(Level.WARNING, "Error while disconnecting client.", e1);
  504. }
  505. }
  506. }
  507. public void cleanMe(boolean fast)
  508. {
  509. try
  510. {
  511. synchronized(this)
  512. {
  513. if (_cleanupTask == null)
  514. {
  515. _cleanupTask = ThreadPoolManager.getInstance().scheduleGeneral(new CleanupTask(), fast ? 5 : 15000L);
  516. }
  517. }
  518. }
  519. catch (Exception e1)
  520. {
  521. _log.log(Level.WARNING, "Error during cleanup.", e1);
  522. }
  523. }
  524. class CleanupTask implements Runnable
  525. {
  526. /**
  527. * @see java.lang.Runnable#run()
  528. */
  529. public void run()
  530. {
  531. try
  532. {
  533. // Update BBS
  534. try
  535. {
  536. RegionBBSManager.getInstance().changeCommunityBoard();
  537. }
  538. catch (Exception e)
  539. {
  540. e.printStackTrace();
  541. }
  542. // we are going to mannually save the char bellow thus we can force the cancel
  543. if (_autoSaveInDB != null)
  544. {
  545. _autoSaveInDB.cancel(true);
  546. }
  547. L2PcInstance player = L2GameClient.this.getActiveChar();
  548. if (player != null) // this should only happen on connection loss
  549. {
  550. // we store all data from players who are disconnected while in an event in order to restore it in the next login
  551. if (player.atEvent)
  552. {
  553. EventData data = new EventData(player.eventX, player.eventY, player.eventZ, player.eventkarma, player.eventpvpkills, player.eventpkkills, player.eventTitle, player.kills, player.eventSitForced);
  554. L2Event.connectionLossData.put(player.getName(), data);
  555. }
  556. if (player.isFlying())
  557. {
  558. player.removeSkill(SkillTable.getInstance().getInfo(4289, 1));
  559. }
  560. // to prevent call cleanMe() again
  561. isDetached(false);
  562. // notify the world about our disconnect
  563. player.deleteMe();
  564. try
  565. {
  566. saveCharToDisk(player);
  567. }
  568. catch (Exception e2) { /* ignore any problems here */ }
  569. }
  570. L2GameClient.this.setActiveChar(null);
  571. }
  572. catch (Exception e1)
  573. {
  574. _log.log(Level.WARNING, "Error while cleanup client.", e1);
  575. }
  576. finally
  577. {
  578. LoginServerThread.getInstance().sendLogout(L2GameClient.this.getAccountName());
  579. }
  580. }
  581. }
  582. class AutoSaveTask implements Runnable
  583. {
  584. public void run()
  585. {
  586. try
  587. {
  588. L2PcInstance player = L2GameClient.this.getActiveChar();
  589. if (player != null)
  590. {
  591. saveCharToDisk(player);
  592. }
  593. }
  594. catch (Exception e)
  595. {
  596. _log.log(Level.SEVERE, "Error on AutoSaveTask.", e);
  597. }
  598. }
  599. }
  600. public boolean isProtocolOk()
  601. {
  602. return _protocol;
  603. }
  604. public void setProtocolOk(boolean b)
  605. {
  606. _protocol = b;
  607. }
  608. }