Example usage for io.netty.buffer Unpooled wrappedBuffer

List of usage examples for io.netty.buffer Unpooled wrappedBuffer

Introduction

In this page you can find the example usage for io.netty.buffer Unpooled wrappedBuffer.

Prototype

public static ByteBuf wrappedBuffer(ByteBuffer... buffers) 

Source Link

Document

Creates a new big-endian composite buffer which wraps the slices of the specified NIO buffers without copying them.

Usage

From source file:com.quavo.osrs.network.protocol.codec.game.GamePacketDecoder.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (!in.isReadable() || !player.getChannel().isRegistered()) {
        return;//  w ww . j a  v a 2 s  .c o  m
    }
    int opcode = in.readUnsignedByte();
    Optional<PacketDecoderIdentifier> data = PacketDecoderIdentifier.getPacket(opcode);
    if (data.isPresent()) {
        PacketDecoderIdentifier packet = data.get();

        int size = packet.getSize();
        if (packet.getType() == PacketType.VARIABLE_BYTE) {
            if (in.readableBytes() < 1) {
                return;
            }
            size = in.readUnsignedByte();
        } else if (packet.getType() == PacketType.VARIABLE_SHORT) {
            if (in.readableBytes() < 2) {
                return;
            }
            size = in.readUnsignedShort();
        }

        if (in.readableBytes() >= size) {
            if (size < 0) {
                return;
            }

            byte[] bytes = new byte[size];
            in.readBytes(bytes, 0, size);
            out.add(new GamePacketRequest(this, player, packet.getId(),
                    new GamePacketReader(Unpooled.wrappedBuffer(bytes))));
        }

    } else {
        System.out.println("No data present for incoming packet: " + opcode + ".");
        in.readBytes(new byte[in.readableBytes()]);
    }
}

From source file:com.quavo.util.buf.ByteBufUtils.java

License:Open Source License

/**
 * Encrypts a {@link ByteBuf} using with a exponent and modulus.
 * // w  w w.j  a  v  a 2  s . com
 * @param buffer The {@link ByteBuf} to encrypt.
 * @param exponent The exponent.
 * @param modulus The modulus.
 * @return The encrypted buffer.
 */
public static ByteBuf encipherRSA(ByteBuf buffer, BigInteger exponent, BigInteger modulus) {
    byte[] bytes = new byte[buffer.readShort()];
    buffer.readBytes(bytes);
    return Unpooled.wrappedBuffer(new BigInteger(bytes).modPow(exponent, modulus).toByteArray());
}

From source file:com.quavo.util.buf.ByteBufUtils.java

License:Open Source License

/**
 * Deciphers the specified {@link ByteBuf} with the given key.
 * //w w w .j  a  v a2  s .  com
 * @param buffer The {@link ByteBuf}.
 * @param key The key.
 * @return The new {@link ByteBuf}.
 */
public static ByteBuf decipherXTEA(ByteBuf buffer, int[] key) {
    byte[] bytes = new byte[buffer.readableBytes()];
    buffer.readBytes(bytes);
    ByteBuf xteaBuffer = Unpooled.wrappedBuffer(bytes);
    decipherXTEA(xteaBuffer, 0, bytes.length, key);
    return xteaBuffer;
}

From source file:com.rain.websocketclient.WebSocketClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    final int port;
    if (uri.getPort() == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*w w w .j a  v  a  2  s  . co  m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        } else {
            port = -1;
        }
    } else {
        port = uri.getPort();
    }

    if (!"ws".equalsIgnoreCase(scheme) && !"wss".equalsIgnoreCase(scheme)) {
        System.err.println("Only WS(S) is supported.");
        return;
    }

    final boolean ssl = "wss".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00.
        // If you change it to V00, ping is not supported and remember to change
        // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline.
        final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory
                .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), host, port));
                }
                p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler);
            }
        });

        Channel ch = b.connect(uri.getHost(), port).sync().channel();
        handler.handshakeFuture().sync();

        BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String msg = console.readLine();
            if (msg == null) {
                break;
            } else if ("bye".equals(msg.toLowerCase())) {
                ch.writeAndFlush(new CloseWebSocketFrame());
                ch.closeFuture().sync();
                break;
            } else if ("ping".equals(msg.toLowerCase())) {
                WebSocketFrame frame = new PingWebSocketFrame(
                        Unpooled.wrappedBuffer(new byte[] { 8, 1, 8, 1 }));
                ch.writeAndFlush(frame);
            } else {
                WebSocketFrame frame = new TextWebSocketFrame(msg);
                ch.writeAndFlush(frame);
            }
        }
    } finally {
        group.shutdownGracefully();
    }
}

From source file:com.relayrides.pushy.apns.ApnsClient.java

License:Open Source License

