L2GameClient.java 28 KB

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