Example usage for io.netty.channel ChannelHandlerContext alloc

List of usage examples for io.netty.channel ChannelHandlerContext alloc

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext alloc.

Prototype

ByteBufAllocator alloc();

Source Link

Document

Return the assigned ByteBufAllocator which will be used to allocate ByteBuf s.

Usage

From source file:com.vethrfolnir.login.network.mu.ClientChannelHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buff = (ByteBuf) msg;//from   w  w  w. ja va2  s  .com

    switch (buff.getUnsignedByte(0)) {
    case 0xC1:
    case 0xC2:
    case 0xC3:
    case 0xC4:
        break;
    default:
        ctx.close();
        buff.release(); //TODO: maybe add a flood protector?
        log.warn("Client[" + ctx.channel() + "] is not a mu online client! Disconnecting!");
        return;
    }

    // we are not interested in the header and size;
    buff.readerIndex(2);

    int opcode = buff.readUnsignedShort();

    switch (opcode) {

    case 0xf4_03: { // Request Server information
        int serverId = buff.readUnsignedByte();
        ByteBuf buf = ctx.alloc().heapBuffer().order(ByteOrder.LITTLE_ENDIAN);

        WritePacket packet = SendServerInfo.StaticPacket;
        packet.write(null, buf, nameService, serverId);
        packet.markLength(buf);
        ;

        ctx.writeAndFlush(buf);
        break;
    }
    case 0xf4_06: { // Request Server list
        ByteBuf buf = ctx.alloc().heapBuffer().order(ByteOrder.LITTLE_ENDIAN);

        WritePacket packet = SendServerLists.StaticPacket;
        packet.write(null, buf, nameService);
        packet.markLength(buf);

        ctx.writeAndFlush(buf);
        break;
    }
    default:
        log.warn("Unkown packet[OPCODE = " + Integer.toHexString(opcode) + "] Dump: "
                + PrintData.printData(buff.nioBuffer(0, buff.writerIndex())));
        ctx.close();
        break;
    }
    buff.release();
}

From source file:com.xiovr.unibot.bot.network.impl.ConnectionEncoderImpl.java

License:Open Source License

@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {

    if (!(msg instanceof Packet)) {
        ctx.write(msg, promise);//  w w  w.j a  v a  2  s  .  co  m
        return;
    }

    final Packet pck = (Packet) msg;
    //      System.out.println("Encoded packet pck.len=" + pck.getPosition());

    int size = pck.getPosition();

    ByteBuf encoded = ctx.alloc().heapBuffer(size);

    //      final byte[] encArr = encoded.array();
    final byte[] pckArr = pck.getBuf().array();

    encoded.writeBytes(pckArr, 0, size);

    //      System.arraycopy(pckArr, 0, encArr, encoded.writerIndex(),size); 

    //      encoded.writerIndex(encoded.writerIndex()+pck.getPosition());
    ctx.write(encoded, promise);
    PacketPool.free(pck);
}

From source file:com.xx_dev.apn.proxy.ApnProxyAESDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (this.state()) {
    case READ_MAGIC_NUMBER: {
        int magicNumber = in.readInt();
        if (magicNumber != 0x34ed2b11) {
            throw new Exception("Wrong magic number!");
        }//  ww  w. ja va  2  s  .c  o  m
        this.checkpoint(STATE.READ_LENGTH);
    }
    case READ_LENGTH: {
        length = in.readInt();
        if (length > 1024 * 512 + 1000) {
            ctx.close();
        }
        this.checkpoint(STATE.READ_CONTENT);
    }
    case READ_CONTENT: {
        c1.init(Cipher.DECRYPT_MODE, securekey, iv);
        byte[] data = new byte[length];
        in.readBytes(data, 0, length);
        byte[] raw = c1.doFinal(data);
        ByteBuf outBuf = ctx.alloc().buffer();
        outBuf.writeBytes(raw);
        out.add(outBuf);
        this.checkpoint(STATE.READ_MAGIC_NUMBER);
        break;
    }
    default:
        throw new Error("Shouldn't reach here.");
    }

}

From source file:com.xx_dev.apn.socks.local.FakeHttpClientDecoder.java

License:Apache License