/**
 * <p>Registers a private signing key for the given topics. Clears any topics and keys previously associated with
 * the given team.</p>//from  www .j av a  2s.c o m
 *
 * <p>Callers <em>must</em> register signing keys for all topics to which they intend to send notifications. Tokens
 * may be registered at any time in a client's life-cycle.</p>
 *
 * @param signingKeyInputStream an input stream that provides a PEM-encoded, PKCS#8-formatted elliptic-curve private
 * key with which to sign authentication tokens
 * @param teamId the Apple-issued, ten-character identifier for the team to which the given private key belongs
 * @param keyId the Apple-issued, ten-character identifier for the given private key
 * @param topics the topics to which the given signing key is applicable
 *
 * @throws InvalidKeyException if the given key is invalid for any reason
 * @throws NoSuchAlgorithmException if the JRE does not support the required token-signing algorithm
 * @throws IOException if a private key could not be loaded from the given input stream for any reason
 *
 * @since 0.9
 */
public void registerSigningKey(final InputStream signingKeyInputStream, final String teamId, final String keyId,
        final String... topics) throws InvalidKeyException, NoSuchAlgorithmException, IOException {
    final ECPrivateKey signingKey;
    {
        final String base64EncodedPrivateKey;
        {
            final StringBuilder privateKeyBuilder = new StringBuilder();

            final BufferedReader reader = new BufferedReader(new InputStreamReader(signingKeyInputStream));
            boolean haveReadHeader = false;
            boolean haveReadFooter = false;

            for (String line; (line = reader.readLine()) != null;) {
                if (!haveReadHeader) {
                    if (line.contains("BEGIN PRIVATE KEY")) {
                        haveReadHeader = true;
                        continue;
                    }
                } else {
                    if (line.contains("END PRIVATE KEY")) {
                        haveReadFooter = true;
                        break;
                    } else {
                        privateKeyBuilder.append(line);
                    }
                }
            }

            if (!(haveReadHeader && haveReadFooter)) {
                throw new IOException("Could not find private key header/footer");
            }

            base64EncodedPrivateKey = privateKeyBuilder.toString();
        }

        final ByteBuf wrappedEncodedPrivateKey = Unpooled
                .wrappedBuffer(base64EncodedPrivateKey.getBytes(StandardCharsets.US_ASCII));

        try {
            final ByteBuf decodedPrivateKey = Base64.decode(wrappedEncodedPrivateKey);

            try {
                final byte[] keyBytes = new byte[decodedPrivateKey.readableBytes()];
                decodedPrivateKey.readBytes(keyBytes);

                final PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
                final KeyFactory keyFactory = KeyFactory.getInstance("EC");
                signingKey = (ECPrivateKey) keyFactory.generatePrivate(keySpec);
            } catch (final InvalidKeySpecException e) {
                throw new InvalidKeyException(e);
            } finally {
                decodedPrivateKey.release();
            }
        } finally {
            wrappedEncodedPrivateKey.release();
        }
    }

    this.registerSigningKey(signingKey, teamId, keyId, topics);
}

From source file:com.rs3e.network.protocol.codec.login.LoginDecoder.java

License:Open Source License

/**
 * Decodes the payload of login./*from www .  j  a v a2 s.  c o m*/
 * 
 * @param ctx
 *            The channel handler context.
 * @param buf
 *            The byte buf for writing data.
 * @return The login message, or {@code Null}.
 */
/*
 * private Object decodePayload(ChannelHandlerContext ctx, ByteBuf buf) {
 * if(buf.readable()) {
 * 
 * int loginType = buf.readByte(); System.out.println("Login Type: " +
 * loginType); } return null; }
 */

private Object decodeLobbyPayload(ChannelHandlerContext context, ByteBuf buffer) throws ProtocolException {
    int secureBufferSize = buffer.readShort() & 0xFFFF;
    if (buffer.readableBytes() < secureBufferSize) {
        throw new ProtocolException("Invalid secure buffer size.");
    }

    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) {
        throw new ProtocolException("Invalid block opcode.");
    }

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

    long vHash = secureBuffer.readLong();
    if (vHash != 0L) {
        throw new ProtocolException("Invalid login virtual hash.");
    }

    ByteBufUtils.readString(secureBuffer);

    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);
    return null;
    // return new LoginPayload(password, xteaKey, xteaBlock);
}

From source file:com.rs3e.network.protocol.login.LoginDecoder.java

License:Open Source License

/**
 * Decodes the payload of login.//from   www.j av a2  s .  c  o m
 * @param ctx The channel handler context.
 * @param buf The byte buf for writing data.
 * @return The login message, or {@code Null}.
 */
/*private Object decodePayload(ChannelHandlerContext ctx, ByteBuf buf) {
   if(buf.readable()) {
         
 int loginType = buf.readByte();
 System.out.println("Login Type: " + loginType);
   }
   return null;
}*/

private Object decodeLobbyPayload(ChannelHandlerContext context, ByteBuf buffer) throws ProtocolException {
    int secureBufferSize = buffer.readShort() & 0xFFFF;
    if (buffer.readableBytes() < secureBufferSize) {
        throw new ProtocolException("Invalid secure buffer size.");
    }

    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) {
        throw new ProtocolException("Invalid block opcode.");
    }

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

    long vHash = secureBuffer.readLong();
    if (vHash != 0L) {
        throw new ProtocolException("Invalid login virtual hash.");
    }

    String password = ByteBufUtils.readString(secureBuffer);

    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);
    return null;
    //return new LoginPayload(password, xteaKey, xteaBlock);   
}

