L2GameClient.java 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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<ReceivablePacket<L2GameClient>>(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. * Returns cached connection IP address, for checking detached clients.
  146. * For loaded offline traders returns localhost address.
  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. *
  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. Connection con = null;
  257. try
  258. {
  259. con = L2DatabaseFactory.getInstance().getConnection();
  260. PreparedStatement statement = con.prepareStatement("SELECT clanId FROM characters WHERE charId=?");
  261. statement.setInt(1, objid);
  262. ResultSet rs = statement.executeQuery();
  263. rs.next();
  264. int clanId = rs.getInt(1);
  265. byte answer = 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. rs.close();
  283. statement.close();
  284. // Setting delete time
  285. if (answer == 0)
  286. {
  287. if (Config.DELETE_DAYS == 0)
  288. {
  289. deleteCharByObjId(objid);
  290. }
  291. else
  292. {
  293. statement = con.prepareStatement("UPDATE characters SET deletetime=? WHERE charId=?");
  294. statement.setLong(1, System.currentTimeMillis() + (Config.DELETE_DAYS * 86400000L)); // 24*60*60*1000 = 86400000
  295. statement.setInt(2, objid);
  296. statement.execute();
  297. statement.close();
  298. }
  299. LogRecord record = new LogRecord(Level.WARNING, "Delete");
  300. record.setParameters(new Object[] { objid, this });
  301. _logAccounting.log(record);
  302. }
  303. return answer;
  304. }
  305. catch (Exception e)
  306. {
  307. _log.log(Level.SEVERE, "Error updating delete time of character.", e);
  308. return -1;
  309. }
  310. finally
  311. {
  312. L2DatabaseFactory.close(con);
  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().store();
  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. Connection con = null;
  346. try
  347. {
  348. con = L2DatabaseFactory.getInstance().getConnection();
  349. PreparedStatement statement = con.prepareStatement("UPDATE characters SET deletetime=0 WHERE charId=?");
  350. statement.setInt(1, objid);
  351. statement.execute();
  352. statement.close();
  353. }
  354. catch (Exception e)
  355. {
  356. _log.log(Level.SEVERE, "Error restoring character.", e);
  357. }
  358. finally
  359. {
  360. L2DatabaseFactory.close(con);
  361. }
  362. final LogRecord record = new LogRecord(Level.WARNING, "Restore");
  363. record.setParameters(new Object[] { objid, this });
  364. _logAccounting.log(record);
  365. }
  366. public static void deleteCharByObjId(int objid)
  367. {
  368. if (objid < 0)
  369. {
  370. return;
  371. }
  372. CharNameTable.getInstance().removeName(objid);
  373. Connection con = null;
  374. try
  375. {
  376. con = L2DatabaseFactory.getInstance().getConnection();
  377. PreparedStatement statement = con.prepareStatement("DELETE FROM character_contacts WHERE charId=? OR contactId=?");
  378. statement.setInt(1, objid);
  379. statement.setInt(2, objid);
  380. statement.execute();
  381. statement.close();
  382. statement = con.prepareStatement("DELETE FROM character_friends WHERE charId=? OR friendId=?");
  383. statement.setInt(1, objid);
  384. statement.setInt(2, objid);
  385. statement.execute();
  386. statement.close();
  387. statement = con.prepareStatement("DELETE FROM character_hennas WHERE charId=?");
  388. statement.setInt(1, objid);
  389. statement.execute();
  390. statement.close();
  391. statement = con.prepareStatement("DELETE FROM character_macroses WHERE charId=?");
  392. statement.setInt(1, objid);
  393. statement.execute();
  394. statement.close();
  395. statement = con.prepareStatement("DELETE FROM character_quests WHERE charId=?");
  396. statement.setInt(1, objid);
  397. statement.execute();
  398. statement.close();
  399. statement = con.prepareStatement("DELETE FROM character_quest_global_data WHERE charId=?");
  400. statement.setInt(1, objid);
  401. statement.executeUpdate();
  402. statement.close();
  403. statement = con.prepareStatement("DELETE FROM character_recipebook WHERE charId=?");
  404. statement.setInt(1, objid);
  405. statement.execute();
  406. statement.close();
  407. statement = con.prepareStatement("DELETE FROM character_shortcuts WHERE charId=?");
  408. statement.setInt(1, objid);
  409. statement.execute();
  410. statement.close();
  411. statement = con.prepareStatement("DELETE FROM character_skills WHERE charId=?");
  412. statement.setInt(1, objid);
  413. statement.execute();
  414. statement.close();
  415. statement = con.prepareStatement("DELETE FROM character_skills_save WHERE charId=?");
  416. statement.setInt(1, objid);
  417. statement.execute();
  418. statement.close();
  419. statement = con.prepareStatement("DELETE FROM character_subclasses WHERE charId=?");
  420. statement.setInt(1, objid);
  421. statement.execute();
  422. statement.close();
  423. statement = con.prepareStatement("DELETE FROM heroes WHERE charId=?");
  424. statement.setInt(1, objid);
  425. statement.execute();
  426. statement.close();
  427. statement = con.prepareStatement("DELETE FROM olympiad_nobles WHERE charId=?");
  428. statement.setInt(1, objid);
  429. statement.execute();
  430. statement.close();
  431. statement = con.prepareStatement("DELETE FROM seven_signs WHERE charId=?");
  432. statement.setInt(1, objid);
  433. statement.execute();
  434. statement.close();
  435. statement = con.prepareStatement("DELETE FROM pets WHERE item_obj_id IN (SELECT object_id FROM items WHERE items.owner_id=?)");
  436. statement.setInt(1, objid);
  437. statement.execute();
  438. statement.close();
  439. statement = con.prepareStatement("DELETE FROM item_attributes WHERE itemId IN (SELECT object_id FROM items WHERE items.owner_id=?)");
  440. statement.setInt(1, objid);
  441. statement.execute();
  442. statement.close();
  443. statement = con.prepareStatement("DELETE FROM items WHERE owner_id=?");
  444. statement.setInt(1, objid);
  445. statement.execute();
  446. statement.close();
  447. statement = con.prepareStatement("DELETE FROM merchant_lease WHERE player_id=?");
  448. statement.setInt(1, objid);
  449. statement.execute();
  450. statement.close();
  451. statement = con.prepareStatement("DELETE FROM character_raid_points WHERE charId=?");
  452. statement.setInt(1, objid);
  453. statement.execute();
  454. statement.close();
  455. statement = con.prepareStatement("DELETE FROM character_reco_bonus WHERE charId=?");
  456. statement.setInt(1, objid);
  457. statement.execute();
  458. statement.close();
  459. statement = con.prepareStatement("DELETE FROM character_instance_time WHERE charId=?");
  460. statement.setInt(1, objid);
  461. statement.execute();
  462. statement.close();
  463. statement = con.prepareStatement("DELETE FROM characters WHERE charId=?");
  464. statement.setInt(1, objid);
  465. statement.execute();
  466. statement.close();
  467. }
  468. catch (Exception e)
  469. {
  470. _log.log(Level.SEVERE, "Error deleting character.", e);
  471. }
  472. finally
  473. {
  474. L2DatabaseFactory.close(con);
  475. }
  476. }
  477. public L2PcInstance loadCharFromDisk(int charslot)
  478. {
  479. final int objId = getObjectIdForSlot(charslot);
  480. if (objId < 0)
  481. {
  482. return null;
  483. }
  484. L2PcInstance character = L2World.getInstance().getPlayer(objId);
  485. if (character != null)
  486. {
  487. // exploit prevention, should not happens in normal way
  488. _log.severe("Attempt of double login: " + character.getName() + "(" + objId + ") " + getAccountName());
  489. if (character.getClient() != null)
  490. {
  491. character.getClient().closeNow();
  492. }
  493. else
  494. {
  495. character.deleteMe();
  496. }
  497. return null;
  498. }
  499. character = L2PcInstance.load(objId);
  500. if (character != null)
  501. {
  502. // preinit some values for each login
  503. character.setRunning(); // running is default
  504. character.standUp(); // standing is default
  505. character.refreshOverloaded();
  506. character.refreshExpertisePenalty();
  507. character.setOnlineStatus(true, false);
  508. }
  509. else
  510. {
  511. _log.severe("could not restore in slot: " + charslot);
  512. }
  513. //setCharacter(character);
  514. return character;
  515. }
  516. /**
  517. * @param chars
  518. */
  519. public void setCharSelection(CharSelectInfoPackage[] chars)
  520. {
  521. _charSlotMapping = chars;
  522. }
  523. public CharSelectInfoPackage getCharSelection(int charslot)
  524. {
  525. if ((_charSlotMapping == null) || (charslot < 0) || (charslot >= _charSlotMapping.length))
  526. {
  527. return null;
  528. }
  529. return _charSlotMapping[charslot];
  530. }
  531. public SecondaryPasswordAuth getSecondaryAuth()
  532. {
  533. return _secondaryAuth;
  534. }
  535. public void close(L2GameServerPacket gsp)
  536. {
  537. if (getConnection() == null)
  538. {
  539. return; // ofline shop
  540. }
  541. if (_aditionalClosePacket != null)
  542. {
  543. getConnection().close(new L2GameServerPacket[] { _aditionalClosePacket, gsp });
  544. }
  545. else
  546. {
  547. getConnection().close(gsp);
  548. }
  549. }
  550. public void close(L2GameServerPacket[] gspArray)
  551. {
  552. if (getConnection() == null)
  553. {
  554. return; // ofline shop
  555. }
  556. getConnection().close(gspArray);
  557. }
  558. /**
  559. * @param charslot
  560. * @return
  561. */
  562. private int getObjectIdForSlot(int charslot)
  563. {
  564. final CharSelectInfoPackage info = getCharSelection(charslot);
  565. if (info == null)
  566. {
  567. _log.warning(toString() + " tried to delete Character in slot " + charslot + " but no characters exits at that slot.");
  568. return -1;
  569. }
  570. return info.getObjectId();
  571. }
  572. @Override
  573. protected void onForcedDisconnection()
  574. {
  575. LogRecord record = new LogRecord(Level.WARNING, "Disconnected abnormally");
  576. record.setParameters(new Object[] { this });
  577. _logAccounting.log(record);
  578. }
  579. @Override
  580. protected void onDisconnection()
  581. {
  582. // no long running tasks here, do it async
  583. try
  584. {
  585. ThreadPoolManager.getInstance().executeTask(new DisconnectTask());
  586. }
  587. catch (RejectedExecutionException e)
  588. {
  589. // server is closing
  590. }
  591. }
  592. /**
  593. * Close client connection with {@link ServerClose} packet
  594. */
  595. public void closeNow()
  596. {
  597. _isDetached = true; // prevents more packets execution
  598. close(ServerClose.STATIC_PACKET);
  599. synchronized (this)
  600. {
  601. if (_cleanupTask != null)
  602. {
  603. cancelCleanup();
  604. }
  605. _cleanupTask = ThreadPoolManager.getInstance().scheduleGeneral(new CleanupTask(), 0); //instant
  606. }
  607. }
  608. /**
  609. * Produces the best possible string representation of this client.
  610. */
  611. @Override
  612. public String toString()
  613. {
  614. try
  615. {
  616. final InetAddress address = getConnection().getInetAddress();
  617. switch (getState())
  618. {
  619. case CONNECTED:
  620. return "[IP: " + (address == null ? "disconnected" : address.getHostAddress()) + "]";
  621. case AUTHED:
  622. return "[Account: " + getAccountName() + " - IP: " + (address == null ? "disconnected" : address.getHostAddress()) + "]";
  623. case IN_GAME:
  624. return "[Character: " + (getActiveChar() == null ? "disconnected" : getActiveChar().getName() + "[" + getActiveChar().getObjectId() + "]") + " - Account: " + getAccountName() + " - IP: " + (address == null ? "disconnected" : address.getHostAddress()) + "]";
  625. default:
  626. throw new IllegalStateException("Missing state on switch");
  627. }
  628. }
  629. catch (NullPointerException e)
  630. {
  631. return "[Character read failed due to disconnect]";
  632. }
  633. }
  634. private class DisconnectTask implements Runnable
  635. {
  636. /**
  637. * @see java.lang.Runnable#run()
  638. */
  639. @Override
  640. public void run()
  641. {
  642. boolean fast = true;
  643. try
  644. {
  645. if ((getActiveChar() != null) && !isDetached())
  646. {
  647. setDetached(true);
  648. if (offlineMode(getActiveChar()))
  649. {
  650. getActiveChar().leaveParty();
  651. // If the L2PcInstance has Pet, unsummon it
  652. if (getActiveChar().getPet() != null)
  653. {
  654. getActiveChar().getPet().setRestoreSummon(true);
  655. getActiveChar().getPet().unSummon(getActiveChar());
  656. // Dead pet wasn't unsummoned, broadcast npcinfo changes (pet will be without owner name - means owner offline)
  657. if (getActiveChar().getPet() != null)
  658. {
  659. getActiveChar().getPet().broadcastNpcInfo(0);
  660. }
  661. }
  662. if (Config.OFFLINE_SET_NAME_COLOR)
  663. {
  664. getActiveChar().getAppearance().setNameColor(Config.OFFLINE_NAME_COLOR);
  665. getActiveChar().broadcastUserInfo();
  666. }
  667. if (getActiveChar().getOfflineStartTime() == 0)
  668. {
  669. getActiveChar().setOfflineStartTime(System.currentTimeMillis());
  670. }
  671. final LogRecord record = new LogRecord(Level.INFO, "Entering offline mode");
  672. record.setParameters(new Object[] { L2GameClient.this });
  673. _logAccounting.log(record);
  674. return;
  675. }
  676. fast = !getActiveChar().isInCombat() && !getActiveChar().isLocked();
  677. }
  678. cleanMe(fast);
  679. }
  680. catch (Exception e1)
  681. {
  682. _log.log(Level.WARNING, "Error while disconnecting client.", e1);
  683. }
  684. }
  685. }
  686. /**
  687. * @param player the player to be check.
  688. * @return {@code true} if the player is allowed to remain as off-line shop.
  689. */
  690. private boolean offlineMode(L2PcInstance player)
  691. {
  692. boolean canSetShop = false;
  693. if (player.isInOlympiadMode() || player.isFestivalParticipant() || TvTEvent.isPlayerParticipant(player.getObjectId()) || player.isInJail() || (player.getVehicle() != null))
  694. {
  695. return false;
  696. }
  697. if (Config.OFFLINE_TRADE_ENABLE && ((player.getPrivateStoreType() == L2PcInstance.STORE_PRIVATE_SELL) || (player.getPrivateStoreType() == L2PcInstance.STORE_PRIVATE_BUY)))
  698. {
  699. canSetShop = true;
  700. }
  701. else if (Config.OFFLINE_CRAFT_ENABLE && (player.isInCraftMode() || (player.getPrivateStoreType() == L2PcInstance.STORE_PRIVATE_MANUFACTURE)))
  702. {
  703. canSetShop = true;
  704. }
  705. if (Config.OFFLINE_MODE_IN_PEACE_ZONE && !player.isInsideZone(L2Character.ZONE_PEACE))
  706. {
  707. canSetShop = false;
  708. }
  709. return canSetShop;
  710. }
  711. public void cleanMe(boolean fast)
  712. {
  713. try
  714. {
  715. synchronized (this)
  716. {
  717. if (_cleanupTask == null)
  718. {
  719. _cleanupTask = ThreadPoolManager.getInstance().scheduleGeneral(new CleanupTask(), fast ? 5 : 15000L);
  720. }
  721. }
  722. }
  723. catch (Exception e1)
  724. {
  725. _log.log(Level.WARNING, "Error during cleanup.", e1);
  726. }
  727. }
  728. private class CleanupTask implements Runnable
  729. {
  730. /**
  731. * @see java.lang.Runnable#run()
  732. */
  733. @Override
  734. public void run()
  735. {
  736. try
  737. {
  738. // we are going to manually save the char bellow thus we can force the cancel
  739. if (_autoSaveInDB != null)
  740. {
  741. _autoSaveInDB.cancel(true);
  742. //ThreadPoolManager.getInstance().removeGeneral((Runnable) _autoSaveInDB);
  743. }
  744. if (getActiveChar() != null) // this should only happen on connection loss
  745. {
  746. if (getActiveChar().isLocked())
  747. {
  748. _log.log(Level.WARNING, "Player " + getActiveChar().getName() + " still performing subclass actions during disconnect.");
  749. }
  750. // we store all data from players who are disconnected while in an event in order to restore it in the next login
  751. if (L2Event.isParticipant(getActiveChar()))
  752. {
  753. L2Event.savePlayerEventStatus(getActiveChar());
  754. }
  755. // prevent closing again
  756. getActiveChar().setClient(null);
  757. if (getActiveChar().isOnline())
  758. {
  759. getActiveChar().deleteMe();
  760. AntiFeedManager.getInstance().onDisconnect(L2GameClient.this);
  761. }
  762. }
  763. setActiveChar(null);
  764. }
  765. catch (Exception e1)
  766. {
  767. _log.log(Level.WARNING, "Error while cleanup client.", e1);
  768. }
  769. finally
  770. {
  771. LoginServerThread.getInstance().sendLogout(getAccountName());
  772. }
  773. }
  774. }
  775. private class AutoSaveTask implements Runnable
  776. {
  777. @Override
  778. public void run()
  779. {
  780. try
  781. {
  782. L2PcInstance player = getActiveChar();
  783. if ((player != null) && player.isOnline()) // safety precaution
  784. {
  785. saveCharToDisk();
  786. if (player.getPet() != null)
  787. {
  788. player.getPet().store();
  789. }
  790. }
  791. }
  792. catch (Exception e)
  793. {
  794. _log.log(Level.SEVERE, "Error on AutoSaveTask.", e);
  795. }
  796. }
  797. }
  798. public boolean isProtocolOk()
  799. {
  800. return _protocol;
  801. }
  802. public void setProtocolOk(boolean b)
  803. {
  804. _protocol = b;
  805. }
  806. public boolean handleCheat(String punishment)
  807. {
  808. if (_activeChar != null)
  809. {
  810. Util.handleIllegalPlayerAction(_activeChar, toString() + ": " + punishment, Config.DEFAULT_PUNISH);
  811. return true;
  812. }
  813. Logger _logAudit = Logger.getLogger("audit");
  814. _logAudit.log(Level.INFO, "AUDIT: Client " + toString() + " kicked for reason: " + punishment);
  815. closeNow();
  816. return false;
  817. }
  818. /**
  819. * Returns false if client can receive packets.
  820. * True if detached, or flood detected, or queue overflow detected and queue still not empty.
  821. */
  822. public boolean dropPacket()
  823. {
  824. if (_isDetached)
  825. {
  826. return true;
  827. }
  828. // flood protection
  829. if (getStats().countPacket(_packetQueue.size()))
  830. {
  831. sendPacket(ActionFailed.STATIC_PACKET);
  832. return true;
  833. }
  834. return getStats().dropPacket();
  835. }
  836. /**
  837. * Counts buffer underflow exceptions.
  838. */
  839. public void onBufferUnderflow()
  840. {
  841. if (getStats().countUnderflowException())
  842. {
  843. _log.severe("Client " + toString() + " - Disconnected: Too many buffer underflow exceptions.");
  844. closeNow();
  845. return;
  846. }
  847. if (_state == GameClientState.CONNECTED) // in CONNECTED state kick client immediately
  848. {
  849. if (Config.PACKET_HANDLER_DEBUG)
  850. {
  851. _log.severe("Client " + toString() + " - Disconnected, too many buffer underflows in non-authed state.");
  852. }
  853. closeNow();
  854. }
  855. }
  856. /**
  857. * Counts unknown packets
  858. */
  859. public void onUnknownPacket()
  860. {
  861. if (getStats().countUnknownPacket())
  862. {
  863. _log.severe("Client " + toString() + " - Disconnected: Too many unknown packets.");
  864. closeNow();
  865. return;
  866. }
  867. if (_state == GameClientState.CONNECTED) // in CONNECTED state kick client immediately
  868. {
  869. if (Config.PACKET_HANDLER_DEBUG)
  870. {
  871. _log.severe("Client " + toString() + " - Disconnected, too many unknown packets in non-authed state.");
  872. }
  873. closeNow();
  874. }
  875. }
  876. /**
  877. * Add packet to the queue and start worker thread if needed
  878. */
  879. public void execute(ReceivablePacket<L2GameClient> packet)
  880. {
  881. if (getStats().countFloods())
  882. {
  883. _log.severe("Client " + toString() + " - Disconnected, too many floods:" + getStats().longFloods + " long and " + getStats().shortFloods + " short.");
  884. closeNow();
  885. return;
  886. }
  887. if (!_packetQueue.offer(packet))
  888. {
  889. if (getStats().countQueueOverflow())
  890. {
  891. _log.severe("Client " + toString() + " - Disconnected, too many queue overflows.");
  892. closeNow();
  893. }
  894. else
  895. {
  896. sendPacket(ActionFailed.STATIC_PACKET);
  897. }
  898. return;
  899. }
  900. if (_queueLock.isLocked())
  901. {
  902. return;
  903. }
  904. try
  905. {
  906. if (_state == GameClientState.CONNECTED)
  907. {
  908. if (getStats().processedPackets > 3)
  909. {
  910. if (Config.PACKET_HANDLER_DEBUG)
  911. {
  912. _log.severe("Client " + toString() + " - Disconnected, too many packets in non-authed state.");
  913. }
  914. closeNow();
  915. return;
  916. }
  917. ThreadPoolManager.getInstance().executeIOPacket(this);
  918. }
  919. else
  920. {
  921. ThreadPoolManager.getInstance().executePacket(this);
  922. }
  923. }
  924. catch (RejectedExecutionException e)
  925. {
  926. // if the server is shutdown we ignore
  927. if (!ThreadPoolManager.getInstance().isShutdown())
  928. {
  929. _log.severe("Failed executing: " + packet.getClass().getSimpleName() + " for Client: " + toString());
  930. }
  931. }
  932. }
  933. @Override
  934. public void run()
  935. {
  936. if (!_queueLock.tryLock())
  937. {
  938. return;
  939. }
  940. try
  941. {
  942. int count = 0;
  943. ReceivablePacket<L2GameClient> packet;
  944. while (true)
  945. {
  946. packet = _packetQueue.poll();
  947. if (packet == null)
  948. {
  949. return;
  950. }
  951. if (_isDetached) // clear queue immediately after detach
  952. {
  953. _packetQueue.clear();
  954. return;
  955. }
  956. try
  957. {
  958. packet.run();
  959. }
  960. catch (Exception e)
  961. {
  962. _log.severe("Exception during execution " + packet.getClass().getSimpleName() + ", client: " + toString() + "," + e.getMessage());
  963. }
  964. count++;
  965. if (getStats().countBurst(count))
  966. {
  967. return;
  968. }
  969. }
  970. }
  971. finally
  972. {
  973. _queueLock.unlock();
  974. }
  975. }
  976. public void setClientTracert(int[][] tracert)
  977. {
  978. trace = tracert;
  979. }
  980. public int[][] getTrace()
  981. {
  982. return trace;
  983. }
  984. private boolean cancelCleanup()
  985. {
  986. final Future<?> task = _cleanupTask;
  987. if (task != null)
  988. {
  989. _cleanupTask = null;
  990. return task.cancel(true);
  991. }
  992. return false;
  993. }
  994. public void setAditionalClosePacket(L2GameServerPacket aditionalClosePacket)
  995. {
  996. _aditionalClosePacket = aditionalClosePacket;
  997. }
  998. }