Minor renaming and refactoring

This commit is contained in:
P0nk
2021-06-29 20:27:32 +02:00
parent 828c3c5345
commit 0e98abff41
5 changed files with 329 additions and 306 deletions

View File

@@ -38,6 +38,8 @@ import net.server.audit.locks.MonitoredLockType;
import net.server.audit.locks.factory.MonitoredReentrantLockFactory; import net.server.audit.locks.factory.MonitoredReentrantLockFactory;
import net.server.channel.Channel; import net.server.channel.Channel;
import net.server.coordinator.login.MapleLoginBypassCoordinator; import net.server.coordinator.login.MapleLoginBypassCoordinator;
import net.server.coordinator.session.Hwid;
import net.server.coordinator.session.IpAddresses;
import net.server.coordinator.session.MapleSessionCoordinator; import net.server.coordinator.session.MapleSessionCoordinator;
import net.server.coordinator.session.MapleSessionCoordinator.AntiMulticlientResult; import net.server.coordinator.session.MapleSessionCoordinator.AntiMulticlientResult;
import net.server.guild.MapleGuild; import net.server.guild.MapleGuild;
@@ -157,24 +159,32 @@ public class MapleClient extends ChannelInboundHandlerAdapter {
@Override @Override
public void channelActive(ChannelHandlerContext ctx) { public void channelActive(ChannelHandlerContext ctx) {
final io.netty.channel.Channel channel = ctx.channel();
if (!Server.getInstance().isOnline()) { if (!Server.getInstance().isOnline()) {
ctx.channel().close(); channel.close();
return; return;
} }
String hostAddress = "null"; this.remoteAddress = getRemoteAddress(channel);
this.ioChannel = channel;
}
private static String getRemoteAddress(io.netty.channel.Channel channel) {
String remoteAddress = "null";
try { try {
hostAddress = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress(); String hostAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
if (hostAddress != null) {
remoteAddress = IpAddresses.evaluateRemoteAddress(hostAddress); // thanks dyz for noticing Local/LAN/WAN connections not interacting properly
}
} catch (NullPointerException npe) { } catch (NullPointerException npe) {
log.warn("Unable to get remote address for client", npe); log.warn("Unable to get remote address for client", npe);
} }
this.remoteAddress = hostAddress;
this.ioChannel = ctx.channel(); return remoteAddress;
} }
@Override @Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
// InPacket packet = new ByteBufInPacket((ByteBuf) msg);
if (!(msg instanceof InPacket packet)) { if (!(msg instanceof InPacket packet)) {
log.warn("Received invalid message: {}", msg); log.warn("Received invalid message: {}", msg);
return; return;
@@ -799,17 +809,17 @@ public class MapleClient extends ChannelInboundHandlerAdapter {
return accId; return accId;
} }
public void updateLoginState(int newstate) { public void updateLoginState(int newState) {
// rules out possibility of multiple account entries // rules out possibility of multiple account entries
if (newstate == LOGIN_LOGGEDIN) { if (newState == LOGIN_LOGGEDIN) {
MapleSessionCoordinator.getInstance().updateOnlineSession(this.getSession()); MapleSessionCoordinator.getInstance().updateOnlineClient(session);
} }
try (Connection con = DatabaseConnection.getConnection(); try (Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = con.prepareStatement("UPDATE accounts SET loggedin = ?, lastlogin = ? WHERE id = ?")) { PreparedStatement ps = con.prepareStatement("UPDATE accounts SET loggedin = ?, lastlogin = ? WHERE id = ?")) {
// using sql currenttime here could potentially break the login, thanks Arnah for pointing this out // using sql currenttime here could potentially break the login, thanks Arnah for pointing this out
ps.setInt(1, newstate); ps.setInt(1, newState);
ps.setTimestamp(2, new java.sql.Timestamp(Server.getInstance().getCurrentTime())); ps.setTimestamp(2, new java.sql.Timestamp(Server.getInstance().getCurrentTime()));
ps.setInt(3, getAccID()); ps.setInt(3, getAccID());
ps.executeUpdate(); ps.executeUpdate();
@@ -817,12 +827,12 @@ public class MapleClient extends ChannelInboundHandlerAdapter {
e.printStackTrace(); e.printStackTrace();
} }
if (newstate == LOGIN_NOTLOGGEDIN) { if (newState == LOGIN_NOTLOGGEDIN) {
loggedIn = false; loggedIn = false;
serverTransition = false; serverTransition = false;
setAccID(0); setAccID(0);
} else { } else {
serverTransition = (newstate == LOGIN_SERVER_TRANSITION); serverTransition = (newState == LOGIN_SERVER_TRANSITION);
loggedIn = !serverTransition; loggedIn = !serverTransition;
} }
} }
@@ -1165,7 +1175,7 @@ public class MapleClient extends ChannelInboundHandlerAdapter {
try { try {
if (lastPong < pingedAt) { if (lastPong < pingedAt) {
if (ioChannel.isActive()) { if (ioChannel.isActive()) {
log.info("Disconnected {} due to being idle. Cause: {}", remoteAddress, event.state()); log.info("Disconnected {} due to idling. Reason: {}", remoteAddress, event.state());
updateLoginState(MapleClient.LOGIN_NOTLOGGEDIN); updateLoginState(MapleClient.LOGIN_NOTLOGGEDIN);
disconnectSession(); disconnectSession();
} }

View File

@@ -48,7 +48,7 @@ public final class PacketProcessor {
} }
public static PacketProcessor getLoginServerProcessor() { public static PacketProcessor getLoginServerProcessor() {
return getProcessor(LoginServer.WORLD, LoginServer.CHANNEL); return getProcessor(LoginServer.WORLD_ID, LoginServer.CHANNEL_ID);
} }
public static PacketProcessor getChannelServerProcessor(int world, int channel) { public static PacketProcessor getChannelServerProcessor(int world, int channel) {

View File

@@ -7,8 +7,8 @@ import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel;
public class LoginServer extends AbstractServer { public class LoginServer extends AbstractServer {
public static final int WORLD = -1; public static final int WORLD_ID = -1;
public static final int CHANNEL = -1; public static final int CHANNEL_ID = -1;
private Channel channel; private Channel channel;
public LoginServer(int port) { public LoginServer(int port) {

View File

@@ -16,7 +16,16 @@ public abstract class ServerChannelInitializer extends ChannelInitializer<Socket
void initPipeline(SocketChannel socketChannel, MapleClient client) { void initPipeline(SocketChannel socketChannel, MapleClient client) {
final InitializationVector sendIv = InitializationVector.generateSend(); final InitializationVector sendIv = InitializationVector.generateSend();
final InitializationVector recvIv = InitializationVector.generateReceive(); final InitializationVector recvIv = InitializationVector.generateReceive();
writeInitialUnencryptedHelloPacket(socketChannel, sendIv, recvIv);
setUpHandlers(socketChannel, sendIv, recvIv, client);
}
private void writeInitialUnencryptedHelloPacket(SocketChannel socketChannel, InitializationVector sendIv, InitializationVector recvIv) {
socketChannel.writeAndFlush(Unpooled.wrappedBuffer(MaplePacketCreator.getHello(ServerConstants.VERSION, sendIv, recvIv))); socketChannel.writeAndFlush(Unpooled.wrappedBuffer(MaplePacketCreator.getHello(ServerConstants.VERSION, sendIv, recvIv)));
}
private void setUpHandlers(SocketChannel socketChannel, InitializationVector sendIv, InitializationVector recvIv,
MapleClient client) {
socketChannel.pipeline().addFirst("IdleStateHandler", new IdleStateHandler(30, 30, 0)); socketChannel.pipeline().addFirst("IdleStateHandler", new IdleStateHandler(30, 30, 0));
socketChannel.pipeline().addLast("PacketCodec", new PacketCodec(ClientCyphers.of(sendIv, recvIv))); socketChannel.pipeline().addLast("PacketCodec", new PacketCodec(ClientCyphers.of(sendIv, recvIv)));
socketChannel.pipeline().addLast("MapleClient", client); socketChannel.pipeline().addLast("MapleClient", client);

View File

@@ -59,7 +59,7 @@ import java.util.stream.Collectors;
public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler { public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
private static Set<Integer> attemptingLoginAccounts = new HashSet<>(); private static final Set<Integer> attemptingLoginAccounts = new HashSet<>();
private boolean tryAcquireAccount(int accId) { private boolean tryAcquireAccount(int accId) {
synchronized (attemptingLoginAccounts) { synchronized (attemptingLoginAccounts) {
@@ -85,23 +85,27 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
@Override @Override
public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) {
final int cid = slea.readInt(); final int cid = slea.readInt(); // TODO: investigate if this is the "client id" supplied in MaplePacketCreator#getServerIP()
final Server server = Server.getInstance(); final Server server = Server.getInstance();
if (c.tryacquireClient()) { // thanks MedicOP for assisting on concurrency protection here if (!c.tryacquireClient()) {
// thanks MedicOP for assisting on concurrency protection here
c.announce(MaplePacketCreator.getAfterLoginError(10));
}
try { try {
World wserv = server.getWorld(c.getWorld()); World wserv = server.getWorld(c.getWorld());
if(wserv == null) { if (wserv == null) {
c.disconnect(true, false); c.disconnect(true, false);
return; return;
} }
Channel cserv = wserv.getChannel(c.getChannel()); Channel cserv = wserv.getChannel(c.getChannel());
if(cserv == null) { if (cserv == null) {
c.setChannel(1); c.setChannel(1);
cserv = wserv.getChannel(c.getChannel()); cserv = wserv.getChannel(c.getChannel());
if(cserv == null) { if (cserv == null) {
c.disconnect(true, false); c.disconnect(true, false);
return; return;
} }
@@ -118,13 +122,15 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
return; return;
} }
} else { } else {
remoteHwid = player.getClient().getHWID(); Hwid clientHwid = player.getClient().getHwid();
remoteHwid = clientHwid == null ? null : clientHwid.hwid();
} }
int hwidLen = remoteHwid.length(); int hwidLen = remoteHwid.length();
session.setAttribute(MapleClient.CLIENT_HWID, remoteHwid); session.setAttribute(MapleClient.CLIENT_HWID, remoteHwid);
session.setAttribute(MapleClient.CLIENT_NIBBLEHWID, remoteHwid.substring(hwidLen - 8, hwidLen)); String nibbleHwid = remoteHwid.substring(hwidLen - 8, hwidLen);
c.setHWID(remoteHwid); session.setAttribute(MapleClient.CLIENT_NIBBLEHWID, nibbleHwid);
c.setHwid(new Hwid(remoteHwid));
if (!server.validateCharacteridInTransition(c, cid)) { if (!server.validateCharacteridInTransition(c, cid)) {
c.disconnect(true, false); c.disconnect(true, false);
@@ -216,7 +222,7 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
c.announce(MaplePacketCreator.getCharInfo(player)); c.announce(MaplePacketCreator.getCharInfo(player));
if (!player.isHidden()) { if (!player.isHidden()) {
if(player.isGM() && YamlConfig.config.server.USE_AUTOHIDE_GM) { if (player.isGM() && YamlConfig.config.server.USE_AUTOHIDE_GM) {
player.toggleHide(true); player.toggleHide(true);
} }
} }
@@ -247,9 +253,9 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
c.announce(MaplePacketCreator.loadFamily(player)); c.announce(MaplePacketCreator.loadFamily(player));
if (player.getFamilyId() > 0) { if (player.getFamilyId() > 0) {
MapleFamily f = wserv.getFamily(player.getFamilyId()); MapleFamily f = wserv.getFamily(player.getFamilyId());
if(f != null) { if (f != null) {
MapleFamilyEntry familyEntry = f.getEntryByID(player.getId()); MapleFamilyEntry familyEntry = f.getEntryByID(player.getId());
if(familyEntry != null) { if (familyEntry != null) {
familyEntry.setCharacter(player); familyEntry.setCharacter(player);
player.setFamilyEntry(familyEntry); player.setFamilyEntry(familyEntry);
@@ -265,6 +271,7 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
} else { } else {
c.announce(MaplePacketCreator.getFamilyInfo(null)); c.announce(MaplePacketCreator.getFamilyInfo(null));
} }
if (player.getGuildId() > 0) { if (player.getGuildId() > 0) {
MapleGuild playerGuild = server.getGuild(player.getGuildId(), player.getWorld(), player); MapleGuild playerGuild = server.getGuild(player.getGuildId(), player.getWorld(), player);
if (playerGuild == null) { if (playerGuild == null) {
@@ -316,7 +323,7 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
MapleInventory eqpInv = player.getInventory(MapleInventoryType.EQUIPPED); MapleInventory eqpInv = player.getInventory(MapleInventoryType.EQUIPPED);
eqpInv.lockInventory(); eqpInv.lockInventory();
try { try {
for(Item it : eqpInv.list()) { for (Item it : eqpInv.list()) {
player.equippedItem((Equip) it); player.equippedItem((Equip) it);
} }
} finally { } finally {
@@ -337,8 +344,8 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
player.checkBerserk(player.isHidden()); player.checkBerserk(player.isHidden());
if (newcomer) { if (newcomer) {
for(MaplePet pet : player.getPets()) { for (MaplePet pet : player.getPets()) {
if(pet != null) { if (pet != null) {
wserv.registerPetHunger(player, player.getPetIndex(pet)); wserv.registerPetHunger(player, player.getPetIndex(pet));
} }
} }
@@ -355,18 +362,18 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
player.announce(MaplePacketCreator.earnTitleMessage("You can vote now! Vote and earn a vote point!")); player.announce(MaplePacketCreator.earnTitleMessage("You can vote now! Vote and earn a vote point!"));
} }
*/ */
if (player.isGM()){ if (player.isGM()) {
Server.getInstance().broadcastGMMessage(c.getWorld(), MaplePacketCreator.earnTitleMessage((player.gmLevel() < 6 ? "GM " : "Admin ") + player.getName() + " has logged in")); Server.getInstance().broadcastGMMessage(c.getWorld(), MaplePacketCreator.earnTitleMessage((player.gmLevel() < 6 ? "GM " : "Admin ") + player.getName() + " has logged in"));
} }
if(diseases != null) { if (diseases != null) {
for(Entry<MapleDisease, Pair<Long, MobSkill>> e : diseases.entrySet()) { for (Entry<MapleDisease, Pair<Long, MobSkill>> e : diseases.entrySet()) {
final List<Pair<MapleDisease, Integer>> debuff = Collections.singletonList(new Pair<>(e.getKey(), e.getValue().getRight().getX())); final List<Pair<MapleDisease, Integer>> debuff = Collections.singletonList(new Pair<>(e.getKey(), e.getValue().getRight().getX()));
c.announce(MaplePacketCreator.giveDebuff(debuff, e.getValue().getRight())); c.announce(MaplePacketCreator.giveDebuff(debuff, e.getValue().getRight()));
} }
} }
} else { } else {
if(player.isRidingBattleship()) { if (player.isRidingBattleship()) {
player.announceBattleshipHp(); player.announceBattleshipHp();
} }
} }
@@ -386,17 +393,17 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
if (player.getMap().getHPDec() > 0) player.resetHpDecreaseTask(); if (player.getMap().getHPDec() > 0) player.resetHpDecreaseTask();
player.resetPlayerRates(); player.resetPlayerRates();
if(YamlConfig.config.server.USE_ADD_RATES_BY_LEVEL == true) player.setPlayerRates(); if (YamlConfig.config.server.USE_ADD_RATES_BY_LEVEL == true) player.setPlayerRates();
player.setWorldRates(); player.setWorldRates();
player.updateCouponRates(); player.updateCouponRates();
player.receivePartyMemberHP(); player.receivePartyMemberHP();
if(player.getPartnerId() > 0) { if (player.getPartnerId() > 0) {
int partnerId = player.getPartnerId(); int partnerId = player.getPartnerId();
final MapleCharacter partner = wserv.getPlayerStorage().getCharacterById(partnerId); final MapleCharacter partner = wserv.getPlayerStorage().getCharacterById(partnerId);
if(partner != null && !partner.isAwayFromWorld()) { if (partner != null && !partner.isAwayFromWorld()) {
player.announce(Wedding.OnNotifyWeddingPartnerTransfer(partnerId, partner.getMapId())); player.announce(Wedding.OnNotifyWeddingPartnerTransfer(partnerId, partner.getMapId()));
partner.announce(Wedding.OnNotifyWeddingPartnerTransfer(player.getId(), player.getMapId())); partner.announce(Wedding.OnNotifyWeddingPartnerTransfer(player.getId(), player.getMapId()));
} }
@@ -427,15 +434,12 @@ public final class PlayerLoggedinHandler extends AbstractMaplePacketHandler {
c.announce(MaplePacketCreator.setNPCScriptable(npcsIds)); c.announce(MaplePacketCreator.setNPCScriptable(npcsIds));
} }
if(newcomer) player.setLoginTime(System.currentTimeMillis()); if (newcomer) player.setLoginTime(System.currentTimeMillis());
} catch(Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally { } finally {
c.releaseClient(); c.releaseClient();
} }
} else {
c.announce(MaplePacketCreator.getAfterLoginError(10));
}
} }
private static void showDueyNotification(MapleClient c, MapleCharacter player) { private static void showDueyNotification(MapleClient c, MapleCharacter player) {