L2GameClient.java 29 KB

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