Example usage for io.netty.buffer ByteBuf readShort

List of usage examples for io.netty.buffer ByteBuf readShort

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf readShort.

Prototype

public abstract short readShort();

Source Link

Document

Gets a 16-bit short integer at the current readerIndex and increases the readerIndex by 2 in this buffer.

Usage

From source file:net.hasor.rsf.remoting.transport.protocol.codec.RpcResponseProtocol.java

License:Apache License

/**decode stream to object*/
public ResponseSocketBlock decode(ByteBuf buf) throws IOException {
    //* --------------------------------------------------------bytes =13
    //* byte[1]  version                              RSF(0x80)
    byte version = buf.readByte();
    //* byte[8]  requestID                            ?ID
    long requestID = buf.readLong();
    //* byte[1]  keepData                             ?
    buf.skipBytes(1);//  w  w  w.  ja  v  a 2 s.co  m
    //* byte[3]  contentLength                        ?
    buf.skipBytes(3);//.readUnsignedMedium()
    //
    ResponseSocketBlock res = new ResponseSocketBlock();
    res.setVersion(version);
    res.setRequestID(requestID);
    //* --------------------------------------------------------bytes =8
    //* byte[2]  status                               ??
    res.setStatus(buf.readShort());
    //* byte[2]  serializeType-(attr-index)           ?
    res.setSerializeType(buf.readShort());
    //* byte[2]  returnType-(attr-index)              
    res.setReturnType(buf.readShort());
    //* byte[2]  returnData-(attr-index)              ?
    res.setReturnData(buf.readShort());
    //* --------------------------------------------------------bytes =1 ~ 1021
    //* byte[1]  optionCount                          ?
    byte optionCount = buf.readByte();
    for (int i = 0; i < optionCount; i++) {
        //* byte[4]  attr-0-(attr-index,attr-index)   ?
        int mergeData = buf.readInt();
        res.addOption(mergeData);
    }
    //* --------------------------------------------------------bytes =6 ~ 8192
    //* byte[2]  attrPool-size (Max = 2047)           ?
    short attrPoolSize = buf.readShort();
    for (int i = 0; i < attrPoolSize; i++) {
        //* byte[4] att-length                        1?
        int length = buf.readInt();
        res.addPoolData(length);
    }
    //* --------------------------------------------------------bytes =n
    //* dataBody                                      ?
    res.fillFrom(buf.readBytes(res.getPoolSize()));
    return res;
}

From source file:net.ieldor.modules.login.LoginManager.java

License:Open Source License

