L2GameClient.java 28 KB

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