L2GameClient.java 28 KB

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