public Player runGameLogin(ByteBuf buffer, Channel channel, ChannelHandlerContext context) {
    boolean unknownEquals14 = buffer.readUnsignedByte() == 1;
    int secureBufferSize = buffer.readShort() & 0xFFFF;
    if (buffer.readableBytes() < secureBufferSize) {
        channel.write(new LoginResponse(LoginResponse.BAD_SESSION));
        //session.getLoginPackets().sendClientPacket(10);
        return null;
    }/*from  w w w  .  j av a  2s  . c o m*/
    byte[] secureBytes = new byte[secureBufferSize];
    buffer.readBytes(secureBytes);

    ByteBuf secureBuffer = Unpooled.wrappedBuffer(
            new BigInteger(secureBytes).modPow(Constants.JS5PrivateKey, Constants.JS5ModulusKey).toByteArray());
    /*byte[] data = new byte[rsaBlockSize];
    buffer.readBytes(data, 0, rsaBlockSize);
    InputStream rsaStream = new InputStream(Utils.cryptRSA(data, Settings.PRIVATE_EXPONENT, Settings.MODULUS));*/
    int blockOpcode = secureBuffer.readUnsignedByte();

    if (blockOpcode != 10) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        //session.getLoginPackets().sendClientPacket(10);
        return null;
    }

    int[] xteaKey = new int[4];
    for (int key = 0; key < xteaKey.length; key++) {
        xteaKey[key] = secureBuffer.readInt();
    }

    long vHash = secureBuffer.readLong();
    if (vHash != 0L) {// rsa block check, pass part
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return null;
    }

    String password = ByteBufUtils.readString(secureBuffer);
    System.out.println("Password: " + password);
    //TODO: Implement password encryption
    //password = Encrypt.encryptSHA1(password);
    //System.out.println("Found password: "+password);
    long[] loginSeeds = new long[2];
    for (int seed = 0; seed < loginSeeds.length; seed++) {
        loginSeeds[seed] = secureBuffer.readLong();
    }

    byte[] xteaBlock = new byte[buffer.readableBytes()];
    System.out.println("Xtea size: " + xteaBlock.length);
    buffer.readBytes(xteaBlock);
    XTEA xtea = new XTEA(xteaKey);
    xtea.decrypt(xteaBlock, 0, xteaBlock.length);

    InputStream xteaBuffer = new InputStream(xteaBlock);

    boolean decodeAsString = xteaBuffer.readByte() == 1;
    String username = decodeAsString ? xteaBuffer.readString()
            : Base37Utils.decodeBase37(xteaBuffer.readLong());
    System.out.println("Username: " + username);
    int displayMode = xteaBuffer.readUnsignedByte();
    int screenWidth = xteaBuffer.readUnsignedShort();
    int screenHeight = xteaBuffer.readUnsignedShort();
    int unknown2 = xteaBuffer.readUnsignedByte();

    xteaBuffer.skip(24); // 24bytes directly from a file, no idea whats there

    String settings = xteaBuffer.readString();
    int affid = xteaBuffer.readInt();
    int indexFiles = xteaBuffer.readByte() & 0xff;

    int[] crcValues = new int[indexFiles];
    int crcCount = xteaBuffer.readUnsignedByte();
    for (int i = 1; i < crcValues.length; i++) {
        crcValues[i] = xteaBuffer.readUnsignedByte();
    }

    @SuppressWarnings("unused")
    MachineData data = new MachineData(xteaBuffer);

    xteaBuffer.readInt();// Packet receive count
    xteaBuffer.readInt();//Unknown
    xteaBuffer.readInt();//Unknown
    xteaBuffer.readString();// Some param string (empty)
    boolean hasAditionalInformation = xteaBuffer.readUnsignedByte() == 1;
    if (hasAditionalInformation) {
        xteaBuffer.readString(); // aditionalInformation
    }
    boolean hasJagtheora = xteaBuffer.readUnsignedByte() == 1;
    boolean js = xteaBuffer.readUnsignedByte() == 1;
    boolean hc = xteaBuffer.readUnsignedByte() == 1;
    int unknown4 = xteaBuffer.readByte();
    int unknown5 = xteaBuffer.readInt();

    String serverToken = xteaBuffer.readString();
    if (!serverToken.equals(Constants.SERVER_TOKEN)) {
        System.out.println("Expected token: " + Constants.SERVER_TOKEN + ", found: " + serverToken);
        channel.write(new LoginResponse(LoginResponse.BAD_SESSION));
        return null;
    }
    boolean unknown7 = xteaBuffer.readUnsignedByte() == 1;

    for (int index = 0; index < crcCount; index++) {
        //int crc = CacheManager.STORE.getIndexes()[index] == null ? -1011863738 : CacheManager.STORE
        //      .getIndexes()[index].getCRC();
        int receivedCRC = xteaBuffer.readInt();
        /*if (crc != receivedCRC && index < 32) {
           Logger.log(this,
            "Invalid CRC at index: "+index+", "+receivedCRC+", "+crc);
           session.getLoginPackets().sendClientPacket(6);
           return;
        }*/
    }
    //TODO: Implement the following checks
    /*if (Utils.invalidAccountName(username)) {
       session.getLoginPackets().sendClientPacket(3);
       return;
    }
    if (World.getPlayers().size() >= Settings.PLAYERS_LIMIT - 10) {
       session.getLoginPackets().sendClientPacket(7);
       return;
    }
    if (World.containsPlayer(username)) {
       session.getLoginPackets().sendClientPacket(5);
       return;
    }
    if (AntiFlood.getSessionsIP(session.getIP()) > 3) {
       session.getLoginPackets().sendClientPacket(9);
       return;
    }*/
    LoadResult result = null;
    try {
        result = BinaryPlayerManager.loadPlayer(new LoginHandshakeMessage(username, password, context));
    } catch (IOException e) {
        channel.write(new LoginResponse(LoginResponse.ERROR_PROFILE_LOAD));
        return null;
    }
    if (result.getReturnCode() != LoginResponse.SUCCESS) {
        channel.write(new LoginResponse(result.getReturnCode()));
        return null;
    }
    Player player = result.getPlayer();
    player.initDisplayName();
    channel.write(new LoginConfigData(Constants.NIS_CONFIG, true));
    return player;
    /*player.init(session, username, displayMode, screenWidth, screenHeight, mInformation, new IsaacKeyPair(isaacKeys));
    session.getLoginPackets().sendLoginDetails(player);
    session.setDecoder(3, player);
    session.setEncoder(2, player);*/
    //player.start();
    /*Player player;
    if (!SerializableFilesManager.containsPlayer(username)) 
       player = new Player(password);
    else {
       player = SerializableFilesManager.loadPlayer(username);
       if (player == null) {
    session.getLoginPackets().sendClientPacket(20);
    return;
       }
       if (!SerializableFilesManager.createBackup(username)) {
    session.getLoginPackets().sendClientPacket(20);
    return;
       }
       if (!password.equals(player.getPassword())) {
    session.getLoginPackets().sendClientPacket(3);
    return;
       }
    }
    if (player.isPermBanned() || player.getBanned() > Utils.currentTimeMillis()) {
       session.getLoginPackets().sendClientPacket(4);
       return;
    }*/
}

