L2GameClient.java 28 KB

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