L2GameClient.java 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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.getPrivateStoreType() == L2PcInstance.STORE_PRIVATE_SELL) || (player.getPrivateStoreType() == L2PcInstance.STORE_PRIVATE_BUY)) && Config.OFFLINE_TRADE_ENABLE) || ((player.isInCraftMode() || (player.getPrivateStoreType() == L2PcInstance.STORE_PRIVATE_MANUFACTURE)) && Config.OFFLINE_CRAFT_ENABLE))
  626. {
  627. player.leaveParty();
  628. // If the L2PcInstance has Pet, unsummon it
  629. if (player.getPet() != null)
  630. {
  631. player.getPet().setRestoreSummon(true);
  632. player.getPet().unSummon(player);
  633. // dead pet wasnt unsummoned, broadcast npcinfo changes (pet will be without owner name - means owner offline)
  634. if (player.getPet() != null)
  635. player.getPet().broadcastNpcInfo(0);
  636. }
  637. if (Config.OFFLINE_SET_NAME_COLOR)
  638. {
  639. player.getAppearance().setNameColor(Config.OFFLINE_NAME_COLOR);
  640. player.broadcastUserInfo();
  641. }
  642. if (player.getOfflineStartTime() == 0)
  643. player.setOfflineStartTime(System.currentTimeMillis());
  644. LogRecord record = new LogRecord(Level.INFO, "Entering offline mode");
  645. record.setParameters(new Object[]{L2GameClient.this});
  646. _logAccounting.log(record);
  647. return;
  648. }
  649. }
  650. if (player.isInCombat() || player.isLocked())
  651. {
  652. fast = false;
  653. }
  654. }
  655. cleanMe(fast);
  656. }
  657. catch (Exception e1)
  658. {
  659. _log.log(Level.WARNING, "Error while disconnecting client.", e1);
  660. }
  661. }
  662. }
  663. public void cleanMe(boolean fast)
  664. {
  665. try
  666. {
  667. synchronized(this)
  668. {
  669. if (_cleanupTask == null)
  670. {
  671. _cleanupTask = ThreadPoolManager.getInstance().scheduleGeneral(new CleanupTask(), fast ? 5 : 15000L);
  672. }
  673. }
  674. }
  675. catch (Exception e1)
  676. {
  677. _log.log(Level.WARNING, "Error during cleanup.", e1);
  678. }
  679. }
  680. class CleanupTask implements Runnable
  681. {
  682. /**
  683. * @see java.lang.Runnable#run()
  684. */
  685. @Override
  686. public void run()
  687. {
  688. try
  689. {
  690. // we are going to manually save the char bellow thus we can force the cancel
  691. if (_autoSaveInDB != null)
  692. {
  693. _autoSaveInDB.cancel(true);
  694. //ThreadPoolManager.getInstance().removeGeneral((Runnable) _autoSaveInDB);
  695. }
  696. L2PcInstance player = L2GameClient.this.getActiveChar();
  697. if (player != null) // this should only happen on connection loss
  698. {
  699. if (player.isLocked())
  700. {
  701. _log.log(Level.WARNING, "Player "+player.getName()+" still performing subclass actions during disconnect.");
  702. }
  703. // we store all data from players who are disconnected while in an event in order to restore it in the next login
  704. if (L2Event.isParticipant(player))
  705. {
  706. L2Event.savePlayerEventStatus(player);
  707. }
  708. // prevent closing again
  709. player.setClient(null);
  710. if (player.isOnline())
  711. {
  712. player.deleteMe();
  713. AntiFeedManager.getInstance().onDisconnect(L2GameClient.this);
  714. }
  715. }
  716. L2GameClient.this.setActiveChar(null);
  717. }
  718. catch (Exception e1)
  719. {
  720. _log.log(Level.WARNING, "Error while cleanup client.", e1);
  721. }
  722. finally
  723. {
  724. LoginServerThread.getInstance().sendLogout(L2GameClient.this.getAccountName());
  725. }
  726. }
  727. }
  728. class AutoSaveTask implements Runnable
  729. {
  730. @Override
  731. public void run()
  732. {
  733. try
  734. {
  735. L2PcInstance player = L2GameClient.this.getActiveChar();
  736. if (player != null && player.isOnline()) // safety precaution
  737. {
  738. saveCharToDisk();
  739. if (player.getPet() != null)
  740. player.getPet().store();
  741. }
  742. }
  743. catch (Exception e)
  744. {
  745. _log.log(Level.SEVERE, "Error on AutoSaveTask.", e);
  746. }
  747. }
  748. }
  749. public boolean isProtocolOk()
  750. {
  751. return _protocol;
  752. }
  753. public void setProtocolOk(boolean b)
  754. {
  755. _protocol = b;
  756. }
  757. public boolean handleCheat(String punishment)
  758. {
  759. if (_activeChar != null)
  760. {
  761. Util.handleIllegalPlayerAction(_activeChar, toString()+": "+punishment, Config.DEFAULT_PUNISH);
  762. return true;
  763. }
  764. Logger _logAudit = Logger.getLogger("audit");
  765. _logAudit.log(Level.INFO, "AUDIT: Client "+toString()+" kicked for reason: "+punishment);
  766. closeNow();
  767. return false;
  768. }
  769. /**
  770. * Returns false if client can receive packets.
  771. * True if detached, or flood detected, or queue overflow detected and queue still not empty.
  772. */
  773. public boolean dropPacket()
  774. {
  775. if (_isDetached) // detached clients can't receive any packets
  776. return true;
  777. // flood protection
  778. if (getStats().countPacket(_packetQueue.size()))
  779. {
  780. sendPacket(ActionFailed.STATIC_PACKET);
  781. return true;
  782. }
  783. return getStats().dropPacket();
  784. }
  785. /**
  786. * Counts buffer underflow exceptions.
  787. */
  788. public void onBufferUnderflow()
  789. {
  790. if (getStats().countUnderflowException())
  791. {
  792. _log.severe("Client " + toString() + " - Disconnected: Too many buffer underflow exceptions.");
  793. closeNow();
  794. return;
  795. }
  796. if (_state == GameClientState.CONNECTED) // in CONNECTED state kick client immediately
  797. {
  798. if (Config.PACKET_HANDLER_DEBUG)
  799. _log.severe("Client " + toString() + " - Disconnected, too many buffer underflows in non-authed state.");
  800. closeNow();
  801. }
  802. }
  803. /**
  804. * Counts unknown packets
  805. */
  806. public void onUnknownPacket()
  807. {
  808. if (getStats().countUnknownPacket())
  809. {
  810. _log.severe("Client " + toString() + " - Disconnected: Too many unknown packets.");
  811. closeNow();
  812. return;
  813. }
  814. if (_state == GameClientState.CONNECTED) // in CONNECTED state kick client immediately
  815. {
  816. if (Config.PACKET_HANDLER_DEBUG)
  817. _log.severe("Client " + toString() + " - Disconnected, too many unknown packets in non-authed state.");
  818. closeNow();
  819. }
  820. }
  821. /**
  822. * Add packet to the queue and start worker thread if needed
  823. */
  824. public void execute(ReceivablePacket<L2GameClient> packet)
  825. {
  826. if (getStats().countFloods())
  827. {
  828. _log.severe("Client " + toString() + " - Disconnected, too many floods:"+getStats().longFloods+" long and "+getStats().shortFloods+" short.");
  829. closeNow();
  830. return;
  831. }
  832. if (!_packetQueue.offer(packet))
  833. {
  834. if (getStats().countQueueOverflow())
  835. {
  836. _log.severe("Client " + toString() + " - Disconnected, too many queue overflows.");
  837. closeNow();
  838. }
  839. else
  840. sendPacket(ActionFailed.STATIC_PACKET);
  841. return;
  842. }
  843. if (_queueLock.isLocked()) // already processing
  844. return;
  845. try
  846. {
  847. if (_state == GameClientState.CONNECTED)
  848. {
  849. if (getStats().processedPackets > 3)
  850. {
  851. if (Config.PACKET_HANDLER_DEBUG)
  852. _log.severe("Client " + toString() + " - Disconnected, too many packets in non-authed state.");
  853. closeNow();
  854. return;
  855. }
  856. ThreadPoolManager.getInstance().executeIOPacket(this);
  857. }
  858. else
  859. ThreadPoolManager.getInstance().executePacket(this);
  860. }
  861. catch (RejectedExecutionException e)
  862. {
  863. // if the server is shutdown we ignore
  864. if (!ThreadPoolManager.getInstance().isShutdown())
  865. {
  866. _log.severe("Failed executing: "+packet.getClass().getSimpleName()+" for Client: "+toString());
  867. }
  868. }
  869. }
  870. @Override
  871. public void run()
  872. {
  873. if (!_queueLock.tryLock())
  874. return;
  875. try
  876. {
  877. int count = 0;
  878. while (true)
  879. {
  880. final ReceivablePacket<L2GameClient> packet = _packetQueue.poll();
  881. if (packet == null) // queue is empty
  882. return;
  883. if (_isDetached) // clear queue immediately after detach
  884. {
  885. _packetQueue.clear();
  886. return;
  887. }
  888. try
  889. {
  890. packet.run();
  891. }
  892. catch (Exception e)
  893. {
  894. _log.severe("Exception during execution "+packet.getClass().getSimpleName()+", client: "+toString()+","+e.getMessage());
  895. }
  896. count++;
  897. if (getStats().countBurst(count))
  898. return;
  899. }
  900. }
  901. finally
  902. {
  903. _queueLock.unlock();
  904. }
  905. }
  906. public void setClientTracert(int[][] tracert)
  907. {
  908. trace = tracert;
  909. }
  910. public int[][] getTrace()
  911. {
  912. return trace;
  913. }
  914. private boolean cancelCleanup()
  915. {
  916. Future<?> task = _cleanupTask;
  917. if (task != null)
  918. {
  919. _cleanupTask = null;
  920. return task.cancel(true);
  921. }
  922. return false;
  923. }
  924. public void setAditionalClosePacket(L2GameServerPacket _aditionalClosePacket)
  925. {
  926. this._aditionalClosePacket = _aditionalClosePacket;
  927. }
  928. }