L2GameClient.java 28 KB

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