From source file:com.rs3e.network.session.impl.LoginSession.java

License:Open Source License

@Override
public void message(Object obj) {
    //System.out.println("Login message method called...");
    if (obj instanceof LoginPayload) {
        LoginPayload loginData = (LoginPayload) obj;
        ByteBuf buffer = Unpooled.wrappedBuffer(loginData.getPayload());
        if (loginData.getType() == LoginPayload.LoginType.LOBBY) {
            decodeLobbyLogin(buffer);/*from   w ww  .j av a  2  s. c  o  m*/
        }
    }
}

From source file:com.rs3e.network.session.impl.LoginSession.java

License:Open Source License

private void decodeLobbyLogin(ByteBuf buffer) {
    int secureBufferSize = buffer.readShort() & 0xFFFF;
    if (buffer.readableBytes() < secureBufferSize) {
        channel.write(new LoginResponse(LoginResponse.BAD_LOGIN_PACKET));
        return;//w  ww. j a  va2  s .  c  om
    }

    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);

    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());

    @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.readInt();
    }

    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)) {
        channel.write(new LoginResponse(LoginResponse.BAD_SESSION));
        return;
    }

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

    if (GeneralUtils.invalidAccountName(username)) {
        //session.getLoginPackets().sendClientPacket(3);//Invalid username or password
        channel.write(new LoginResponse(LoginResponse.INVALID_UN_PWD));
        return;
    }
    /*
    if (World.getPlayers().size() >= Settings.PLAYERS_LIMIT - 10) {
       session.getLoginPackets().sendClientPacket(7);//World full
       return;
    }
    if (World.containsPlayer(username) || World.containsLobbyPlayer(username)) {
       session.getLoginPackets().sendClientPacket(5);//Account not logged out
       return;
    }
    if (AntiFlood.getSessionsIP(session.getIP()) > 3) {
       session.getLoginPackets().sendClientPacket(9);//Login limit exceeded
       return;
    }*/
    Player player;// = new Player(new PlayerDefinition(username, password));
    if (!SerializableFilesManager.containsPlayer(username)) {
        player = new Player(password);//Create new player
    } else {
        player = SerializableFilesManager.loadPlayer(username);
        if (player == null) {
            //session.getLoginPackets().sendClientPacket(20);//Invalid login server
            channel.write(new LoginResponse(LoginResponse.INVALID_LOGIN_SERVER));
            return;
        }
        /*if (!SerializableFilesManager.createBackup(username)) {
           //session.getLoginPackets().sendClientPacket(20);//Invalid login server
           //return;
        }*/
        if (!player.isCorrectPassword(password)) {
            //session.getLoginPackets().sendClientPacket(3);
            channel.write(new LoginResponse(LoginResponse.INVALID_UN_PWD));
            return;
        }
    } // || player.getBanned() > Utils.currentTimeMillis()
    if (player.isPermBanned()) {
        //session.getLoginPackets().sendClientPacket(4);//Account disabled
        channel.write(new LoginResponse(LoginResponse.ACCOUNT_DISABLED));
        return;
    } //24 = account does not exist
    player.lobbyInit(context.channel(), username);

    /*int returnCode = 2;
    if (FileManager.contains(username)) {
       player = (Player) FileManager.load(username);
       if (player == null) {
    returnCode = 24;
       } else if (!password.equals(player.getDefinition().getPassword()) && !Constants.isOwnerIP(channel.getRemoteAddress().toString().split(":")[0].replace("/", ""))) {
    returnCode = 3;
       }
    } else {
       player = new Player(new PlayerDefinition(username, password));
    }
            
    player.init(channel, currentLoginType);
    World.getWorld().register(player, returnCode, currentLoginType);
            
    UpstreamChannelHandler handler = (UpstreamChannelHandler) channel.getPipeline().get("upHandler");
    handler.setPlayer(player);
            
    context.getChannel().setAttachment(player);
            
    channel.getPipeline().replace("decoder", "decoder", new InBufferDecoder());*/
}

From source file:com.rs3e.network.session.impl.UpdateSession.java

License:Open Source License

/**
 * Process' the file queue./*www  .ja va2s .co m*/
 */
public void processFileQueue() {
    FileRequest request;

    synchronized (fileQueue) {
        request = fileQueue.pop();
        if (fileQueue.isEmpty()) {
            idle = true;
        } else {
            service.addPendingSession(this);
            idle = false;
        }
    }

    if (request != null) {
        int type = request.getType();
        int file = request.getFile();

        RS3Cache cache = mainContext.getCache();
        ByteBuf buf;

        try {
            if (type == 255 && file == 255)
                buf = Unpooled.wrappedBuffer(mainContext.getChecksumTable());
            else {
                buf = Unpooled.wrappedBuffer(cache.getStore().read(type, file));
                if (type != 255)
                    buf = buf.slice(0, buf.readableBytes() - 2);
            }
            channel.write(new FileResponse(request.isPriority(), type, file, buf));
        } catch (IOException ex) {
            logger.log(Level.WARNING, "Failed to service file request " + type + ", " + file + ".", ex);
        }
    }
}