L2GameClient.java 27 KB

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