From source file:net.ieldor.modules.login.LoginManager.java

License:Open Source License

public void runLobbyLogin(ByteBuf buffer, Channel channel, ChannelHandlerContext context) {
    int secureBufferSize = buffer.readShort() & 0xFFFF;
    if (buffer.readableBytes() < secureBufferSize) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return;/*www.j  a va  2s  .  c  o  m*/
    }

    byte[] secureBytes = new byte[secureBufferSize];
    buffer.readBytes(secureBytes);

    ByteBuf secureBuffer = Unpooled.wrappedBuffer(
            new BigInteger(secureBytes).modPow(Constants.JS5PrivateKey, Constants.JS5ModulusKey).toByteArray());
    int blockOpcode = secureBuffer.readUnsignedByte();

    if (blockOpcode != 10) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return;
    }

    int[] xteaKey = new int[4];
    for (int key = 0; key < xteaKey.length; key++) {
        xteaKey[key] = secureBuffer.readInt();
    }

    long vHash = secureBuffer.readLong();
    if (vHash != 0L) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return;
    }

    String password = ByteBufUtils.readString(secureBuffer);
    //System.out.println("Found password: "+password);
    long[] loginSeeds = new long[2];
    for (int seed = 0; seed < loginSeeds.length; seed++) {
        loginSeeds[seed] = secureBuffer.readLong();
    }

    byte[] xteaBlock = new byte[buffer.readableBytes()];
    buffer.readBytes(xteaBlock);
    XTEA xtea = new XTEA(xteaKey);
    xtea.decrypt(xteaBlock, 0, xteaBlock.length);

    InputStream xteaBuffer = new InputStream(xteaBlock);

    boolean decodeAsString = xteaBuffer.readByte() == 1;
    String username = decodeAsString ? xteaBuffer.readString()
            : Base37Utils.decodeBase37(xteaBuffer.readLong());
    //System.out.println("Found username: "+username);
    @SuppressWarnings("unused")
    int gameType = xteaBuffer.readUnsignedByte();
    @SuppressWarnings("unused")
    int languageID = xteaBuffer.readUnsignedByte();

    @SuppressWarnings("unused")
    int displayMode = xteaBuffer.readByte();
    @SuppressWarnings("unused")
    int screenWidth = xteaBuffer.readUnsignedShort();// Client screen width
    @SuppressWarnings("unused")
    int screenHeight = xteaBuffer.readUnsignedShort();// Client screen height
    @SuppressWarnings("unused")
    int anUnknownByte = xteaBuffer.readByte();

    byte[] randomData = new byte[24];
    for (int i = 0; i < randomData.length; i++) {
        randomData[i] = (byte) (xteaBuffer.readByte() & 0xFF);
    }

    @SuppressWarnings("unused")
    String clientSettings = xteaBuffer.readString();

    int indexFiles = xteaBuffer.readByte() & 0xff;

    int[] crcValues = new int[indexFiles];

    for (int i = 0; i < crcValues.length; i++) {
        crcValues[i] = xteaBuffer.readUnsignedByte();
    }
    @SuppressWarnings("unused")
    MachineData data = new MachineData(xteaBuffer);
    /*int length = xteaBuffer.readUnsignedByte();byte[] machineData = new byte[length];
    for (int data = 0; data < machineData.length; data++) {
       machineData[data] = (byte) xteaBuffer.readUnsignedByte();
    }*/

    xteaBuffer.readInt();// Packet receive count
    xteaBuffer.readString();// Some param string (empty)
    xteaBuffer.readInt();// Another param (0)
    xteaBuffer.readInt();// Yet another param (2036537831)

    String serverToken = xteaBuffer.readString();
    if (!serverToken.equals(Constants.SERVER_TOKEN)) {
        System.out.println("Expected token: " + Constants.SERVER_TOKEN + ", found: " + serverToken);
        channel.write(new LoginResponse(LoginResponse.BAD_SESSION));
        return;
    }

    xteaBuffer.readByte();// Final param (2424)

    LoadResult result = null;
    try {
        result = BinaryPlayerManager.loadPlayer(new LoginHandshakeMessage(username, password, context));
    } catch (IOException e) {
        channel.write(new LoginResponse(LoginResponse.ERROR_PROFILE_LOAD));
        return;
    }
    if (result.getReturnCode() != LoginResponse.SUCCESS) {
        channel.write(new LoginResponse(result.getReturnCode()));
        return;
    }
    Player player = result.getPlayer();
    player.initDisplayName();
    int rights = 0;
    long memberEndDate = 1420073999999L;
    int memberFlags = 0x1;//0x1 - if members, 0x2 - subscription
    int lastLoginDay = 0;
    int recoverySetDay = 4000;//The day on which recovery questions were last set
    int msgCount = 0;
    String loginIp = null;
    int emailStatus = 3;//email status (0 - no email, 1 - pending parental confirmation, 2 - pending confirmation, 3 - registered)
    String displayName = player.getDisplayName();
    WorldData defaultWorld = WorldList.DEFAULT_WORLD;

    LobbyLoginData lobbyData = new LobbyLoginData(rights, memberEndDate, memberFlags, lastLoginDay,
            recoverySetDay, msgCount, loginIp, emailStatus, displayName, defaultWorld);

    channel.write(lobbyData);
    player.lobbyLogin(context);
    /*Packet response = encodeLobbyResponse(player);
    channel.write(new LoginResponse(LoginResponse.SUCCESS, response.getPayload(), response.getLength()));
    */
}

