List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:divconq.net.ByteToMessageDecoder.java
License:Apache License
private void expandCumulation(ChannelHandlerContext ctx, int readable) { ByteBuf oldCumulation = this.cumulation; this.cumulation = ctx.alloc().buffer(oldCumulation.readableBytes() + readable); this.cumulation.writeBytes(oldCumulation); oldCumulation.release();/*from w w w. j a v a 2 s.c o m*/ }
From source file:divconq.net.ssl.SslHandler.java
License:Apache License
private void unwrap(ChannelHandlerContext ctx, ByteBuffer packet, int initialOutAppBufCapacity) throws SSLException { // If SSLEngine expects a heap buffer for unwrapping, do the conversion. final ByteBuffer oldPacket; final ByteBuf newPacket; final int oldPos = packet.position(); if (wantsInboundHeapBuffer && packet.isDirect()) { newPacket = ctx.alloc().heapBuffer(packet.limit() - oldPos); newPacket.writeBytes(packet);/*from w w w .j a v a 2s. c om*/ oldPacket = packet; packet = newPacket.nioBuffer(); } else { oldPacket = null; newPacket = null; } boolean wrapLater = false; ByteBuf decodeOut = allocate(ctx, initialOutAppBufCapacity); try { for (;;) { final SSLEngineResult result = unwrap(engine, packet, decodeOut); final Status status = result.getStatus(); final HandshakeStatus handshakeStatus = result.getHandshakeStatus(); final int produced = result.bytesProduced(); final int consumed = result.bytesConsumed(); if (status == Status.CLOSED) { // notify about the CLOSED state of the SSLEngine. See #137 sslCloseFuture.trySuccess(ctx.channel()); break; } switch (handshakeStatus) { case NEED_UNWRAP: break; case NEED_WRAP: wrapNonAppData(ctx, true); break; case NEED_TASK: runDelegatedTasks(); break; case FINISHED: setHandshakeSuccess(); wrapLater = true; continue; case NOT_HANDSHAKING: if (setHandshakeSuccessIfStillHandshaking()) { wrapLater = true; continue; } if (flushedBeforeHandshakeDone) { // We need to call wrap(...) in case there was a flush done before the handshake completed. // // See https://github.com/netty/netty/pull/2437 flushedBeforeHandshakeDone = false; wrapLater = true; } break; default: throw new IllegalStateException("Unknown handshake status: " + handshakeStatus); } if (status == Status.BUFFER_UNDERFLOW || consumed == 0 && produced == 0) { break; } } if (wrapLater) { wrap(ctx, true); } } catch (SSLException e) { setHandshakeFailure(e); throw e; } finally { // If we converted packet into a heap buffer at the beginning of this method, // we should synchronize the position of the original buffer. if (newPacket != null) { oldPacket.position(oldPos + packet.position()); newPacket.release(); } if (decodeOut.isReadable()) { ctx.fireChannelRead(decodeOut); } else { decodeOut.release(); } } }
From source file:divconq.net.ssl.SslHandler.java
License:Apache License
private ByteBuf allocate(ChannelHandlerContext ctx, int capacity) { ByteBufAllocator alloc = ctx.alloc(); if (wantsDirectBuffer) { return alloc.directBuffer(capacity); } else {/* w w w . jav a 2 s .c o m*/ return alloc.buffer(capacity); } }
From source file:dorkbox.network.pipeline.udp.KryoEncoderUdp.java
License:Apache License
@Override protected void encode(ChannelHandlerContext context, Object message, List<Object> out) throws Exception { if (message != null) { try {/*from www . ja v a 2 s . co m*/ ByteBuf outBuffer = context.alloc().ioBuffer(maxSize); // no size info, since this is UDP, it is not segmented writeObject(this.serializationManager, context, message, outBuffer); // have to check to see if we are too big for UDP! if (outBuffer.readableBytes() > maxSize) { String msg = "Object is TOO BIG FOR UDP! " + message.toString() + " (Max " + maxSize + ", was " + outBuffer.readableBytes() + ")"; LoggerFactory.getLogger(this.getClass()).error(msg); throw new IOException(msg); } DatagramPacket packet = new DatagramPacket(outBuffer, (InetSocketAddress) context.channel().remoteAddress()); out.add(packet); } catch (Exception e) { String msg = "Unable to serialize object of type: " + message.getClass().getName(); LoggerFactory.getLogger(this.getClass()).error(msg, e); throw new IOException(msg, e); } } }
From source file:example.http2.helloworld.frame.server.HelloWorldHttp2Handler.java
License:Apache License
/** * If receive a frame with end-of-stream set, send a pre-canned response. *//*from w ww .j ava 2 s .co m*/ private static void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers) throws Exception { if (headers.isEndStream()) { ByteBuf content = ctx.alloc().buffer(); content.writeBytes(RESPONSE_BYTES.duplicate()); ByteBufUtil.writeAscii(content, " - via HTTP/2"); sendResponse(ctx, headers.stream(), content); } }
From source file:example.http2.helloworld.multiplex.server.HelloWorldHttp2Handler.java
License:Apache License
/** * If receive a frame with end-of-stream set, send a pre-canned response. *///from w w w . j av a2 s . c om private static void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers) throws Exception { if (headers.isEndStream()) { ByteBuf content = ctx.alloc().buffer(); content.writeBytes(RESPONSE_BYTES.duplicate()); ByteBufUtil.writeAscii(content, " - via HTTP/2"); sendResponse(ctx, content); } }
From source file:example.http2.helloworld.server.HelloWorldHttp1Handler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception { if (HttpUtil.is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }//www. ja va 2 s. com boolean keepAlive = HttpUtil.isKeepAlive(req); ByteBuf content = ctx.alloc().buffer(); content.writeBytes(HelloWorldHttp2Handler.RESPONSE_BYTES.duplicate()); ByteBufUtil.writeAscii(content, " - via " + req.protocolVersion() + " (" + establishApproach + ")"); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); response.headers().setInt(CONTENT_LENGTH, response.content().readableBytes()); if (!keepAlive) { ctx.write(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE); ctx.write(response); } }
From source file:gribbit.http.utils.UTF8.java
License:Open Source License
public static ByteBuf stringToUTF8ByteBuf(String str, ChannelHandlerContext ctx) { ByteBuf byteBuf = ctx.alloc().buffer(str.length() * 2); byteBuf.writeBytes(stringToUTF8(str)); return byteBuf; }
From source file:gwlpr.protocol.handshake.HandshakeHandler.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { ByteBuf buf = in.order(ByteOrder.LITTLE_ENDIAN); switch (server) { case LoginServer: // client version: {//from w ww . java2s. co m // lengthcheck if (buf.readableBytes() < (P000_ClientVersion.getLength() + P000_ClientSeed.getLength())) { return; } // get the header P000_ClientVersion.Header header = P000_ClientVersion.serializeHeader(buf); // check the header if (header == null || !P000_ClientVersion.check(header)) { return; } // get the data P000_ClientVersion.Payload payload = P000_ClientVersion.serializePayload(buf); LOGGER.debug(String.format("Got the client version: %d", payload.ClientVersion)); } break; case GameServer: // verify client: { // lengthcheck if (buf.readableBytes() < (P000_VerifyClient.getLength() + P000_ClientSeed.getLength())) { return; } // get the header P000_VerifyClient.Header header = P000_VerifyClient.serializeHeader(buf); // check the header if (header == null || !P000_VerifyClient.check(header)) { return; } // get the data verifyClient = P000_VerifyClient.serializePayload(buf); LOGGER.debug(String.format("Got the verify client packet.")); } break; } // client seed: // get the header P000_ClientSeed.Header header = P000_ClientSeed.serializeHeader(buf); // check the header if (header == null || !P000_ClientSeed.check(header)) { return; } // get the data P000_ClientSeed.Payload payload = P000_ClientSeed.serializePayload(buf); LOGGER.debug("Got the client seed packet."); // INITIALIZE ENCRYPTION WITH THE CLIENT SEED PAYLOAD // generate the shared key byte[] sharedKeyBytes = EncryptionUtils.generateSharedKey(payload.ClientPublicKey); // start RC4 key generation byte[] randomBytes = new byte[20]; new SecureRandom().nextBytes(randomBytes); final byte[] rc4Key = EncryptionUtils.hash(randomBytes); // encrypt the RC4 key before sending it to the client byte[] xoredRandomBytes = EncryptionUtils.XOR(randomBytes, sharedKeyBytes); // INITIALIZATION OF ENCRYPTION DONE // we can set the RC4 decoder now... if encryption is enabled if (encryption == EncryptionOptions.Enable) { RC4Codec.Decoder decoder = new RC4Codec.Decoder(rc4Key); ctx.pipeline().addFirst(decoder); LOGGER.debug("RC4Decoder added to pipeline."); } // now send the server seed packet P001_ServerSeed serverSeed = new P001_ServerSeed(); serverSeed.setEncryptedRC4Key(xoredRandomBytes); buf = ctx.alloc().buffer(70).order(ByteOrder.LITTLE_ENDIAN); serverSeed.serializeInto(buf); ChannelFuture cf = ctx.writeAndFlush(buf); // also remove this handler ctx.pipeline().remove(this); // set the RC4 encoder only after the serverseed packet has been send! cf.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (encryption == EncryptionOptions.Enable) { // add the rc4 codec if encryption is enabled RC4Codec.Encoder encoder = new RC4Codec.Encoder(rc4Key); ctx.pipeline().addFirst(encoder); LOGGER.debug("RC4Encoder added to pipeline."); } // tell the channel's context that handshake has been done ctx.channel().attr(GameAppContextKey.KEY).get() .trigger(new HandShakeDoneEvent(ctx.channel(), verifyClient)); } }); }
From source file:herddb.network.netty.DataMessageEncoder.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { Message m = (Message) msg;//from w w w . j a v a 2s . com ByteBuf encoded = ctx.alloc().buffer(); MessageUtils.encodeMessage(encoded, m); ctx.writeAndFlush(encoded, promise); }