L2GameClient.java 27 KB

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