use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project scalecube by scalecube.
the class NettyStreamChannelInitializer method initChannel.
@Override
protected void initChannel(Channel channel) {
ChannelPipeline pipeline = channel.pipeline();
// contexs contexts contexs
channel.pipeline().addLast(channelContextHandler);
// frame codecs
pipeline.addLast(new LengthFieldPrepender(LENGTH_FIELD_LENGTH));
pipeline.addLast(new LengthFieldBasedFrameDecoder(MAX_FRAME_LENGTH, 0, LENGTH_FIELD_LENGTH, 0, LENGTH_FIELD_LENGTH));
// message acceptor
pipeline.addLast(messageHandler);
// at-least-something exception handler
pipeline.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable throwable) {
// Hint: at this point one can look at throwable, make some exception translation, and via channelContext post
// ChannelContextError event, and hence give business layer ability to react on low level system error events
LOGGER.warn("Exception caught for channel {}, {}", ctx.channel(), throwable);
}
});
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project drill by apache.
the class UserServer method getHandshakeHandler.
@Override
protected ServerHandshakeHandler<UserToBitHandshake> getHandshakeHandler(final BitToUserConnection connection) {
return new ServerHandshakeHandler<UserToBitHandshake>(RpcType.HANDSHAKE, UserToBitHandshake.PARSER) {
@Override
protected void consumeHandshake(ChannelHandlerContext ctx, UserToBitHandshake inbound) throws Exception {
BitToUserHandshake handshakeResp = getHandshakeResponse(inbound);
OutboundRpcMessage msg = new OutboundRpcMessage(RpcMode.RESPONSE, this.handshakeType, coordinationId, handshakeResp);
ctx.writeAndFlush(msg);
if (handshakeResp.getStatus() != HandshakeStatus.SUCCESS && handshakeResp.getStatus() != HandshakeStatus.AUTH_REQUIRED) {
// If handling handshake results in an error, throw an exception to terminate the connection.
throw new RpcException("Handshake request failed: " + handshakeResp.getErrorMessage());
}
}
@Override
public BitToUserHandshake getHandshakeResponse(UserToBitHandshake inbound) throws Exception {
if (logger.isTraceEnabled()) {
logger.trace("Handling handshake from user to bit. {}", serializeUserToBitHandshakeWithoutPassword(inbound));
}
// if timeout is unsupported or is set to false, disable timeout.
if (!inbound.hasSupportTimeout() || !inbound.getSupportTimeout()) {
connection.disableReadTimeout();
logger.warn("Timeout Disabled as client {} doesn't support it.", connection.getName());
}
BitToUserHandshake.Builder respBuilder = BitToUserHandshake.newBuilder().setRpcVersion(UserRpcConfig.RPC_VERSION).setServerInfos(UserRpcUtils.getRpcEndpointInfos(SERVER_NAME)).addAllSupportedMethods(UserRpcConfig.SUPPORTED_SERVER_METHODS);
try {
if (inbound.getRpcVersion() != UserRpcConfig.RPC_VERSION) {
final String errMsg = String.format("Invalid rpc version. Expected %d, actual %d.", UserRpcConfig.RPC_VERSION, inbound.getRpcVersion());
return handleFailure(respBuilder, HandshakeStatus.RPC_VERSION_MISMATCH, errMsg, null);
}
connection.setHandshake(inbound);
if (!config.isAuthEnabled()) {
connection.finalizeSession(inbound.getCredentials().getUserName());
respBuilder.setStatus(HandshakeStatus.SUCCESS);
return respBuilder.build();
}
// If sasl_support field is absent in handshake message then treat the client as < 1.10 client
final boolean clientSupportsSasl = inbound.hasSaslSupport();
// saslSupportOrdinal will be set to UNKNOWN_SASL_SUPPORT, if sasl_support field in handshake is set to a
// value which is unknown to this server. We will treat those clients as one which knows SASL protocol.
final int saslSupportOrdinal = (clientSupportsSasl) ? inbound.getSaslSupport().ordinal() : SaslSupport.UNKNOWN_SASL_SUPPORT.ordinal();
// Check if client doesn't support SASL or only supports SASL_AUTH and server has encryption enabled
if ((!clientSupportsSasl || saslSupportOrdinal == SaslSupport.SASL_AUTH.ordinal()) && config.isEncryptionEnabled()) {
throw new UserAuthenticationException("The server doesn't allow client without encryption support." + " Please upgrade your client or talk to your system administrator.");
}
if (!clientSupportsSasl) {
// for backward compatibility < 1.10
final String userName = inbound.getCredentials().getUserName();
if (logger.isTraceEnabled()) {
logger.trace("User {} on connection {} is likely using an older client.", userName, connection.getRemoteAddress());
}
try {
String password = "";
final UserProperties props = inbound.getProperties();
for (int i = 0; i < props.getPropertiesCount(); i++) {
Property prop = props.getProperties(i);
if (DrillProperties.PASSWORD.equalsIgnoreCase(prop.getKey())) {
password = prop.getValue();
break;
}
}
final PlainFactory plainFactory;
try {
plainFactory = (PlainFactory) config.getAuthProvider().getAuthenticatorFactory(PlainFactory.SIMPLE_NAME);
} catch (final SaslException e) {
throw new UserAuthenticationException("The server no longer supports username/password" + " based authentication. Please talk to your system administrator.");
}
plainFactory.getAuthenticator().authenticate(userName, password);
connection.changeHandlerTo(config.getMessageHandler());
connection.finalizeSession(userName);
respBuilder.setStatus(HandshakeStatus.SUCCESS);
logger.info("Authenticated {} from {} successfully using PLAIN", userName, connection.getRemoteAddress());
return respBuilder.build();
} catch (UserAuthenticationException ex) {
return handleFailure(respBuilder, HandshakeStatus.AUTH_FAILED, ex.getMessage(), ex);
}
}
// Offer all the configured mechanisms to client. If certain mechanism doesn't support encryption
// like PLAIN, those should fail during the SASL handshake negotiation.
respBuilder.addAllAuthenticationMechanisms(config.getAuthProvider().getAllFactoryNames());
// set the encrypted flag in handshake message. For older clients this field is optional so will be ignored
respBuilder.setEncrypted(connection.isEncryptionEnabled());
respBuilder.setMaxWrappedSize(connection.getMaxWrappedSize());
// for now, this means PLAIN credentials will be sent over twice
// (during handshake and during sasl exchange)
respBuilder.setStatus(HandshakeStatus.AUTH_REQUIRED);
return respBuilder.build();
} catch (Exception e) {
return handleFailure(respBuilder, HandshakeStatus.UNKNOWN_FAILURE, e.getMessage(), e);
}
}
};
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project component-runtime by Talend.
the class ServingProxyHandler method channelRead0.
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
if (!request.decoderResult().isSuccess()) {
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
api.getExecutor().execute(() -> {
final Map<String, String> headers = StreamSupport.stream(Spliterators.spliteratorUnknownSize(request.headers().iteratorAsString(), Spliterator.IMMUTABLE), false).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
final Attribute<String> baseAttr = ctx.channel().attr(Handlers.BASE);
Optional<Response> matching = api.getResponseLocator().findMatching(new RequestImpl((baseAttr == null || baseAttr.get() == null ? "" : baseAttr.get()) + request.uri(), request.method().name(), headers), api.getHeaderFilter());
if (!matching.isPresent()) {
if (HttpMethod.CONNECT.name().equalsIgnoreCase(request.method().name())) {
final Map<String, String> responseHeaders = new HashMap<>();
responseHeaders.put(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.KEEP_ALIVE.toString());
responseHeaders.put(HttpHeaderNames.CONTENT_LENGTH.toString(), "0");
matching = of(new ResponseImpl(responseHeaders, HttpResponseStatus.OK.code(), Unpooled.EMPTY_BUFFER.array()));
if (api.getSslContext() != null) {
final SSLEngine sslEngine = api.getSslContext().createSSLEngine();
sslEngine.setUseClientMode(false);
ctx.channel().pipeline().addFirst("ssl", new SslHandler(sslEngine, true));
final String uri = request.uri();
final String[] parts = uri.split(":");
ctx.channel().attr(Handlers.BASE).set("https://" + parts[0] + (parts.length > 1 && !"443".equals(parts[1]) ? ":" + parts[1] : ""));
}
} else {
sendError(ctx, new HttpResponseStatus(HttpURLConnection.HTTP_BAD_REQUEST, "You are in proxy mode. No response was found for the simulated request. Please ensure to capture it for next executions. " + request.method().name() + " " + request.uri()));
return;
}
}
final Response resp = matching.get();
final ByteBuf bytes = ofNullable(resp.payload()).map(Unpooled::copiedBuffer).orElse(Unpooled.EMPTY_BUFFER);
final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(resp.status()), bytes);
HttpUtil.setContentLength(response, bytes.array().length);
if (!api.isSkipProxyHeaders()) {
response.headers().set("X-Talend-Proxy-JUnit", "true");
}
ofNullable(resp.headers()).ifPresent(h -> h.forEach((k, v) -> response.headers().set(k, v)));
ctx.writeAndFlush(response);
});
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project redisson by redisson.
the class RedisChannelInitializer method initSsl.
private void initSsl(final RedisClientConfig config, Channel ch) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, SSLException, UnrecoverableKeyException {
if (!config.getAddress().isSsl()) {
return;
}
io.netty.handler.ssl.SslProvider provided = io.netty.handler.ssl.SslProvider.JDK;
if (config.getSslProvider() == SslProvider.OPENSSL) {
provided = io.netty.handler.ssl.SslProvider.OPENSSL;
}
SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(provided);
sslContextBuilder.protocols(config.getSslProtocols());
if (config.getSslTruststore() != null) {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream stream = config.getSslTruststore().openStream();
try {
char[] password = null;
if (config.getSslTruststorePassword() != null) {
password = config.getSslTruststorePassword().toCharArray();
}
keyStore.load(stream, password);
} finally {
stream.close();
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sslContextBuilder.trustManager(trustManagerFactory);
}
if (config.getSslKeystore() != null) {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream stream = config.getSslKeystore().openStream();
char[] password = null;
if (config.getSslKeystorePassword() != null) {
password = config.getSslKeystorePassword().toCharArray();
}
try {
keyStore.load(stream, password);
} finally {
stream.close();
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
sslContextBuilder.keyManager(keyManagerFactory);
}
SSLParameters sslParams = new SSLParameters();
if (config.isSslEnableEndpointIdentification()) {
sslParams.setEndpointIdentificationAlgorithm("HTTPS");
} else {
if (config.getSslTruststore() == null) {
sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
}
}
SslContext sslContext = sslContextBuilder.build();
String hostname = config.getSslHostname();
if (hostname == null || NetUtil.createByteArrayFromIpAddressString(hostname) != null) {
hostname = config.getAddress().getHost();
}
SSLEngine sslEngine = sslContext.newEngine(ch.alloc(), hostname, config.getAddress().getPort());
sslEngine.setSSLParameters(sslParams);
SslHandler sslHandler = new SslHandler(sslEngine);
ch.pipeline().addLast(sslHandler);
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
volatile boolean sslInitDone;
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
if (sslInitDone) {
super.channelActive(ctx);
}
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (!sslInitDone && (evt instanceof SslHandshakeCompletionEvent)) {
SslHandshakeCompletionEvent e = (SslHandshakeCompletionEvent) evt;
if (e.isSuccess()) {
sslInitDone = true;
ctx.fireChannelActive();
} else {
RedisConnection connection = RedisConnection.getFrom(ctx.channel());
connection.closeAsync();
connection.getConnectionPromise().completeExceptionally(e.cause());
}
}
super.userEventTriggered(ctx, evt);
}
});
}
use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project motan by weibocom.
the class NettyHttpRequestHandlerTest method testChannelRead0.
@Test
public void testChannelRead0() throws Exception {
final MessageHandler messageHandler = mockery.mock(MessageHandler.class);
final ChannelHandlerContext ctx = mockery.mock(ChannelHandlerContext.class);
final FullHttpResponse response = mockery.mock(FullHttpResponse.class);
mockery.checking(new Expectations() {
{
allowing(ctx).write(with(any(FullHttpResponse.class)));
will(new CustomAction("verify") {
@Override
public Object invoke(Invocation invocation) throws Throwable {
FullHttpResponse actualResponse = (FullHttpResponse) invocation.getParameter(0);
assertNotNull(actualResponse);
assertEquals(response, actualResponse);
return null;
}
});
allowing(ctx).flush();
will(returnValue(null));
allowing(ctx).close();
will(returnValue(null));
atLeast(1).of(messageHandler).handle(with(any(Channel.class)), with(any(Object.class)));
will(returnValue(response));
allowing(response).headers();
will(returnValue(new DefaultHttpHeaders()));
}
});
FullHttpRequest httpRequest = buildHttpRequest("anyPath");
NettyHttpRequestHandler handler = new NettyHttpRequestHandler(null, messageHandler);
handler.channelRead0(ctx, httpRequest);
}
Aggregations