L2GameClient.java 28 KB

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