L2GameClient.java 29 KB

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