001/*
002Copyright 2015 Hendrik Saly
003
004Licensed under the Apache License, Version 2.0 (the "License");
005you may not use this file except in compliance with the License.
006You may obtain a copy of the License at
007
008    http://www.apache.org/licenses/LICENSE-2.0
009
010Unless required by applicable law or agreed to in writing, software
011distributed under the License is distributed on an "AS IS" BASIS,
012WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013See the License for the specific language governing permissions and
014limitations under the License.
015 */
016
017package de.saly.es.example.tssl.netty;
018
019import org.elasticsearch.common.logging.ESLogger;
020import org.elasticsearch.common.netty.channel.ChannelFuture;
021import org.elasticsearch.common.netty.channel.ChannelFutureListener;
022import org.elasticsearch.common.netty.channel.ChannelHandlerContext;
023import org.elasticsearch.common.netty.channel.ChannelStateEvent;
024import org.elasticsearch.common.netty.handler.ssl.SslHandler;
025import org.elasticsearch.transport.netty.MessageChannelHandler;
026import org.elasticsearch.transport.netty.NettyTransport;
027
028public class SecureMessageChannelHandler extends MessageChannelHandler {
029
030    public SecureMessageChannelHandler(final NettyTransport transport, final ESLogger logger) {
031        super(transport, logger, "default");
032    }
033
034    @Override
035    public void channelConnected(final ChannelHandlerContext ctx, final ChannelStateEvent e) {
036        //prevent javax.net.ssl.SSLException: Received close_notify during handshake
037        final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class);
038        final ChannelFuture handshakeFuture = sslHandler.handshake();
039        handshakeFuture.addListener(new ChannelFutureListener() {
040
041            @Override
042            public void operationComplete(final ChannelFuture future) throws Exception {
043                if (logger.isTraceEnabled()) {
044                    logger.trace("Node to Node encryption cipher is {}/{}", sslHandler.getEngine().getSession().getProtocol(), sslHandler
045                            .getEngine().getSession().getCipherSuite());
046                }
047                ctx.sendUpstream(e);
048            }
049        });
050    }
051
052}