L2GameClient.java 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  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().store();
  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 characters WHERE charId=?"))
  479. {
  480. ps.setInt(1, objid);
  481. ps.execute();
  482. }
  483. if (Config.L2JMOD_ALLOW_WEDDING)
  484. {
  485. try (PreparedStatement ps = con.prepareStatement("DELETE FROM mods_wedding WHERE player1Id = ? OR player2Id = ?"))
  486. {
  487. ps.setInt(1, objid);
  488. ps.setInt(2, objid);
  489. ps.execute();
  490. }
  491. }
  492. }
  493. catch (Exception e)
  494. {
  495. _log.log(Level.SEVERE, "Error deleting character.", e);
  496. }
  497. }
  498. public L2PcInstance loadCharFromDisk(int charslot)
  499. {
  500. final int objId = getObjectIdForSlot(charslot);
  501. if (objId < 0)
  502. {
  503. return null;
  504. }
  505. L2PcInstance character = L2World.getInstance().getPlayer(objId);
  506. if (character != null)
  507. {
  508. // exploit prevention, should not happens in normal way
  509. _log.severe("Attempt of double login: " + character.getName() + "(" + objId + ") " + getAccountName());
  510. if (character.getClient() != null)
  511. {
  512. character.getClient().closeNow();
  513. }
  514. else
  515. {
  516. character.deleteMe();
  517. }
  518. return null;
  519. }
  520. character = L2PcInstance.load(objId);
  521. if (character != null)
  522. {
  523. // preinit some values for each login
  524. character.setRunning(); // running is default
  525. character.standUp(); // standing is default
  526. character.refreshOverloaded();
  527. character.refreshExpertisePenalty();
  528. character.setOnlineStatus(true, false);
  529. }
  530. else
  531. {
  532. _log.severe("could not restore in slot: " + charslot);
  533. }
  534. // setCharacter(character);
  535. return character;
  536. }
  537. /**
  538. * @param chars
  539. */
  540. public void setCharSelection(CharSelectInfoPackage[] chars)
  541. {
  542. _charSlotMapping = chars;
  543. }
  544. public CharSelectInfoPackage getCharSelection(int charslot)
  545. {
  546. if ((_charSlotMapping == null) || (charslot < 0) || (charslot >= _charSlotMapping.length))
  547. {
  548. return null;
  549. }
  550. return _charSlotMapping[charslot];
  551. }
  552. public SecondaryPasswordAuth getSecondaryAuth()
  553. {
  554. return _secondaryAuth;
  555. }
  556. public void close(L2GameServerPacket gsp)
  557. {
  558. if (getConnection() == null)
  559. {
  560. return; // ofline shop
  561. }
  562. if (_aditionalClosePacket != null)
  563. {
  564. getConnection().close(new L2GameServerPacket[]
  565. {
  566. _aditionalClosePacket,
  567. gsp
  568. });
  569. }
  570. else
  571. {
  572. getConnection().close(gsp);
  573. }
  574. }
  575. public void close(L2GameServerPacket[] gspArray)
  576. {
  577. if (getConnection() == null)
  578. {
  579. return; // ofline shop
  580. }
  581. getConnection().close(gspArray);
  582. }
  583. /**
  584. * @param charslot
  585. * @return
  586. */
  587. private int getObjectIdForSlot(int charslot)
  588. {
  589. final CharSelectInfoPackage info = getCharSelection(charslot);
  590. if (info == null)
  591. {
  592. _log.warning(toString() + " tried to delete Character in slot " + charslot + " but no characters exits at that slot.");
  593. return -1;
  594. }
  595. return info.getObjectId();
  596. }
  597. @Override
  598. protected void onForcedDisconnection()
  599. {
  600. LogRecord record = new LogRecord(Level.WARNING, "Disconnected abnormally");
  601. record.setParameters(new Object[]
  602. {
  603. this
  604. });
  605. _logAccounting.log(record);
  606. }
  607. @Override
  608. protected void onDisconnection()
  609. {
  610. // no long running tasks here, do it async
  611. try
  612. {
  613. ThreadPoolManager.getInstance().executeTask(new DisconnectTask());
  614. }
  615. catch (RejectedExecutionException e)
  616. {
  617. // server is closing
  618. }
  619. }
  620. /**
  621. * Close client connection with {@link ServerClose} packet
  622. */
  623. public void closeNow()
  624. {
  625. _isDetached = true; // prevents more packets execution
  626. close(ServerClose.STATIC_PACKET);
  627. synchronized (this)
  628. {
  629. if (_cleanupTask != null)
  630. {
  631. cancelCleanup();
  632. }
  633. _cleanupTask = ThreadPoolManager.getInstance().scheduleGeneral(new CleanupTask(), 0); // instant
  634. }
  635. }
  636. /**
  637. * Produces the best possible string representation of this client.
  638. */
  639. @Override
  640. public String toString()
  641. {
  642. try
  643. {
  644. final InetAddress address = getConnection().getInetAddress();
  645. switch (getState())
  646. {
  647. case CONNECTED:
  648. return "[IP: " + (address == null ? "disconnected" : address.getHostAddress()) + "]";
  649. case AUTHED:
  650. return "[Account: " + getAccountName() + " - IP: " + (address == null ? "disconnected" : address.getHostAddress()) + "]";
  651. case IN_GAME:
  652. return "[Character: " + (getActiveChar() == null ? "disconnected" : getActiveChar().getName() + "[" + getActiveChar().getObjectId() + "]") + " - Account: " + getAccountName() + " - IP: " + (address == null ? "disconnected" : address.getHostAddress()) + "]";
  653. default:
  654. throw new IllegalStateException("Missing state on switch");
  655. }
  656. }
  657. catch (NullPointerException e)
  658. {
  659. return "[Character read failed due to disconnect]";
  660. }
  661. }
  662. protected class DisconnectTask implements Runnable
  663. {
  664. @Override
  665. public void run()
  666. {
  667. boolean fast = true;
  668. try
  669. {
  670. if ((getActiveChar() != null) && !isDetached())
  671. {
  672. getActiveChar().storeZoneRestartLimitTime();
  673. setDetached(true);
  674. if (offlineMode(getActiveChar()))
  675. {
  676. getActiveChar().leaveParty();
  677. // If the L2PcInstance has Pet, unsummon it
  678. if (getActiveChar().hasSummon())
  679. {
  680. getActiveChar().getSummon().setRestoreSummon(true);
  681. getActiveChar().getSummon().unSummon(getActiveChar());
  682. // Dead pet wasn't unsummoned, broadcast npcinfo changes (pet will be without owner name - means owner offline)
  683. if (getActiveChar().getSummon() != null)
  684. {
  685. getActiveChar().getSummon().broadcastNpcInfo(0);
  686. }
  687. }
  688. if (Config.OFFLINE_SET_NAME_COLOR)
  689. {
  690. getActiveChar().getAppearance().setNameColor(Config.OFFLINE_NAME_COLOR);
  691. getActiveChar().broadcastUserInfo();
  692. }
  693. if (getActiveChar().getOfflineStartTime() == 0)
  694. {
  695. getActiveChar().setOfflineStartTime(System.currentTimeMillis());
  696. }
  697. final LogRecord record = new LogRecord(Level.INFO, "Entering offline mode");
  698. record.setParameters(new Object[]
  699. {
  700. L2GameClient.this
  701. });
  702. _logAccounting.log(record);
  703. return;
  704. }
  705. fast = !getActiveChar().isInCombat() && !getActiveChar().isLocked();
  706. }
  707. cleanMe(fast);
  708. }
  709. catch (Exception e1)
  710. {
  711. _log.log(Level.WARNING, "Error while disconnecting client.", e1);
  712. }
  713. }
  714. }
  715. /**
  716. * @param player the player to be check.
  717. * @return {@code true} if the player is allowed to remain as off-line shop.
  718. */
  719. protected boolean offlineMode(L2PcInstance player)
  720. {
  721. boolean canSetShop = false;
  722. if (player.isInOlympiadMode() || player.isFestivalParticipant() || player.isBlockedFromExit() || player.isJailed() || (player.getVehicle() != null))
  723. {
  724. return false;
  725. }
  726. if (Config.OFFLINE_TRADE_ENABLE && ((player.getPrivateStoreType() == L2PcInstance.STORE_PRIVATE_SELL) || (player.getPrivateStoreType() == L2PcInstance.STORE_PRIVATE_BUY)))
  727. {
  728. canSetShop = true;
  729. }
  730. else if (Config.OFFLINE_CRAFT_ENABLE && (player.isInCraftMode() || (player.getPrivateStoreType() == L2PcInstance.STORE_PRIVATE_MANUFACTURE)))
  731. {
  732. canSetShop = true;
  733. }
  734. if (Config.OFFLINE_MODE_IN_PEACE_ZONE && !player.isInsideZone(ZoneId.PEACE))
  735. {
  736. canSetShop = false;
  737. }
  738. return canSetShop;
  739. }
  740. public void cleanMe(boolean fast)
  741. {
  742. try
  743. {
  744. synchronized (this)
  745. {
  746. if (_cleanupTask == null)
  747. {
  748. _cleanupTask = ThreadPoolManager.getInstance().scheduleGeneral(new CleanupTask(), fast ? 5 : 15000L);
  749. }
  750. }
  751. }
  752. catch (Exception e1)
  753. {
  754. _log.log(Level.WARNING, "Error during cleanup.", e1);
  755. }
  756. }
  757. protected class CleanupTask implements Runnable
  758. {
  759. @Override
  760. public void run()
  761. {
  762. try
  763. {
  764. // we are going to manually save the char bellow thus we can force the cancel
  765. if (_autoSaveInDB != null)
  766. {
  767. _autoSaveInDB.cancel(true);
  768. // ThreadPoolManager.getInstance().removeGeneral((Runnable) _autoSaveInDB);
  769. }
  770. if (getActiveChar() != null) // this should only happen on connection loss
  771. {
  772. if (getActiveChar().isLocked())
  773. {
  774. _log.log(Level.WARNING, "Player " + getActiveChar().getName() + " still performing subclass actions during disconnect.");
  775. }
  776. // we store all data from players who are disconnected while in an event in order to restore it in the next login
  777. if (L2Event.isParticipant(getActiveChar()))
  778. {
  779. L2Event.savePlayerEventStatus(getActiveChar());
  780. }
  781. // prevent closing again
  782. getActiveChar().setClient(null);
  783. if (getActiveChar().isOnline())
  784. {
  785. getActiveChar().deleteMe();
  786. AntiFeedManager.getInstance().onDisconnect(L2GameClient.this);
  787. }
  788. }
  789. setActiveChar(null);
  790. }
  791. catch (Exception e1)
  792. {
  793. _log.log(Level.WARNING, "Error while cleanup client.", e1);
  794. }
  795. finally
  796. {
  797. LoginServerThread.getInstance().sendLogout(getAccountName());
  798. }
  799. }
  800. }
  801. protected class AutoSaveTask implements Runnable
  802. {
  803. @Override
  804. public void run()
  805. {
  806. try
  807. {
  808. L2PcInstance player = getActiveChar();
  809. if ((player != null) && player.isOnline()) // safety precaution
  810. {
  811. saveCharToDisk();
  812. if (player.hasSummon())
  813. {
  814. player.getSummon().store();
  815. }
  816. }
  817. }
  818. catch (Exception e)
  819. {
  820. _log.log(Level.SEVERE, "Error on AutoSaveTask.", e);
  821. }
  822. }
  823. }
  824. public boolean isProtocolOk()
  825. {
  826. return _protocol;
  827. }
  828. public void setProtocolOk(boolean b)
  829. {
  830. _protocol = b;
  831. }
  832. public boolean handleCheat(String punishment)
  833. {
  834. if (_activeChar != null)
  835. {
  836. Util.handleIllegalPlayerAction(_activeChar, toString() + ": " + punishment, Config.DEFAULT_PUNISH);
  837. return true;
  838. }
  839. Logger _logAudit = Logger.getLogger("audit");
  840. _logAudit.log(Level.INFO, "AUDIT: Client " + toString() + " kicked for reason: " + punishment);
  841. closeNow();
  842. return false;
  843. }
  844. /**
  845. * True if detached, or flood detected, or queue overflow detected and queue still not empty.
  846. * @return false if client can receive packets.
  847. */
  848. public boolean dropPacket()
  849. {
  850. if (_isDetached)
  851. {
  852. return true;
  853. }
  854. // flood protection
  855. if (getStats().countPacket(_packetQueue.size()))
  856. {
  857. sendPacket(ActionFailed.STATIC_PACKET);
  858. return true;
  859. }
  860. return getStats().dropPacket();
  861. }
  862. /**
  863. * Counts buffer underflow exceptions.
  864. */
  865. public void onBufferUnderflow()
  866. {
  867. if (getStats().countUnderflowException())
  868. {
  869. _log.severe("Client " + toString() + " - Disconnected: Too many buffer underflow exceptions.");
  870. closeNow();
  871. return;
  872. }
  873. if (_state == GameClientState.CONNECTED) // in CONNECTED state kick client immediately
  874. {
  875. if (Config.PACKET_HANDLER_DEBUG)
  876. {
  877. _log.severe("Client " + toString() + " - Disconnected, too many buffer underflows in non-authed state.");
  878. }
  879. closeNow();
  880. }
  881. }
  882. /**
  883. * Counts unknown packets
  884. */
  885. public void onUnknownPacket()
  886. {
  887. if (getStats().countUnknownPacket())
  888. {
  889. _log.severe("Client " + toString() + " - Disconnected: Too many unknown packets.");
  890. closeNow();
  891. return;
  892. }
  893. if (_state == GameClientState.CONNECTED) // in CONNECTED state kick client immediately
  894. {
  895. if (Config.PACKET_HANDLER_DEBUG)
  896. {
  897. _log.severe("Client " + toString() + " - Disconnected, too many unknown packets in non-authed state.");
  898. }
  899. closeNow();
  900. }
  901. }
  902. /**
  903. * Add packet to the queue and start worker thread if needed
  904. * @param packet
  905. */
  906. public void execute(ReceivablePacket<L2GameClient> packet)
  907. {
  908. if (getStats().countFloods())
  909. {
  910. _log.severe("Client " + toString() + " - Disconnected, too many floods:" + getStats().longFloods + " long and " + getStats().shortFloods + " short.");
  911. closeNow();
  912. return;
  913. }
  914. if (!_packetQueue.offer(packet))
  915. {
  916. if (getStats().countQueueOverflow())
  917. {
  918. _log.severe("Client " + toString() + " - Disconnected, too many queue overflows.");
  919. closeNow();
  920. }
  921. else
  922. {
  923. sendPacket(ActionFailed.STATIC_PACKET);
  924. }
  925. return;
  926. }
  927. if (_queueLock.isLocked())
  928. {
  929. return;
  930. }
  931. try
  932. {
  933. if (_state == GameClientState.CONNECTED)
  934. {
  935. if (getStats().processedPackets > 3)
  936. {
  937. if (Config.PACKET_HANDLER_DEBUG)
  938. {
  939. _log.severe("Client " + toString() + " - Disconnected, too many packets in non-authed state.");
  940. }
  941. closeNow();
  942. return;
  943. }
  944. ThreadPoolManager.getInstance().executeIOPacket(this);
  945. }
  946. else
  947. {
  948. ThreadPoolManager.getInstance().executePacket(this);
  949. }
  950. }
  951. catch (RejectedExecutionException e)
  952. {
  953. // if the server is shutdown we ignore
  954. if (!ThreadPoolManager.getInstance().isShutdown())
  955. {
  956. _log.severe("Failed executing: " + packet.getClass().getSimpleName() + " for Client: " + toString());
  957. }
  958. }
  959. }
  960. @Override
  961. public void run()
  962. {
  963. if (!_queueLock.tryLock())
  964. {
  965. return;
  966. }
  967. try
  968. {
  969. int count = 0;
  970. ReceivablePacket<L2GameClient> packet;
  971. while (true)
  972. {
  973. packet = _packetQueue.poll();
  974. if (packet == null)
  975. {
  976. return;
  977. }
  978. if (_isDetached) // clear queue immediately after detach
  979. {
  980. _packetQueue.clear();
  981. return;
  982. }
  983. try
  984. {
  985. packet.run();
  986. }
  987. catch (Exception e)
  988. {
  989. _log.severe("Exception during execution " + packet.getClass().getSimpleName() + ", client: " + toString() + "," + e.getMessage());
  990. }
  991. count++;
  992. if (getStats().countBurst(count))
  993. {
  994. return;
  995. }
  996. }
  997. }
  998. finally
  999. {
  1000. _queueLock.unlock();
  1001. }
  1002. }
  1003. public void setClientTracert(int[][] tracert)
  1004. {
  1005. trace = tracert;
  1006. }
  1007. public int[][] getTrace()
  1008. {
  1009. return trace;
  1010. }
  1011. private boolean cancelCleanup()
  1012. {
  1013. final Future<?> task = _cleanupTask;
  1014. if (task != null)
  1015. {
  1016. _cleanupTask = null;
  1017. return task.cancel(true);
  1018. }
  1019. return false;
  1020. }
  1021. public void setAditionalClosePacket(L2GameServerPacket aditionalClosePacket)
  1022. {
  1023. _aditionalClosePacket = aditionalClosePacket;
  1024. }
  1025. }