From source file:net.ieldor.network.codec.login.LoginDecoder.java

License:Open Source License

private Object decodeConnectionType(ByteBuf buffer) throws ProtocolException {
    int loginType = buffer.readUnsignedByte();
    if (loginType != 16 && loginType != 18 && loginType != 19) {
        System.out.println("Invalid login opcode: " + loginType);
        return new LoginResponse(LoginResponse.BAD_LOGIN_PACKET);
        // throw new ProtocolException("Invalid login opcode: " + loginType);
    }/*from   w w w  .  j  av  a  2  s.  c o m*/

    currentLoginType = loginType == 19 ? LoginType.LOBBY : LoginType.GAME;
    loginSize = buffer.readShort() & 0xFFFF;

    state = LoginState.CLIENT_DETAILS;
    return decodeClientDetails(buffer);
}

From source file:net.killermapper.roadstuff.common.network.PacketSignType.java

License:Open Source License

@Override
public void fromBytes(ByteBuf buf) {
    this.signType = buf.readShort();
    this.signShape = buf.readByte();
    this.tileX = buf.readInt();
    this.tileY = buf.readInt();
    this.tileZ = buf.readInt();
}

From source file:net.mechanicalcat.pycode.net.InvokeWandMessage.java

License:Open Source License

@Override
public void fromBytes(ByteBuf buf) {
    hitVec = new Vec3d(buf.readDouble(), buf.readDouble(), buf.readDouble());
    typeOfHit = RayTraceResult.Type.MISS;
    switch (buf.readShort()) {
    case 1:/* w w  w .j a v  a2  s  .  com*/
        typeOfHit = RayTraceResult.Type.BLOCK;
        blockPos = new BlockPos(buf.readInt(), buf.readInt(), buf.readInt());
        sideHit = EnumFacing.values()[buf.readShort()];
        break;
    case 2:
        typeOfHit = RayTraceResult.Type.ENTITY;
        entityId = buf.readInt();
    }
}

From source file:net.minecrell.quartz.mixin.network.MixinLegacyPingHandler.java

License:MIT License