protected void _decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (this.state()) {
    case READ_FAKE_HTTP: {
        int fakeHttpHeadStartIndex = in.readerIndex();

        int fakeHttpHeadEndIndex = in.forEachByte(new ByteBufProcessor() {
            int c = 0;

            @Override/*w w  w  . ja  va 2  s  .  c  o m*/
            public boolean process(byte value) throws Exception {

                if (value == '\r' || value == '\n') {
                    c++;
                } else {
                    c = 0;
                }

                //logger.info("value=" + value + ", c=" + c);

                if (c >= 4) {
                    return false;
                } else {
                    return true;
                }
            }
        });

        logger.debug("s: " + fakeHttpHeadStartIndex);
        logger.debug("e: " + fakeHttpHeadEndIndex);

        if (fakeHttpHeadEndIndex == -1) {
            logger.warn("w: " + fakeHttpHeadStartIndex);
            break;
        }

        byte[] buf = new byte[fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1];
        in.readBytes(buf, 0, fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1);
        String s = TextUtil.fromUTF8Bytes(buf);

        //logger.info(s);

        String[] ss = StringUtils.split(s, "\r\n");

        //System.out.println(s + "" + this + " " + Thread.currentThread().getName());

        for (String line : ss) {
            if (StringUtils.startsWith(line, "X-C:")) {
                String lenStr = StringUtils.trim(StringUtils.split(line, ":")[1]);
                //System.out.println(lenStr + "" + this + " " + Thread.currentThread().getName());
                //System.out.println("*****************************************");
                try {
                    length = Integer.parseInt(lenStr, 16);
                    trafficLogger.info("D," + LocalConfig.ins().getUser() + "," + length);
                } catch (Throwable t) {
                    logger.error("--------------------------------------");
                    logger.error(s + "" + this + " " + Thread.currentThread().getName());
                    logger.error("--------------------------------------");
                }

            }
        }

        this.checkpoint(STATE.READ_CONTENT);
    }
    case READ_CONTENT: {
        if (length > 0) {
            byte[] buf = new byte[length];
            in.readBytes(buf, 0, length);

            byte[] res = new byte[length];

            for (int i = 0; i < length; i++) {
                res[i] = (byte) (buf[i] ^ (LocalConfig.ins().getEncryptKey() & 0xFF));
            }

            ByteBuf outBuf = ctx.alloc().buffer();

            outBuf.writeBytes(res);

            out.add(outBuf);
        }

        this.checkpoint(STATE.READ_FAKE_HTTP);
        break;
    }
    default:
        throw new Error("Shouldn't reach here.");
    }

}

From source file:com.xx_dev.apn.socks.remote.FakeHttpServerDecoder.java

License:Apache License

protected void _decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    switch (this.state()) {
    case READ_FAKE_HTTP: {
        int fakeHttpHeadStartIndex = in.readerIndex();

        int fakeHttpHeadEndIndex = in.forEachByte(new ByteBufProcessor() {
            int c = 0;

            @Override//from w ww.  j  a  va  2 s  . c  om
            public boolean process(byte value) throws Exception {

                if (value == '\r' || value == '\n') {
                    c++;
                } else {
                    c = 0;
                }

                //logger.info("value=" + value + ", c=" + c);

                if (c >= 4) {
                    return false;
                } else {
                    return true;
                }
            }
        });

        logger.debug("s: " + fakeHttpHeadStartIndex);
        logger.debug("e: " + fakeHttpHeadEndIndex);

        if (fakeHttpHeadEndIndex == -1) {
            logger.warn("w: " + fakeHttpHeadStartIndex);
            break;
        }

        byte[] buf = new byte[fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1];
        in.readBytes(buf, 0, fakeHttpHeadEndIndex - fakeHttpHeadStartIndex + 1);
        String s = TextUtil.fromUTF8Bytes(buf);

        //logger.info(s);

        String[] ss = StringUtils.split(s, "\r\n");

        //System.out.println(s + "" + this + " " + Thread.currentThread().getName());

        for (String line : ss) {
            if (StringUtils.startsWith(line, "X-C:")) {
                String lenStr = StringUtils.trim(StringUtils.split(line, ":")[1]);
                //System.out.println(lenStr + "" + this + " " + Thread.currentThread().getName());
                //System.out.println("*****************************************");
                try {
                    length = Integer.parseInt(lenStr, 16);
                } catch (Throwable t) {
                    logger.error("--------------------------------------");
                    logger.error(s + "" + this + " " + Thread.currentThread().getName());
                    logger.error("--------------------------------------");
                }

            }

            if (StringUtils.startsWith(line, "X-U:")) {
                String user = StringUtils.trim(StringUtils.split(line, ":")[1]);
                ctx.channel().attr(NettyAttributeKey.LINK_USER).set(user);
                logger.info(user);
            }
        }

        this.checkpoint(STATE.READ_CONTENT);
    }
    case READ_CONTENT: {

        trafficLogger.info("U," + ctx.channel().attr(NettyAttributeKey.LINK_USER).get() + "," + length);

        if (length > 0) {

            byte[] buf = new byte[length];
            in.readBytes(buf, 0, length);

            byte[] res = new byte[length];

            for (int i = 0; i < length; i++) {
                res[i] = (byte) (buf[i] ^ (RemoteConfig.ins().getEncryptKey() & 0xFF));
            }

            ByteBuf outBuf = ctx.alloc().buffer();

            outBuf.writeBytes(res);

            out.add(outBuf);
        }

        this.checkpoint(STATE.READ_FAKE_HTTP);
        break;
    }
    default:
        throw new Error("Shouldn't reach here.");
    }

}

