L2GameClient.java 29 KB

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