L2GameClient.java 18 KB

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