L2GameClient.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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 characters WHERE charId=?");
  382. statement.setInt(1, objid);
  383. statement.execute();
  384. statement.close();
  385. }
  386. catch (Exception e)
  387. {
  388. _log.log(Level.SEVERE, "Error deleting character.", e);
  389. }
  390. finally
  391. {
  392. try { con.close(); } catch (Exception e) {}
  393. }
  394. }
  395. public L2PcInstance loadCharFromDisk(int charslot)
  396. {
  397. L2PcInstance character = L2PcInstance.load(getObjectIdForSlot(charslot));
  398. if (character != null)
  399. {
  400. // preinit some values for each login
  401. character.setRunning(); // running is default
  402. character.standUp(); // standing is default
  403. character.refreshOverloaded();
  404. character.refreshExpertisePenalty();
  405. character.setOnlineStatus(true);
  406. }
  407. else
  408. {
  409. _log.severe("could not restore in slot: "+ charslot);
  410. }
  411. //setCharacter(character);
  412. return character;
  413. }
  414. /**
  415. * @param chars
  416. */
  417. public void setCharSelection(CharSelectInfoPackage[] chars)
  418. {
  419. _charSlotMapping.clear();
  420. for (int i = 0; i < chars.length; i++)
  421. {
  422. int objectId = chars[i].getObjectId();
  423. _charSlotMapping.add(Integer.valueOf(objectId));
  424. }
  425. }
  426. public void close(L2GameServerPacket gsp)
  427. {
  428. getConnection().close(gsp);
  429. }
  430. /**
  431. * @param charslot
  432. * @return
  433. */
  434. private int getObjectIdForSlot(int charslot)
  435. {
  436. if (charslot < 0 || charslot >= _charSlotMapping.size())
  437. {
  438. _log.warning(toString()+" tried to delete Character in slot "+charslot+" but no characters exits at that slot.");
  439. return -1;
  440. }
  441. Integer objectId = _charSlotMapping.get(charslot);
  442. return objectId.intValue();
  443. }
  444. @Override
  445. protected void onForcedDisconnection()
  446. {
  447. _log.info("Client "+toString()+" disconnected abnormally.");
  448. }
  449. @Override
  450. protected void onDisconnection()
  451. {
  452. // no long running tasks here, do it async
  453. try
  454. {
  455. ThreadPoolManager.getInstance().executeTask(new DisconnectTask());
  456. }
  457. catch (RejectedExecutionException e)
  458. {
  459. // server is closing
  460. }
  461. }
  462. @Override
  463. public void closeNow()
  464. {
  465. super.closeNow();
  466. cleanMe(true);
  467. }
  468. /**
  469. * Produces the best possible string representation of this client.
  470. */
  471. @Override
  472. public String toString()
  473. {
  474. try
  475. {
  476. InetAddress address = getConnection().getSocket().getInetAddress();
  477. switch (getState())
  478. {
  479. case CONNECTED:
  480. return "[IP: "+(address == null ? "disconnected" : address.getHostAddress())+"]";
  481. case AUTHED:
  482. return "[Account: "+getAccountName()+" - IP: "+(address == null ? "disconnected" : address.getHostAddress())+"]";
  483. case IN_GAME:
  484. return "[Character: "+(getActiveChar() == null ? "disconnected" : getActiveChar().getName())+" - Account: "+getAccountName()+" - IP: "+(address == null ? "disconnected" : address.getHostAddress())+"]";
  485. default:
  486. throw new IllegalStateException("Missing state on switch");
  487. }
  488. }
  489. catch (NullPointerException e)
  490. {
  491. return "[Character read failed due to disconnect]";
  492. }
  493. }
  494. class DisconnectTask implements Runnable
  495. {
  496. /**
  497. * @see java.lang.Runnable#run()
  498. */
  499. public void run()
  500. {
  501. boolean fast = true;
  502. try
  503. {
  504. isDetached(true);
  505. L2PcInstance player = L2GameClient.this.getActiveChar();
  506. if (player != null)
  507. {
  508. if (!player.isInOlympiadMode()
  509. && !player.isFestivalParticipant()
  510. && !TvTEvent.isPlayerParticipant(player.getObjectId()) && !player.isInJail())
  511. {
  512. if ((player.isInStoreMode() && Config.OFFLINE_TRADE_ENABLE)
  513. || (player.isInCraftMode() && Config.OFFLINE_CRAFT_ENABLE))
  514. {
  515. player.leaveParty();
  516. if (Config.OFFLINE_SET_NAME_COLOR)
  517. {
  518. player.getAppearance().setNameColor(Config.OFFLINE_NAME_COLOR);
  519. player.broadcastUserInfo();
  520. }
  521. return;
  522. }
  523. }
  524. if (player.isInCombat())
  525. {
  526. fast = false;
  527. }
  528. }
  529. cleanMe(fast);
  530. }
  531. catch (Exception e1)
  532. {
  533. _log.log(Level.WARNING, "Error while disconnecting client.", e1);
  534. }
  535. }
  536. }
  537. public void cleanMe(boolean fast)
  538. {
  539. try
  540. {
  541. synchronized(this)
  542. {
  543. if (_cleanupTask == null)
  544. {
  545. _cleanupTask = ThreadPoolManager.getInstance().scheduleGeneral(new CleanupTask(), fast ? 5 : 15000L);
  546. }
  547. }
  548. }
  549. catch (Exception e1)
  550. {
  551. _log.log(Level.WARNING, "Error during cleanup.", e1);
  552. }
  553. }
  554. class CleanupTask implements Runnable
  555. {
  556. /**
  557. * @see java.lang.Runnable#run()
  558. */
  559. public void run()
  560. {
  561. try
  562. {
  563. // Update BBS
  564. try
  565. {
  566. RegionBBSManager.getInstance().changeCommunityBoard();
  567. }
  568. catch (Exception e)
  569. {
  570. e.printStackTrace();
  571. }
  572. // we are going to manually save the char bellow thus we can force the cancel
  573. if (_autoSaveInDB != null)
  574. {
  575. _autoSaveInDB.cancel(true);
  576. }
  577. L2PcInstance player = L2GameClient.this.getActiveChar();
  578. if (player != null) // this should only happen on connection loss
  579. {
  580. // we store all data from players who are disconnected while in an event in order to restore it in the next login
  581. if (player.atEvent)
  582. {
  583. EventData data = new EventData(player.eventX, player.eventY, player.eventZ, player.eventkarma, player.eventpvpkills, player.eventpkkills, player.eventTitle, player.kills, player.eventSitForced);
  584. L2Event.connectionLossData.put(player.getName(), data);
  585. }
  586. if (player.isFlying())
  587. {
  588. player.removeSkill(SkillTable.getInstance().getInfo(4289, 1));
  589. }
  590. // to prevent call cleanMe() again
  591. isDetached(false);
  592. // notify the world about our disconnect
  593. player.deleteMe();
  594. try
  595. {
  596. saveCharToDisk(player);
  597. }
  598. catch (Exception e2) { /* ignore any problems here */ }
  599. }
  600. L2GameClient.this.setActiveChar(null);
  601. }
  602. catch (Exception e1)
  603. {
  604. _log.log(Level.WARNING, "Error while cleanup client.", e1);
  605. }
  606. finally
  607. {
  608. LoginServerThread.getInstance().sendLogout(L2GameClient.this.getAccountName());
  609. }
  610. }
  611. }
  612. class AutoSaveTask implements Runnable
  613. {
  614. public void run()
  615. {
  616. try
  617. {
  618. L2PcInstance player = L2GameClient.this.getActiveChar();
  619. if (player != null)
  620. {
  621. saveCharToDisk(player);
  622. }
  623. }
  624. catch (Exception e)
  625. {
  626. _log.log(Level.SEVERE, "Error on AutoSaveTask.", e);
  627. }
  628. }
  629. }
  630. public boolean isProtocolOk()
  631. {
  632. return _protocol;
  633. }
  634. public void setProtocolOk(boolean b)
  635. {
  636. _protocol = b;
  637. }
  638. }