private boolean readLegacy(ChannelHandlerContext ctx, ByteBuf buf) {
    if (buf.readUnsignedByte() != 0xFE) {
        return false;
    }//from  ww w  .  j  a v  a  2  s.co  m

    MinecraftServer server = this.system.getServer();
    InetSocketAddress client = (InetSocketAddress) ctx.channel().remoteAddress();
    ServerStatusResponse response;

    int i = buf.readableBytes();
    switch (i) {
    case 0:
        logger.debug("Ping: (<=1.3) from {}:{}", client.getAddress(), client.getPort());

        response = QuartzStatusResponse.postLegacy(server, client, QuartzLegacyMinecraftVersion.V1_3, null);
        if (response != null) {
            this.writeResponse(ctx,
                    String.format("%s%d%d", QuartzStatusResponse.getUnformattedMotd(response),
                            response.getPlayers().getOnline(), response.getPlayers().getMax()));
        } else {
            ctx.close();
        }

        break;
    case 1:
        if (buf.readUnsignedByte() != 0x01) {
            return false;
        }

        logger.debug("Ping: (1.4-1.5) from {}:{}", client.getAddress(), client.getPort());

        response = QuartzStatusResponse.postLegacy(server, client, QuartzLegacyMinecraftVersion.V1_5, null);
        if (response != null) {
            this.writeResponse(ctx,
                    String.format("1\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d",
                            response.getVersion().getProtocol(), response.getVersion().getName(),
                            QuartzStatusResponse.getMotd(response), response.getPlayers().getOnline(),
                            response.getPlayers().getMax()));
        } else {
            ctx.close();
        }

        break;
    default:
        if (buf.readUnsignedByte() != 0x01 || buf.readUnsignedByte() != 0xFA) {
            return false;
        }
        if (!buf.isReadable(2)) {
            break;
        }
        short length = buf.readShort();
        if (!buf.isReadable(length * 2)) {
            break;
        }
        if (!buf.readBytes(length * 2).toString(Charsets.UTF_16BE).equals("MC|PingHost")) {
            return false;
        }
        if (!buf.isReadable(2)) {
            break;
        }
        length = buf.readShort();
        if (!buf.isReadable(length)) {
            break;
        }

        int protocol = buf.readUnsignedByte();
        length = buf.readShort();
        String host = buf.readBytes(length * 2).toString(Charsets.UTF_16BE);
        int port = buf.readInt();

        logger.debug("Ping: (1.6) from {}:{}", client.getAddress(), client.getPort());

        response = QuartzStatusResponse.postLegacy(server, client,
                new QuartzLegacyMinecraftVersion(QuartzLegacyMinecraftVersion.V1_6, protocol),
                InetSocketAddress.createUnresolved(host, port));
        if (response != null) {
            this.writeResponse(ctx,
                    String.format("1\u0000%d\u0000%s\u0000%s\u0000%d\u0000%d",
                            response.getVersion().getProtocol(), response.getVersion().getName(),
                            QuartzStatusResponse.getMotd(response), response.getPlayers().getOnline(),
                            response.getPlayers().getMax()));
        } else {
            ctx.close();
        }

        break;
    }

    return true;
}

From source file:net.shadowmage.ancientwarfare.core.util.StringTools.java

License:Open Source License

public static final String readString(ByteBuf in) {
    short len = in.readShort();
    byte[] nameBytes = new byte[len];
    in.readBytes(nameBytes);/*  w  w  w.ja va 2 s.  co m*/
    return new String(nameBytes);
}

From source file:net.tridentsdk.data.Slot.java

License:Open Source License

public Slot(ByteBuf buf) {
    this.id = (short) buf.readByte();
    this.mat = Material.fromString(String.valueOf(this.id));

    if (this.id == -1) {
        return;//from w  ww  .ja  v  a2s. c o  m
    }

    this.quantity = buf.readByte();
    this.damageValue = buf.readShort();
    byte b;

    if ((b = buf.readByte()) != 0) {
        try {
            NBTDecoder builder = new NBTDecoder(new ByteBufInputStream(buf));

            this.compoundTag = builder.decode(b);
        } catch (NBTException ignored) {
            // do something
        }
    }
}

From source file:net.tridentsdk.packets.handshake.PacketHandshakeIn.java

License:Open Source License

@Override
public Packet decode(ByteBuf buf) {
    this.protocolVersion = Codec.readVarInt32(buf);
    this.address = Codec.readString(buf);
    this.port = buf.readShort();
    this.nextState = Codec.readVarInt32(buf);
    return this;
}