L2GameClient.java 20 KB

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