L2GameClient.java 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. /*
  2. * Copyright (C) 2004-2013 L2J Server
  3. *
  4. * This file is part of L2J Server.
  5. *
  6. * L2J Server is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * L2J Server is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. package com.l2jserver.gameserver.network;
  20. import java.net.InetAddress;
  21. import java.net.UnknownHostException;
  22. import java.nio.ByteBuffer;
  23. import java.sql.Connection;
  24. import java.sql.PreparedStatement;
  25. import java.sql.ResultSet;
  26. import java.util.concurrent.ArrayBlockingQueue;
  27. import java.util.concurrent.Future;
  28. import java.util.concurrent.RejectedExecutionException;
  29. import java.util.concurrent.ScheduledFuture;
  30. import java.util.concurrent.locks.ReentrantLock;
  31. import java.util.logging.Level;
  32. import java.util.logging.LogRecord;
  33. import java.util.logging.Logger;
  34. import org.mmocore.network.MMOClient;
  35. import org.mmocore.network.MMOConnection;
  36. import org.mmocore.network.ReceivablePacket;
  37. import com.l2jserver.Config;
  38. import com.l2jserver.L2DatabaseFactory;
  39. import com.l2jserver.gameserver.LoginServerThread;
  40. import com.l2jserver.gameserver.LoginServerThread.SessionKey;
  41. import com.l2jserver.gameserver.ThreadPoolManager;
  42. import com.l2jserver.gameserver.datatables.CharNameTable;
  43. import com.l2jserver.gameserver.datatables.ClanTable;
  44. import com.l2jserver.gameserver.datatables.SecondaryAuthData;
  45. import com.l2jserver.gameserver.instancemanager.AntiFeedManager;
  46. import com.l2jserver.gameserver.model.CharSelectInfoPackage;
  47. import com.l2jserver.gameserver.model.L2Clan;
  48. import com.l2jserver.gameserver.model.L2World;
  49. import com.l2jserver.gameserver.model.PcCondOverride;
  50. import com.l2jserver.gameserver.model.actor.instance.L2PcInstance;
  51. import com.l2jserver.gameserver.model.entity.L2Event;
  52. import com.l2jserver.gameserver.model.zone.ZoneId;
  53. import com.l2jserver.gameserver.network.serverpackets.ActionFailed;
  54. import com.l2jserver.gameserver.network.serverpackets.L2GameServerPacket;
  55. import com.l2jserver.gameserver.network.serverpackets.ServerClose;
  56. import com.l2jserver.gameserver.security.SecondaryPasswordAuth;
  57. import com.l2jserver.gameserver.util.FloodProtectors;
  58. import com.l2jserver.gameserver.util.Util;
  59. /**
  60. * Represents a client connected on Game Server.
  61. * @author KenM
  62. */
  63. public final class L2GameClient extends MMOClient<MMOConnection<L2GameClient>> implements Runnable
  64. {
  65. protected static final Logger _log = Logger.getLogger(L2GameClient.class.getName());
  66. protected static final Logger _logAccounting = Logger.getLogger("accounting");
  67. /**
  68. * @author KenM
  69. */
  70. public static enum GameClientState
  71. {
  72. /** Client has just connected . */
  73. CONNECTED,
  74. /** Client has authed but doesn't has character attached to it yet. */
  75. AUTHED,
  76. /** Client has selected a char and is in game. */
  77. IN_GAME
  78. }
  79. private GameClientState _state;
  80. // Info
  81. private final InetAddress _addr;
  82. private String _accountName;
  83. private SessionKey _sessionId;
  84. private L2PcInstance _activeChar;
  85. private final ReentrantLock _activeCharLock = new ReentrantLock();
  86. private SecondaryPasswordAuth _secondaryAuth;
  87. private boolean _isAuthedGG;
  88. private final long _connectionStartTime;
  89. private CharSelectInfoPackage[] _charSlotMapping = null;
  90. // flood protectors
  91. private final FloodProtectors _floodProtectors = new FloodProtectors(this);
  92. // Task
  93. protected final ScheduledFuture<?> _autoSaveInDB;
  94. protected ScheduledFuture<?> _cleanupTask = null;
  95. private L2GameServerPacket _aditionalClosePacket;
  96. // Crypt
  97. private final GameCrypt _crypt;
  98. private final ClientStats _stats;
  99. private boolean _isDetached = false;
  100. private boolean _protocol;
  101. private final ArrayBlockingQueue<ReceivablePacket<L2GameClient>> _packetQueue;
  102. private final ReentrantLock _queueLock = new ReentrantLock();
  103. private int[][] trace;
  104. public L2GameClient(MMOConnection<L2GameClient> con)
  105. {
  106. super(con);
  107. _state = GameClientState.CONNECTED;
  108. _connectionStartTime = System.currentTimeMillis();
  109. _crypt = new GameCrypt();
  110. _stats = new ClientStats();
  111. _packetQueue = new ArrayBlockingQueue<>(Config.CLIENT_PACKET_QUEUE_SIZE);
  112. if (Config.CHAR_STORE_INTERVAL > 0)
  113. {
  114. _autoSaveInDB = ThreadPoolManager.getInstance().scheduleGeneralAtFixedRate(new AutoSaveTask(), 300000L, (Config.CHAR_STORE_INTERVAL * 60000L));
  115. }
  116. else
  117. {
  118. _autoSaveInDB = null;
  119. }
  120. try
  121. {
  122. _addr = con != null ? con.getInetAddress() : InetAddress.getLocalHost();
  123. }
  124. catch (UnknownHostException e)
  125. {
  126. throw new Error("Unable to determine localhost address.");
  127. }
  128. }
  129. public byte[] enableCrypt()
  130. {
  131. byte[] key = BlowFishKeygen.getRandomKey();
  132. _crypt.setKey(key);
  133. return key;
  134. }
  135. public GameClientState getState()
  136. {
  137. return _state;
  138. }
  139. public void setState(GameClientState pState)
  140. {
  141. if (_state != pState)
  142. {
  143. _state = pState;
  144. _packetQueue.clear();
  145. }
  146. }
  147. public ClientStats getStats()
  148. {
  149. return _stats;
  150. }
  151. /**
  152. * For loaded offline traders returns localhost address.
  153. * @return cached connection IP address, for checking detached clients.
  154. */
  155. public InetAddress getConnectionAddress()
  156. {
  157. return _addr;
  158. }
  159. public long getConnectionStartTime()
  160. {
  161. return _connectionStartTime;
  162. }
  163. @Override
  164. public boolean decrypt(ByteBuffer buf, int size)
  165. {
  166. _crypt.decrypt(buf.array(), buf.position(), size);
  167. return true;
  168. }
  169. @Override
  170. public boolean encrypt(final ByteBuffer buf, final int size)
  171. {
  172. _crypt.encrypt(buf.array(), buf.position(), size);
  173. buf.position(buf.position() + size);
  174. return true;
  175. }
  176. public L2PcInstance getActiveChar()
  177. {
  178. return _activeChar;
  179. }
  180. public void setActiveChar(L2PcInstance pActiveChar)
  181. {
  182. _activeChar = pActiveChar;
  183. // JIV remove - done on spawn
  184. /*
  185. * if (_activeChar != null) { L2World.getInstance().storeObject(getActiveChar()); }
  186. */
  187. }
  188. public ReentrantLock getActiveCharLock()
  189. {
  190. return _activeCharLock;
  191. }
  192. public FloodProtectors getFloodProtectors()
  193. {
  194. return _floodProtectors;
  195. }
  196. public void setGameGuardOk(boolean val)
  197. {
  198. _isAuthedGG = val;
  199. }
  200. public boolean isAuthedGG()
  201. {
  202. return _isAuthedGG;
  203. }
  204. public void setAccountName(String pAccountName)
  205. {
  206. _accountName = pAccountName;
  207. if (SecondaryAuthData.getInstance().isEnabled())
  208. {
  209. _secondaryAuth = new SecondaryPasswordAuth(this);
  210. }
  211. }
  212. public String getAccountName()
  213. {
  214. return _accountName;
  215. }
  216. public void setSessionId(SessionKey sk)
  217. {
  218. _sessionId = sk;
  219. }
  220. public SessionKey getSessionId()
  221. {
  222. return _sessionId;
  223. }
  224. public void sendPacket(L2GameServerPacket gsp)
  225. {
  226. if (_isDetached || (gsp == null))
  227. {
  228. return;
  229. }
  230. // Packets from invisible chars sends only to GMs
  231. if (gsp.isInvisible() && (getActiveChar() != null) && !getActiveChar().canOverrideCond(PcCondOverride.SEE_ALL_PLAYERS))
  232. {
  233. return;
  234. }
  235. getConnection().sendPacket(gsp);
  236. gsp.runImpl();
  237. }
  238. public boolean isDetached()
  239. {
  240. return _isDetached;
  241. }
  242. public void setDetached(boolean b)
  243. {
  244. _isDetached = b;
  245. }
  246. /**
  247. * Method to handle character deletion
  248. * @param charslot
  249. * @return a byte: <li>-1: Error: No char was found for such charslot, caught exception, etc... <li>0: character is not member of any clan, proceed with deletion <li>1: character is member of a clan, but not clan leader <li>2: character is clan leader
  250. */
  251. public byte markToDeleteChar(int charslot)
  252. {
  253. int objid = getObjectIdForSlot(charslot);
  254. if (objid < 0)
  255. {
  256. return -1;
  257. }
  258. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  259. PreparedStatement statement = con.prepareStatement("SELECT clanId FROM characters WHERE charId=?"))
  260. {
  261. statement.setInt(1, objid);
  262. byte answer = 0;
  263. try (ResultSet rs = statement.executeQuery())
  264. {
  265. int clanId = rs.next() ? rs.getInt(1) : 0;
  266. if (clanId != 0)
  267. {
  268. L2Clan clan = ClanTable.getInstance().getClan(clanId);
  269. if (clan == null)
  270. {
  271. answer = 0; // jeezes!
  272. }
  273. else if (clan.getLeaderId() == objid)
  274. {
  275. answer = 2;
  276. }
  277. else
  278. {
  279. answer = 1;
  280. }
  281. }
  282. // Setting delete time
  283. if (answer == 0)
  284. {
  285. if (Config.DELETE_DAYS == 0)
  286. {
  287. deleteCharByObjId(objid);
  288. }
  289. else
  290. {
  291. try (PreparedStatement ps2 = con.prepareStatement("UPDATE characters SET deletetime=? WHERE charId=?"))
  292. {
  293. ps2.setLong(1, System.currentTimeMillis() + (Config.DELETE_DAYS * 86400000L)); // 24*60*60*1000 = 86400000
  294. ps2.setInt(2, objid);
  295. ps2.execute();
  296. }
  297. }
  298. LogRecord record = new LogRecord(Level.WARNING, "Delete");
  299. record.setParameters(new Object[]
  300. {
  301. objid,
  302. this
  303. });
  304. _logAccounting.log(record);
  305. }
  306. }
  307. return answer;
  308. }
  309. catch (Exception e)
  310. {
  311. _log.log(Level.SEVERE, "Error updating delete time of character.", e);
  312. return -1;
  313. }
  314. }
  315. /**
  316. * Save the L2PcInstance to the database.
  317. */
  318. public void saveCharToDisk()
  319. {
  320. try
  321. {
  322. if (getActiveChar() != null)
  323. {
  324. getActiveChar().storeMe();
  325. getActiveChar().storeRecommendations();
  326. if (Config.UPDATE_ITEMS_ON_CHAR_STORE)
  327. {
  328. getActiveChar().getInventory().updateDatabase();
  329. getActiveChar().getWarehouse().updateDatabase();
  330. }
  331. }
  332. }
  333. catch (Exception e)
  334. {
  335. _log.log(Level.SEVERE, "Error saving character..", e);
  336. }
  337. }
  338. public void markRestoredChar(int charslot)
  339. {
  340. final int objid = getObjectIdForSlot(charslot);
  341. if (objid < 0)
  342. {
  343. return;
  344. }
  345. try (Connection con = L2DatabaseFactory.getInstance().getConnection();
  346. PreparedStatement statement = con.prepareStatement("UPDATE characters SET deletetime=0 WHERE charId=?"))
  347. {
  348. statement.setInt(1, objid);
  349. statement.execute();
  350. }
  351. catch (Exception e)
  352. {
  353. _log.log(Level.SEVERE, "Error restoring character.", e);
  354. }
  355. final LogRecord record = new LogRecord(Level.WARNING, "Restore");
  356. record.setParameters(new Object[]
  357. {
  358. objid,
  359. this
  360. });
  361. _logAccounting.log(record);
  362. }
  363. public static void deleteCharByObjId(int objid)
  364. {
  365. if (objid < 0)
  366. {
  367. return;
  368. }
  369. CharNameTable.getInstance().removeName(objid);
  370. try (Connection con = L2DatabaseFactory.getInstance().getConnection())
  371. {
  372. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_contacts WHERE charId=? OR contactId=?"))
  373. {
  374. ps.setInt(1, objid);
  375. ps.setInt(2, objid);
  376. ps.execute();
  377. }
  378. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_friends WHERE charId=? OR friendId=?"))
  379. {
  380. ps.setInt(1, objid);
  381. ps.setInt(2, objid);
  382. ps.execute();
  383. }
  384. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_hennas WHERE charId=?"))
  385. {
  386. ps.setInt(1, objid);
  387. ps.execute();
  388. }
  389. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_macroses WHERE charId=?"))
  390. {
  391. ps.setInt(1, objid);
  392. ps.execute();
  393. }
  394. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_quests WHERE charId=?"))
  395. {
  396. ps.setInt(1, objid);
  397. ps.execute();
  398. }
  399. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_quest_global_data WHERE charId=?"))
  400. {
  401. ps.setInt(1, objid);
  402. ps.executeUpdate();
  403. }
  404. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_recipebook WHERE charId=?"))
  405. {
  406. ps.setInt(1, objid);
  407. ps.execute();
  408. }
  409. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_shortcuts WHERE charId=?"))
  410. {
  411. ps.setInt(1, objid);
  412. ps.execute();
  413. }
  414. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_skills WHERE charId=?"))
  415. {
  416. ps.setInt(1, objid);
  417. ps.execute();
  418. }
  419. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_skills_save WHERE charId=?"))
  420. {
  421. ps.setInt(1, objid);
  422. ps.execute();
  423. }
  424. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_subclasses WHERE charId=?"))
  425. {
  426. ps.setInt(1, objid);
  427. ps.execute();
  428. }
  429. try (PreparedStatement ps = con.prepareStatement("DELETE FROM heroes WHERE charId=?"))
  430. {
  431. ps.setInt(1, objid);
  432. ps.execute();
  433. }
  434. try (PreparedStatement ps = con.prepareStatement("DELETE FROM olympiad_nobles WHERE charId=?"))
  435. {
  436. ps.setInt(1, objid);
  437. ps.execute();
  438. }
  439. try (PreparedStatement ps = con.prepareStatement("DELETE FROM seven_signs WHERE charId=?"))
  440. {
  441. ps.setInt(1, objid);
  442. ps.execute();
  443. }
  444. try (PreparedStatement ps = con.prepareStatement("DELETE FROM pets WHERE item_obj_id IN (SELECT object_id FROM items WHERE items.owner_id=?)"))
  445. {
  446. ps.setInt(1, objid);
  447. ps.execute();
  448. }
  449. try (PreparedStatement ps = con.prepareStatement("DELETE FROM item_attributes WHERE itemId IN (SELECT object_id FROM items WHERE items.owner_id=?)"))
  450. {
  451. ps.setInt(1, objid);
  452. ps.execute();
  453. }
  454. try (PreparedStatement ps = con.prepareStatement("DELETE FROM items WHERE owner_id=?"))
  455. {
  456. ps.setInt(1, objid);
  457. ps.execute();
  458. }
  459. try (PreparedStatement ps = con.prepareStatement("DELETE FROM merchant_lease WHERE player_id=?"))
  460. {
  461. ps.setInt(1, objid);
  462. ps.execute();
  463. }
  464. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_raid_points WHERE charId=?"))
  465. {
  466. ps.setInt(1, objid);
  467. ps.execute();
  468. }
  469. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_reco_bonus WHERE charId=?"))
  470. {
  471. ps.setInt(1, objid);
  472. ps.execute();
  473. }
  474. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_instance_time WHERE charId=?"))
  475. {
  476. ps.setInt(1, objid);
  477. ps.execute();
  478. }
  479. try (PreparedStatement ps = con.prepareStatement("DELETE FROM character_variables WHERE charId=?"))
  480. {
  481. ps.setInt(1, objid);
  482. ps.execute();
  483. }
  484. try (PreparedStatement ps = con.prepareStatement("DELETE FROM characters WHERE charId=?"))
  485. {
  486. ps.setInt(1, objid);
  487. ps.execute();
  488. }
  489. if (Config.L2JMOD_ALLOW_WEDDING)
  490. {
  491. try (PreparedStatement ps = con.prepareStatement("DELETE FROM mods_wedding WHERE player1Id = ? OR player2Id = ?"))
  492. {
  493. ps.setInt(1, objid);
  494. ps.setInt(2, objid);
  495. ps.execute();
  496. }
  497. }
  498. }
  499. catch (Exception e)
  500. {
  501. _log.log(Level.SEVERE, "Error deleting character.", e);
  502. }
  503. }
  504. public L2PcInstance loadCharFromDisk(int charslot)
  505. {
  506. final int objId = getObjectIdForSlot(charslot);
  507. if (objId < 0)
  508. {
  509. return null;
  510. }
  511. L2PcInstance character = L2World.getInstance().getPlayer(objId);
  512. if (character != null)
  513. {
  514. // exploit prevention, should not happens in normal way
  515. _log.severe("Attempt of double login: " + character.getName() + "(" + objId + ") " + getAccountName());
  516. if (character.getClient() != null)
  517. {
  518. character.getClient().closeNow();
  519. }
  520. else
  521. {
  522. character.deleteMe();
  523. }
  524. return null;
  525. }
  526. character = L2PcInstance.load(objId);
  527. if (character != null)
  528. {
  529. // preinit some values for each login
  530. character.setRunning(); // running is default
  531. character.standUp(); // standing is default
  532. character.refreshOverloaded();
  533. character.refreshExpertisePenalty();
  534. character.setOnlineStatus(true, false);
  535. }
  536. else
  537. {
  538. _log.severe("could not restore in slot: " + charslot);
  539. }
  540. // setCharacter(character);
  541. return character;
  542. }
  543. /**
  544. * @param chars
  545. */
  546. public void setCharSelection(CharSelectInfoPackage[] chars)
  547. {
  548. _charSlotMapping = chars;
  549. }
  550. public CharSelectInfoPackage getCharSelection(int charslot)
  551. {
  552. if ((_charSlotMapping == null) || (charslot < 0) || (charslot >= _charSlotMapping.length))
  553. {
  554. return null;
  555. }
  556. return _charSlotMapping[charslot];
  557. }
  558. public SecondaryPasswordAuth getSecondaryAuth()
  559. {
  560. return _secondaryAuth;
  561. }
  562. public void close(L2GameServerPacket gsp)
  563. {
  564. if (getConnection() == null)
  565. {
  566. return; // ofline shop
  567. }
  568. if (_aditionalClosePacket != null)
  569. {
  570. getConnection().close(new L2GameServerPacket[]
  571. {
  572. _aditionalClosePacket,
  573. gsp
  574. });
  575. }
  576. else
  577. {
  578. getConnection().close(gsp);
  579. }
  580. }
  581. public void close(L2GameServerPacket[] gspArray)
  582. {
  583. if (getConnection() == null)
  584. {
  585. return; // ofline shop
  586. }
  587. getConnection().close(gspArray);
  588. }
  589. /**
  590. * @param charslot
  591. * @return
  592. */
  593. private int getObjectIdForSlot(int charslot)
  594. {
  595. final CharSelectInfoPackage info = getCharSelection(charslot);
  596. if (info == null)
  597. {
  598. _log.warning(toString() + " tried to delete Character in slot " + charslot + " but no characters exits at that slot.");
  599. return -1;
  600. }
  601. return info.getObjectId();
  602. }
  603. @Override
  604. protected void onForcedDisconnection()
  605. {
  606. LogRecord record = new LogRecord(Level.WARNING, "Disconnected abnormally");
  607. record.setParameters(new Object[]
  608. {
  609. this
  610. });
  611. _logAccounting.log(record);
  612. }
  613. @Override
  614. protected void onDisconnection()
  615. {
  616. // no long running tasks here, do it async
  617. try
  618. {
  619. ThreadPoolManager.getInstance().executeTask(new DisconnectTask());
  620. }
  621. catch (RejectedExecutionException e)
  622. {
  623. // server is closing
  624. }
  625. }
  626. /**
  627. * Close client connection with {@link ServerClose} packet
  628. */
  629. public void closeNow()
  630. {
  631. _isDetached = true; // prevents more packets execution
  632. close(ServerClose.STATIC_PACKET);
  633. synchronized (this)
  634. {
  635. if (_cleanupTask != null)
  636. {
  637. cancelCleanup();
  638. }
  639. _cleanupTask = ThreadPoolManager.getInstance().scheduleGeneral(new CleanupTask(), 0); // instant
  640. }
  641. }
  642. /**
  643. * Produces the best possible string representation of this client.
  644. */
  645. @Override
  646. public String toString()
  647. {
  648. try
  649. {
  650. final InetAddress address = getConnection().getInetAddress();
  651. switch (getState())
  652. {
  653. case CONNECTED:
  654. return "[IP: " + (address == null ? "disconnected" : address.getHostAddress()) + "]";
  655. case AUTHED:
  656. return "[Account: " + getAccountName() + " - IP: " + (address == null ? "disconnected" : address.getHostAddress()) + "]";
  657. case IN_GAME:
  658. return "[Character: " + (getActiveChar() == null ? "disconnected" : getActiveChar().getName() + "[" + getActiveChar().getObjectId() + "]") + " - Account: " + getAccountName() + " - IP: " + (address == null ? "disconnected" : address.getHostAddress()) + "]";
  659. default:
  660. throw new IllegalStateException("Missing state on switch");
  661. }
  662. }
  663. catch (NullPointerException e)
  664. {
  665. return "[Character read failed due to disconnect]";
  666. }
  667. }
  668. protected class DisconnectTask implements Runnable
  669. {
  670. @Override
  671. public void run()
  672. {
  673. boolean fast = true;
  674. try
  675. {
  676. if ((getActiveChar() != null) && !isDetached())
  677. {
  678. setDetached(true);
  679. if (offlineMode(getActiveChar()))
  680. {
  681. getActiveChar().leaveParty();
  682. // If the L2PcInstance has Pet, unsummon it
  683. if (getActiveChar().hasSummon())
  684. {
  685. getActiveChar().getSummon().setRestoreSummon(true);
  686. getActiveChar().getSummon().unSummon(getActiveChar());
  687. // Dead pet wasn't unsummoned, broadcast npcinfo changes (pet will be without owner name - means owner offline)
  688. if (getActiveChar().getSummon() != null)
  689. {
  690. getActiveChar().getSummon().broadcastNpcInfo(0);
  691. }
  692. }
  693. if (Config.OFFLINE_SET_NAME_COLOR)
  694. {
  695. getActiveChar().getAppearance().setNameColor(Config.OFFLINE_NAME_COLOR);
  696. getActiveChar().broadcastUserInfo();
  697. }
  698. if (getActiveChar().getOfflineStartTime() == 0)
  699. {
  700. getActiveChar().setOfflineStartTime(System.currentTimeMillis());
  701. }
  702. final LogRecord record = new LogRecord(Level.INFO, "Entering offline mode");
  703. record.setParameters(new Object[]
  704. {
  705. L2GameClient.this
  706. });
  707. _logAccounting.log(record);
  708. return;
  709. }
  710. fast = !getActiveChar().isInCombat() && !getActiveChar().isLocked();
  711. }
  712. cleanMe(fast);
  713. }
  714. catch (Exception e1)
  715. {
  716. _log.log(Level.WARNING, "Error while disconnecting client.", e1);
  717. }
  718. }
  719. }
  720. /**
  721. * @param player the player to be check.
  722. * @return {@code true} if the player is allowed to remain as off-line shop.
  723. */
  724. protected boolean offlineMode(L2PcInstance player)
  725. {
  726. if (player.isInOlympiadMode() || player.isFestivalParticipant() || player.isBlockedFromExit() || player.isJailed() || (player.getVehicle() != null))
  727. {
  728. return false;
  729. }
  730. boolean canSetShop = false;
  731. switch (player.getPrivateStoreType())
  732. {
  733. case L2PcInstance.STORE_PRIVATE_SELL:
  734. case L2PcInstance.STORE_PRIVATE_PACKAGE_SELL:
  735. case L2PcInstance.STORE_PRIVATE_BUY:
  736. {
  737. canSetShop = Config.OFFLINE_TRADE_ENABLE;
  738. break;
  739. }
  740. case L2PcInstance.STORE_PRIVATE_MANUFACTURE:
  741. {
  742. canSetShop = Config.OFFLINE_TRADE_ENABLE;
  743. break;
  744. }
  745. default:
  746. {
  747. canSetShop = Config.OFFLINE_CRAFT_ENABLE && player.isInCraftMode();
  748. break;
  749. }
  750. }
  751. if (Config.OFFLINE_MODE_IN_PEACE_ZONE && !player.isInsideZone(ZoneId.PEACE))
  752. {
  753. canSetShop = false;
  754. }
  755. return canSetShop;
  756. }
  757. public void cleanMe(boolean fast)
  758. {
  759. try
  760. {
  761. synchronized (this)
  762. {
  763. if (_cleanupTask == null)
  764. {
  765. _cleanupTask = ThreadPoolManager.getInstance().scheduleGeneral(new CleanupTask(), fast ? 5 : 15000L);
  766. }
  767. }
  768. }
  769. catch (Exception e1)
  770. {
  771. _log.log(Level.WARNING, "Error during cleanup.", e1);
  772. }
  773. }
  774. protected class CleanupTask implements Runnable
  775. {
  776. @Override
  777. public void run()
  778. {
  779. try
  780. {
  781. // we are going to manually save the char bellow thus we can force the cancel
  782. if (_autoSaveInDB != null)
  783. {
  784. _autoSaveInDB.cancel(true);
  785. // ThreadPoolManager.getInstance().removeGeneral((Runnable) _autoSaveInDB);
  786. }
  787. if (getActiveChar() != null) // this should only happen on connection loss
  788. {
  789. if (getActiveChar().isLocked())
  790. {
  791. _log.log(Level.WARNING, "Player " + getActiveChar().getName() + " still performing subclass actions during disconnect.");
  792. }
  793. // we store all data from players who are disconnected while in an event in order to restore it in the next login
  794. if (L2Event.isParticipant(getActiveChar()))
  795. {
  796. L2Event.savePlayerEventStatus(getActiveChar());
  797. }
  798. // prevent closing again
  799. getActiveChar().setClient(null);
  800. if (getActiveChar().isOnline())
  801. {
  802. getActiveChar().deleteMe();
  803. AntiFeedManager.getInstance().onDisconnect(L2GameClient.this);
  804. }
  805. }
  806. setActiveChar(null);
  807. }
  808. catch (Exception e1)
  809. {
  810. _log.log(Level.WARNING, "Error while cleanup client.", e1);
  811. }
  812. finally
  813. {
  814. LoginServerThread.getInstance().sendLogout(getAccountName());
  815. }
  816. }
  817. }
  818. protected class AutoSaveTask implements Runnable
  819. {
  820. @Override
  821. public void run()
  822. {
  823. try
  824. {
  825. L2PcInstance player = getActiveChar();
  826. if ((player != null) && player.isOnline()) // safety precaution
  827. {
  828. saveCharToDisk();
  829. if (player.hasSummon())
  830. {
  831. player.getSummon().storeMe();
  832. }
  833. }
  834. }
  835. catch (Exception e)
  836. {
  837. _log.log(Level.SEVERE, "Error on AutoSaveTask.", e);
  838. }
  839. }
  840. }
  841. public boolean isProtocolOk()
  842. {
  843. return _protocol;
  844. }
  845. public void setProtocolOk(boolean b)
  846. {
  847. _protocol = b;
  848. }
  849. public boolean handleCheat(String punishment)
  850. {
  851. if (_activeChar != null)
  852. {
  853. Util.handleIllegalPlayerAction(_activeChar, toString() + ": " + punishment, Config.DEFAULT_PUNISH);
  854. return true;
  855. }
  856. Logger _logAudit = Logger.getLogger("audit");
  857. _logAudit.log(Level.INFO, "AUDIT: Client " + toString() + " kicked for reason: " + punishment);
  858. closeNow();
  859. return false;
  860. }
  861. /**
  862. * True if detached, or flood detected, or queue overflow detected and queue still not empty.
  863. * @return false if client can receive packets.
  864. */
  865. public boolean dropPacket()
  866. {
  867. if (_isDetached)
  868. {
  869. return true;
  870. }
  871. // flood protection
  872. if (getStats().countPacket(_packetQueue.size()))
  873. {
  874. sendPacket(ActionFailed.STATIC_PACKET);
  875. return true;
  876. }
  877. return getStats().dropPacket();
  878. }
  879. /**
  880. * Counts buffer underflow exceptions.
  881. */
  882. public void onBufferUnderflow()
  883. {
  884. if (getStats().countUnderflowException())
  885. {
  886. _log.severe("Client " + toString() + " - Disconnected: Too many buffer underflow exceptions.");
  887. closeNow();
  888. return;
  889. }
  890. if (_state == GameClientState.CONNECTED) // in CONNECTED state kick client immediately
  891. {
  892. if (Config.PACKET_HANDLER_DEBUG)
  893. {
  894. _log.severe("Client " + toString() + " - Disconnected, too many buffer underflows in non-authed state.");
  895. }
  896. closeNow();
  897. }
  898. }
  899. /**
  900. * Counts unknown packets
  901. */
  902. public void onUnknownPacket()
  903. {
  904. if (getStats().countUnknownPacket())
  905. {
  906. _log.severe("Client " + toString() + " - Disconnected: Too many unknown packets.");
  907. closeNow();
  908. return;
  909. }
  910. if (_state == GameClientState.CONNECTED) // in CONNECTED state kick client immediately
  911. {
  912. if (Config.PACKET_HANDLER_DEBUG)
  913. {
  914. _log.severe("Client " + toString() + " - Disconnected, too many unknown packets in non-authed state.");
  915. }
  916. closeNow();
  917. }
  918. }
  919. /**
  920. * Add packet to the queue and start worker thread if needed
  921. * @param packet
  922. */
  923. public void execute(ReceivablePacket<L2GameClient> packet)
  924. {
  925. if (getStats().countFloods())
  926. {
  927. _log.severe("Client " + toString() + " - Disconnected, too many floods:" + getStats().longFloods + " long and " + getStats().shortFloods + " short.");
  928. closeNow();
  929. return;
  930. }
  931. if (!_packetQueue.offer(packet))
  932. {
  933. if (getStats().countQueueOverflow())
  934. {
  935. _log.severe("Client " + toString() + " - Disconnected, too many queue overflows.");
  936. closeNow();
  937. }
  938. else
  939. {
  940. sendPacket(ActionFailed.STATIC_PACKET);
  941. }
  942. return;
  943. }
  944. if (_queueLock.isLocked())
  945. {
  946. return;
  947. }
  948. try
  949. {
  950. if (_state == GameClientState.CONNECTED)
  951. {
  952. if (getStats().processedPackets > 3)
  953. {
  954. if (Config.PACKET_HANDLER_DEBUG)
  955. {
  956. _log.severe("Client " + toString() + " - Disconnected, too many packets in non-authed state.");
  957. }
  958. closeNow();
  959. return;
  960. }
  961. ThreadPoolManager.getInstance().executeIOPacket(this);
  962. }
  963. else
  964. {
  965. ThreadPoolManager.getInstance().executePacket(this);
  966. }
  967. }
  968. catch (RejectedExecutionException e)
  969. {
  970. // if the server is shutdown we ignore
  971. if (!ThreadPoolManager.getInstance().isShutdown())
  972. {
  973. _log.severe("Failed executing: " + packet.getClass().getSimpleName() + " for Client: " + toString());
  974. }
  975. }
  976. }
  977. @Override
  978. public void run()
  979. {
  980. if (!_queueLock.tryLock())
  981. {
  982. return;
  983. }
  984. try
  985. {
  986. int count = 0;
  987. ReceivablePacket<L2GameClient> packet;
  988. while (true)
  989. {
  990. packet = _packetQueue.poll();
  991. if (packet == null)
  992. {
  993. return;
  994. }
  995. if (_isDetached) // clear queue immediately after detach
  996. {
  997. _packetQueue.clear();
  998. return;
  999. }
  1000. try
  1001. {
  1002. packet.run();
  1003. }
  1004. catch (Exception e)
  1005. {
  1006. _log.severe("Exception during execution " + packet.getClass().getSimpleName() + ", client: " + toString() + "," + e.getMessage());
  1007. }
  1008. count++;
  1009. if (getStats().countBurst(count))
  1010. {
  1011. return;
  1012. }
  1013. }
  1014. }
  1015. finally
  1016. {
  1017. _queueLock.unlock();
  1018. }
  1019. }
  1020. public void setClientTracert(int[][] tracert)
  1021. {
  1022. trace = tracert;
  1023. }
  1024. public int[][] getTrace()
  1025. {
  1026. return trace;
  1027. }
  1028. private boolean cancelCleanup()
  1029. {
  1030. final Future<?> task = _cleanupTask;
  1031. if (task != null)
  1032. {
  1033. _cleanupTask = null;
  1034. return task.cancel(true);
  1035. }
  1036. return false;
  1037. }
  1038. public void setAditionalClosePacket(L2GameServerPacket aditionalClosePacket)
  1039. {
  1040. _aditionalClosePacket = aditionalClosePacket;
  1041. }
  1042. }