public void operationComplete(ChannelFuture future) { p.remove(httpEncoderName); } });
@Override public void applyProtocol(PlayerSession playerSession) { LOG.trace("Going to apply {} on session: {}", getProtocolName(), playerSession); ChannelPipeline pipeline = NettyUtils .getPipeLineOfConnection(playerSession); pipeline.addLast("textWebsocketDecoder", textWebsocketDecoder); pipeline.addLast("eventHandler", new DefaultToServerHandler( playerSession)); pipeline.addLast("textWebsocketEncoder", textWebsocketEncoder); // Since the pipeline was not cleared for this protocol do some cleanup // manually. pipeline.remove(LoginProtocol.LOGIN_HANDLER_NAME); pipeline.remove(AbstractNettyProtocol.IDLE_CHECK_HANDLER); pipeline.remove(AbstractNettyProtocol.IDLE_STATE_CHECK_HANDLER); }
public void operationComplete(ChannelFuture future) throws Exception { logger.info("remove unused channel handlers after authentication is done successfully."); ctx.getPipeline().remove(HandshakeInitializationHandler.class.getName()); ctx.getPipeline().remove(ClientAuthenticationHandler.class.getName());
/** * Passes the join complete message to the client, and marks the entities joining as successful. * @param channelHandlerContext * @param joinComplete */ private void completeJoin(ChannelHandlerContext channelHandlerContext, NetData.JoinCompleteMessage joinComplete) { logger.info("Join complete received"); server.setClientId(joinComplete.getClientId()); channelHandlerContext.getPipeline().remove(this); channelHandlerContext.getPipeline().get(ClientHandler.class).joinComplete(server); joinStatus.setComplete(); }
/** * Replace the HTTP decoder with a new Web Socket decoder. * Note that we do not use {@link ChannelPipeline#replace(String, String, ChannelHandler)}, because the server * might have sent the first frame immediately after the upgrade response. In such a case, the HTTP decoder might * have the first frame in its cumulation buffer and the HTTP decoder will forward it to the next handler. * The Web Socket decoder will not receive it if we simply replaced it. For more information, refer to * {@link HttpResponseDecoder} and its unit tests. */ static void replaceDecoder(Channel channel, ChannelHandler wsDecoder) { ChannelPipeline p = channel.getPipeline(); ChannelHandlerContext httpDecoderCtx = p.getContext(HttpResponseDecoder.class); if (httpDecoderCtx == null) { throw new IllegalStateException("can't find an HTTP decoder from the pipeline"); } p.addAfter(httpDecoderCtx.getName(), "ws-decoder", wsDecoder); p.remove(httpDecoderCtx.getName()); } }
/** * Process the handshake verification, checking that both the server and client have attempted it. If successful marks the channel as Authenticated. * @param handshakeVerification * @param ctx Channel Handler Context. */ private void processHandshakeVerification(NetData.HandshakeVerification handshakeVerification, ChannelHandlerContext ctx) { logger.info("Received server verification"); if (serverHello == null || clientHello == null) { logger.error("Received server verification without requesting it: cancelling authentication"); joinStatus.setErrorMessage(AUTHENTICATION_FAILURE); ctx.getChannel().close(); return; } if (!serverCertificate.verify(HandshakeCommon.getSignatureData(serverHello, clientHello), handshakeVerification.getSignature().toByteArray())) { logger.error("Server failed verification: cancelling authentication"); joinStatus.setErrorMessage(AUTHENTICATION_FAILURE); ctx.getChannel().close(); return; } // And we're authenticated. ctx.getPipeline().remove(this); channelAuthenticated(ctx); }
/** * Replace this {@link FrameDecoder} in the {@link ChannelPipeline} with the given {@link ChannelHandler}. All * remaining bytes in the {@link ChannelBuffer} will get send to the new {@link ChannelHandler} that was used * as replacement * */ public void replace(String handlerName, ChannelHandler handler) { if (ctx == null) { throw new IllegalStateException( "Replace cann only be called once the FrameDecoder is added to the ChannelPipeline"); } ChannelPipeline pipeline = ctx.getPipeline(); pipeline.addAfter(ctx.getName(), handlerName, handler); try { if (cumulation != null) { Channels.fireMessageReceived(ctx, cumulation.readBytes(actualReadableBytes())); } } finally { pipeline.remove(this); } }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, State state) throws Exception { switch (state) { case CHECK_PROTOCOL_VERSION: { version = SocksMessage.ProtocolVersion.fromByte(buffer.readByte()); if (version != SocksMessage.ProtocolVersion.SOCKS5) { break; } checkpoint(State.READ_AUTH_SCHEMES); } case READ_AUTH_SCHEMES: { authSchemes.clear(); authSchemeNum = buffer.readByte(); for (int i = 0; i < authSchemeNum; i++) { authSchemes.add(SocksMessage.AuthScheme.fromByte(buffer.readByte())); } msg = new SocksInitRequest(authSchemes); break; } } ctx.getPipeline().remove(this); return msg; }
public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { // Get the SslHandler from the ChannelPipeline so we can obtain the SslEngine from it. SslHandler handler = ctx.getPipeline().get(SslHandler.class); if (handler == null) { // SslHandler is needed by SPDY by design. throw new IllegalStateException("SslHandler is needed for SPDY"); } ChannelPipeline pipeline = ctx.getPipeline(); SelectedProtocol protocol = getProtocol(handler.getEngine()); switch (protocol) { case None: // Not done with choosing the protocol, so just return here for now, return; case SpdyVersion3_1: addSpdyHandlers(ctx, SpdyVersion.SPDY_3_1); break; case HttpVersion1_0: case HttpVersion1_1: addHttpHandlers(ctx); break; default: throw new IllegalStateException("Unknown SelectedProtocol"); } // When we reached here we can remove this handler as its now clear what protocol we want to use // from this point on. pipeline.remove(this); ctx.sendUpstream(e); }
private void processClientHandshake(NetData.HandshakeHello clientHello, NetData.HandshakeVerification handshakeVerification, ChannelHandlerContext ctx) { logger.info("Received client certificate"); PublicIdentityCertificate clientCert = NetMessageUtil.convert(clientHello.getCertificate()); if (!clientCert.verifySignedBy(config.getSecurity().getServerPublicCertificate())) { logger.error("Received invalid client certificate, ending connection attempt"); ctx.getChannel().close(); return; } byte[] clientSignature = handshakeVerification.getSignature().toByteArray(); byte[] signatureData = HandshakeCommon.getSignatureData(serverHello, clientHello); if (!clientCert.verify(signatureData, clientSignature)) { logger.error("Received invalid verification signature, ending connection attempt"); ctx.getChannel().close(); return; } logger.info("Sending server verification"); byte[] serverSignature = config.getSecurity().getServerPrivateCertificate().sign(signatureData); ctx.getChannel().write(NetData.NetMessage.newBuilder() .setHandshakeVerification(NetData.HandshakeVerification.newBuilder() .setSignature(ByteString.copyFrom(serverSignature))).build()); // Identity has been established, inform the server handler and withdraw from the pipeline ctx.getPipeline().remove(this); serverConnectionHandler.channelAuthenticated(clientCert); }
/** * Upgrades the connection and send the handshake response. */ protected ChannelFuture writeHandshakeResponse( Channel channel, HttpResponse res, ChannelHandler encoder, ChannelHandler decoder) { final ChannelPipeline p = channel.getPipeline(); if (p.get(HttpChunkAggregator.class) != null) { p.remove(HttpChunkAggregator.class); } final String httpEncoderName = p.getContext(HttpResponseEncoder.class).getName(); p.addAfter(httpEncoderName, "wsencoder", encoder); p.get(HttpRequestDecoder.class).replace("wsdecoder", decoder); final ChannelFuture future = channel.write(res); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { p.remove(httpEncoderName); } }); return future; }
ctx.getPipeline().remove(this); serverConnectionHandler.channelAuthenticated(clientCertificates.getPublicCert()); } catch (BadEncryptedDataException e) {
private void receivedConnect(NetData.JoinMessage message) { logger.info("Received Start Join"); NetClient client = new NetClient(channelHandlerContext.getChannel(), networkSystem, identity); client.setPreferredName(message.getName()); client.setColor(new Color(message.getColor().getRgba())); client.setViewDistanceMode(ViewDistance.forIndex(message.getViewDistanceLevel())); channelHandlerContext.getPipeline().remove(this); serverHandler.connectionComplete(client); }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, State state) throws Exception { switch (state) { case CHECK_PROTOCOL_VERSION: { version = SocksMessage.ProtocolVersion.fromByte(buffer.readByte()); if (version != SocksMessage.ProtocolVersion.SOCKS5) { break; } checkpoint(State.READ_PREFFERED_AUTH_TYPE); } case READ_PREFFERED_AUTH_TYPE: { authScheme = SocksMessage.AuthScheme.fromByte(buffer.readByte()); msg = new SocksInitResponse(authScheme); break; } } ctx.getPipeline().remove(this); return msg; }
ctx.getPipeline().remove(this); channelAuthenticated(ctx); } catch (InvalidProtocolBufferException e) {
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, State state) throws Exception { switch (state) { case CHECK_PROTOCOL_VERSION: { version = SocksMessage.SubnegotiationVersion.fromByte(buffer.readByte()); if (version != SocksMessage.SubnegotiationVersion.AUTH_PASSWORD) { break; } checkpoint(State.READ_AUTH_RESPONSE); } case READ_AUTH_RESPONSE: { authStatus = SocksMessage.AuthStatus.fromByte(buffer.readByte()); msg = new SocksAuthResponse(authStatus); } } ctx.getPipeline().remove(this); return msg; }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { // Will use the first bytes to detect a protocol. if (buffer.readableBytes() < bytesForProtocolCheck) { return null; } ChannelPipeline pipeline = ctx.getPipeline(); if (!loginProtocol.applyProtocol(buffer, pipeline)) { byte[] headerBytes = new byte[bytesForProtocolCheck]; buffer.getBytes(buffer.readerIndex(), headerBytes, 0, bytesForProtocolCheck); LOG.error( "Unknown protocol, discard everything and close the connection {}. Incoming Bytes {}", ctx.getChannel().getId(), BinaryUtils.getHexString(headerBytes)); close(buffer, channel); return null; } else { pipeline.remove(this); } // Forward the current read buffer as is to the new handlers. return buffer.readBytes(buffer.readableBytes()); }
@Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, State state) throws Exception { switch (state) { case CHECK_PROTOCOL_VERSION: { version = SocksMessage.SubnegotiationVersion.fromByte(buffer.readByte()); if (version != SocksMessage.SubnegotiationVersion.AUTH_PASSWORD) { break; } checkpoint(State.READ_USERNAME); } case READ_USERNAME: { fieldLength = buffer.readByte(); username = buffer.readBytes(fieldLength).toString(CharsetUtil.US_ASCII); checkpoint(State.READ_PASSWORD); } case READ_PASSWORD: { fieldLength = buffer.readByte(); password = buffer.readBytes(fieldLength).toString(CharsetUtil.US_ASCII); msg = new SocksAuthRequest(username, password); } } ctx.getPipeline().remove(this); return msg; }
ctx.getPipeline().remove(this); return msg;