From source file:com.zaradai.distributor.messaging.netty.handler.AbstractHandshakeHandler.java

License:Apache License

private void beginHandshake(ChannelHandlerContext handlerContext) {
    if (client) {
        final ByteBuf buffer = handlerContext.alloc().buffer(BUFFER_SIZE);
        clientWrite(buffer);//  w w w  .jav a2 s .c  o m
        handlerContext.writeAndFlush(buffer);
    }
}

From source file:com.zaradai.distributor.messaging.netty.handler.AbstractHandshakeHandler.java

License:Apache License

private void decodeAsServer(ChannelHandlerContext handlerContext, ByteBuf in) {
    if (serverReadAndValidate(handlerContext, in)) {
        final ByteBuf buffer = handlerContext.alloc().buffer(BUFFER_SIZE);
        serverWrite(buffer);/*from ww w  .  j av  a 2 s. c o m*/
        handlerContext.writeAndFlush(buffer);
        notifyHandshakeSuccess(handlerContext);
    } else {
        notifyHandshakeFailure(handlerContext, new MessagingException("Invalid Header"));
    }
}

From source file:de.jackwhite20.cascade.shared.pipeline.handler.PacketEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, Packet packet, List<Object> out) throws Exception {

    try {//from  w w w  . j a  va2  s.  c o  m
        byte id = protocol.findId(packet.getClass());

        ByteBuf byteBuf = ctx.alloc().buffer();
        byteBuf.writeByte(id);
        packet.write(byteBuf);

        out.add(byteBuf);
    } catch (IllegalStateException e) {
        ctx.fireExceptionCaught(e);
    }
}

From source file:de.jackwhite20.japs.shared.pipeline.handler.JSONObjectEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, JSONObject jsonObject, List<Object> out) throws Exception {

    out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(jsonObject.toString()), CharsetUtil.UTF_8));
}

From source file:de.unipassau.isl.evs.ssh.core.network.handler.Decrypter.java

License:Open Source License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> decoded) throws Exception {
    try {//from  www .  j  a  va2  s  .c o  m
        final int encryptedLength = in.readInt();
        final int decryptedLength = decryptCipher.getOutputSize(encryptedLength);

        final ByteBuf out = ctx.alloc().buffer(decryptedLength);
        //Log.v(TAG, "Decrypting " + encryptedLength + "b data to " + decryptedLength + "b of decrypted data");
        decryptCipher.doFinal(in.nioBuffer(in.readerIndex(), encryptedLength),
                out.nioBuffer(out.writerIndex(), decryptedLength));
        out.writerIndex(out.writerIndex() + decryptedLength);
        in.readerIndex(in.readerIndex() + encryptedLength);

        decoded.add(out);
    } catch (GeneralSecurityException | RuntimeException e) {
        ctx.close();
        throw e;
    }
}