L2GameClient.java 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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<>(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. protected class DisconnectTask implements Runnable
  643. {
  644. @Override
  645. public void run()
  646. {
  647. boolean fast = true;
  648. try
  649. {
  650. if ((getActiveChar() != null) && !isDetached())
  651. {
  652. getActiveChar().storeZoneRestartLimitTime();
  653. setDetached(true);
  654. if (offlineMode(getActiveChar()))
  655. {
  656. getActiveChar().leaveParty();
  657. // If the L2PcInstance has Pet, unsummon it
  658. if (getActiveChar().getPet() != null)
  659. {
  660. getActiveChar().getPet().setRestoreSummon(true);
  661. getActiveChar().getPet().unSummon(getActiveChar());
  662. // Dead pet wasn't unsummoned, broadcast npcinfo changes (pet will be without owner name - means owner offline)
  663. if (getActiveChar().getPet() != null)
  664. {
  665. getActiveChar().getPet().broadcastNpcInfo(0);
  666. }
  667. }
  668. if (Config.OFFLINE_SET_NAME_COLOR)
  669. {
  670. getActiveChar().getAppearance().setNameColor(Config.OFFLINE_NAME_COLOR);
  671. getActiveChar().broadcastUserInfo();
  672. }
  673. if (getActiveChar().getOfflineStartTime() == 0)
  674. {
  675. getActiveChar().setOfflineStartTime(System.currentTimeMillis());
  676. }
  677. final LogRecord record = new LogRecord(Level.INFO, "Entering offline mode");
  678. record.setParameters(new Object[] { L2GameClient.this });
  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() || TvTEvent.isPlayerParticipant(player.getObjectId()) || 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(L2Character.ZONE_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.getPet() != null)
  790. {
  791. player.getPet().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. }