List of usage examples for io.netty.channel ChannelHandlerContext name
String name();
From source file:eu.jangos.realm.network.decoder.RealmPacketDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { logger.debug("Packet received: " + in.readableBytes()); // We should at least get the header. if (in.readableBytes() < HEADER_LENGTH) { logger.debug("Packet received but less than header size."); return;//from w ww . j a v a 2s.c o m } ByteBuf msg = in.order(ByteOrder.LITTLE_ENDIAN); // We should decrypt the header only once per packet. if (opcode == 0) { byte[] header = new byte[HEADER_LENGTH]; int readBytes = (ctx.channel().attr(AUTH).get() == AuthStep.STEP_AUTHED ? HEADER_LENGTH : 4); for (int i = 0; i < readBytes; i++) { header[i] = msg.readByte(); } header = ctx.channel().attr(CRYPT).get().decrypt(header); size = (short) ((header[0] << 8 | header[1]) & 0xFF); opcode = (short) ((header[3] << 8 | header[2] & 0xFF)); logger.debug("Opcode received: " + opcode + ", with size: " + size + " (readable bytes: " + in.readableBytes() + ") "); } if ((in.readableBytes() + 4) < size) { logger.debug( "Packet size is higher than the available bytes. (" + in.readableBytes() + ", " + size + ")"); return; } final Opcodes code = Opcodes.convert(opcode); if (code == null) { return; } AbstractRealmClientPacket packet = null; switch (code) { case CMSG_PING: packet = new CMSG_PING(code, size); break; case CMSG_AUTH_SESSION: packet = new CMSG_AUTH_SESSION(code, (short) 0); break; case CMSG_CHAR_ENUM: packet = new CMSG_CHAR_ENUM(code, size); break; case CMSG_CHAR_CREATE: packet = new CMSG_CHAR_CREATE(code, size); break; case CMSG_CHAR_DELETE: packet = new CMSG_CHAR_DELETE(code, size); break; case CMSG_PLAYER_LOGIN: packet = new CMSG_PLAYER_LOGIN(code, size); break; default: logger.debug("Context: " + ctx.name() + "Packet received, opcode not supported: " + code); msg.clear(); ctx.close(); break; } if (packet != null) { try { logger.debug("Context: " + ctx.name() + "Packet received, opcode: " + code); logger.debug("Packet content: \n" + StringUtils.toPacketString(ByteBufUtil.hexDump(msg).toUpperCase(), size, code)); packet.decode(msg); opcode = 0; size = 0; } catch (Exception e) { return; } out.add(packet); msg.clear(); } }
From source file:eu.jangos.realm.network.encoder.RealmPacketEncoder.java
License:Open Source License
@Override protected void encode(ChannelHandlerContext ctx, AbstractRealmServerPacket msg, ByteBuf out) throws Exception { logger.debug("Context: " + ctx.name() + ", packet: " + msg.toString()); msg.encode(out);// w w w. j a va2 s.co m logger.debug("Packet content: \n" + StringUtils.toPacketString(ByteBufUtil.hexDump(out).toUpperCase(), msg.getSize(), msg.getCode())); // Reversing header. reverseHeader(ctx, out); }
From source file:eu.jangos.realm.network.handler.RealmAuthHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { AbstractRealmClientPacket request = (AbstractRealmClientPacket) msg; // By default, response is no access for a login activity. AbstractRealmServerPacket response = new SMSG_AUTH_RESPONSE(Opcodes.SMSG_AUTH_RESPONSE); logger.info(msg.toString());//from w ww . j ava2s . com switch (request.getOpcode()) { case CMSG_AUTH_SESSION: if (ctx.channel().attr(AUTH).get() != AuthStep.STEP_AUTHING) { logger.error("Client is sending a CMSG_AUTH_SESSION packet again while being authenticating."); ctx.close(); return; } this.cAuthSession = (CMSG_AUTH_SESSION) request; // Checking build number. if (this.cAuthSession.getBuild() < Integer.parseInt(parameterService.getParameter("minSupportedBuild")) || this.cAuthSession.getBuild() > Integer .parseInt(parameterService.getParameter("maxSupportedBuild"))) { logger.debug("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount() + " : Build is not supported."); ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_VERSION_INVALID); break; } // Checking account existence. if (!this.accountService.checkExistence(this.cAuthSession.getAccount().toUpperCase())) { logger.debug("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount() + " : Account does not exist."); ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_UNKNOWN_ACCOUNT); break; } account = this.accountService.getAccount(this.cAuthSession.getAccount()); // Checking if this account is the one logging into the authentication server. if (!account.getLastIp() .equals(((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress())) { logger.debug("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount() + " : IP is not the same one than the one used to authenticate."); ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_FAIL_NOACCESS); break; } // Checking if account is locked. if (account.isLocked()) { logger.debug("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount() + " : Account is locked."); ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_BANNED); break; } // Checking if account is banned -- Includes IP & Account. if (this.accountService.isBanned(account, ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress())) { logger.debug("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount() + " : Account is banned."); ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_BANNED); break; } // At this step, we can start making the calculation. try { BigNumber K = new BigNumber(account.getSessionkey(), 16); if (AuthUtils.checkClientDigest(this.cAuthSession.getAccount(), seed, this.cAuthSession.getSeed(), K, this.cAuthSession.getDigest())) { // We are happy that client could login. logger.info("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount() + " : Account is logged in."); worldService.addSession(account.getId(), ctx); // Initializing the crypt. ctx.channel().attr(CRYPT).get().init(K.asByteArray()); ctx.channel().attr(AUTH).set(AuthStep.STEP_AUTHED); ctx.channel().attr(ACCOUNT).set(account); ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_SUCCESS); // We send add-on data as well. SMSG_ADDON_INFO packet = new SMSG_ADDON_INFO(); packet.setListAddons(((CMSG_AUTH_SESSION) request).getListAddon()); ctx.write(packet); } else { // Well, the calculation went wrong. logger.info("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount() + " : Can't verify the hash."); ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_FAIL_NOACCESS); break; } } catch (NoSuchAlgorithmException nsa) { // Something went wrong, aborting connection. logger.info("Context: " + ctx.name() + ", account: " + this.cAuthSession.getAccount() + " : Problem to find an algorithm."); ((SMSG_AUTH_RESPONSE) response).setResult(AuthEnum.AUTH_FAIL_FAIL_NOACCESS); break; } break; default: logger.error("Packet received, opcode not handled: " + request.getOpcode()); response = null; break; } if (response != null) { ctx.writeAndFlush(response); } else { // Let pass this to other handlers. ctx.fireChannelRead(msg); } }
From source file:example.http2.helloworld.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *//*from ww w .ja v a 2 s. c om*/ private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); final HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory); final CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler = new CleartextHttp2ServerUpgradeHandler( sourceCodec, upgradeHandler, new HelloWorldHttp2HandlerBuilder().build()); p.addLast(cleartextHttp2ServerUpgradeHandler); p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
From source file:http2.server.Http2ServerInitializer.java
License:Apache License
/** * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0 *//*from ww w . ja v a2 s .com*/ private void configureClearText(SocketChannel ch) { final ChannelPipeline p = ch.pipeline(); final HttpServerCodec sourceCodec = new HttpServerCodec(); p.addLast(sourceCodec); p.addLast(new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory)); // ? p.addLast(new SimpleChannelInboundHandler<HttpMessage>() { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception { // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP. System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)"); ChannelPipeline pipeline = ctx.pipeline(); ChannelHandlerContext thisCtx = pipeline.context(this); pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted.")); pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength)); ctx.fireChannelRead(ReferenceCountUtil.retain(msg)); } }); p.addLast(new UserEventLogger()); }
From source file:io.grpc.alts.internal.TsiHandshakeHandler.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // Process the data. If we need to send more data, do so now. if (handshaker.processBytesFromPeer(in) && handshaker.isInProgress()) { sendHandshake(ctx);/*from w w w. ja va2 s . c o m*/ } // If the handshake is complete, transition to the framing state. if (!handshaker.isInProgress()) { TsiPeer peer = handshaker.extractPeer(); Object authContext = handshaker.extractPeerObject(); SecurityDetails details = handshakeValidator.validatePeerObject(authContext); // createFrameProtector must be called last. TsiFrameProtector protector = handshaker.createFrameProtector(ctx.alloc()); TsiFrameHandler framer; boolean success = false; try { framer = new TsiFrameHandler(protector); // adding framer and next handler after this handler before removing Decoder (current // handler). This will prevents any missing read from decoder and/or unframed write from // next handler. ctx.pipeline().addAfter(ctx.name(), null, framer); ctx.pipeline().addAfter(ctx.pipeline().context(framer).name(), null, next); ctx.pipeline().remove(ctx.name()); fireProtocolNegotiationEvent(ctx, peer, authContext, details); success = true; } finally { if (!success && protector != null) { protector.destroy(); } } } }
From source file:io.grpc.netty.WriteBufferingAndExceptionHandler.java
License:Apache License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addBefore(ctx.name(), null, next); super.handlerAdded(ctx); // kick off protocol negotiation. ctx.pipeline().fireUserEventTriggered(ProtocolNegotiationEvent.DEFAULT); }
From source file:io.hekate.network.netty.NettyClientTimeoutHandler.java
License:Apache License
private void mayBeRegisterHeartbeatHandler(NettyClientHandshakeEvent evt, ChannelHandlerContext ctx) { int interval = evt.hbInterval(); int threshold = evt.hbLossThreshold(); boolean disableHeartbeats = evt.isHbDisabled(); ChannelPipeline pipe = ctx.pipeline(); if (idleTimeout > 0) { if (trace) { log.trace("Registering idle connection handler [to={}, idle-timeout={}]", id, idleTimeout); }/*from w w w . j a v a 2s .co m*/ pipe.addBefore(ctx.name(), "idle-channel-handler", new HeartbeatOnlyIdleStateHandler(idleTimeout)); } if (interval > 0 && threshold > 0) { int readerIdle = interval * threshold; int writerIdle = disableHeartbeats ? 0 : interval; if (trace) { log.trace("Registering heartbeat handler [to={}, reader-idle={}, writer-idle={}]", id, readerIdle, writerIdle); } pipe.addBefore(ctx.name(), "heartbeat-handler", new IdleStateHandler(readerIdle, writerIdle, 0, TimeUnit.MILLISECONDS)); } }
From source file:io.liveoak.container.protocols.websocket.WebSocketStompFrameDecoder.java
License:Open Source License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addAfter(ctx.name(), "stomp-frame-decoder", new StompFrameDecoder()); }
From source file:io.liveoak.container.protocols.websocket.WebSocketStompFrameEncoder.java
License:Open Source License
@Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { ctx.pipeline().addAfter(ctx.name(), "stomp-frame-encoder", new StompFrameEncoder()); }