Bug 2875 - fix initiating OFPT_HELLO over SSL from the controller
[openflowjava.git] / openflow-protocol-impl / src / main / java / org / opendaylight / openflowjava / protocol / impl / core / TcpChannelInitializer.java
1 /*
2  * Copyright (c) 2013 Pantheon Technologies s.r.o. and others. All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.openflowjava.protocol.impl.core;
10
11 import io.netty.channel.Channel;
12 import io.netty.channel.group.DefaultChannelGroup;
13 import io.netty.channel.socket.SocketChannel;
14 import io.netty.handler.ssl.SslHandler;
15
16 import java.net.InetAddress;
17 import java.util.Iterator;
18 import java.util.concurrent.TimeUnit;
19
20 import javax.net.ssl.SSLEngine;
21
22 import io.netty.util.concurrent.Future;
23 import io.netty.util.concurrent.GenericFutureListener;
24 import org.opendaylight.openflowjava.protocol.impl.core.connection.ConnectionAdapterFactory;
25 import org.opendaylight.openflowjava.protocol.impl.core.connection.ConnectionAdapterFactoryImpl;
26 import org.opendaylight.openflowjava.protocol.impl.core.connection.ConnectionFacade;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * Initializes TCP / TLS channel
32  * @author michal.polkorab
33  */
34 public class TcpChannelInitializer extends ProtocolChannelInitializer<SocketChannel> {
35
36     private static final Logger LOGGER = LoggerFactory
37             .getLogger(TcpChannelInitializer.class);
38     private final DefaultChannelGroup allChannels;
39     private ConnectionAdapterFactory connectionAdapterFactory;
40
41     /**
42      * default ctor
43      */
44     public TcpChannelInitializer() {
45         this( new DefaultChannelGroup("netty-receiver", null), new ConnectionAdapterFactoryImpl() );
46     }
47
48     /**
49      * Testing Constructor
50      *
51      */
52     protected TcpChannelInitializer( DefaultChannelGroup channelGroup, ConnectionAdapterFactory connAdaptorFactory ) {
53         allChannels = channelGroup ;
54         connectionAdapterFactory = connAdaptorFactory ;
55     }
56
57     @Override
58     protected void initChannel(final SocketChannel ch) {
59         if (ch.remoteAddress() != null) {
60             InetAddress switchAddress = ch.remoteAddress().getAddress();
61             int port = ch.localAddress().getPort();
62             int remotePort = ch.remoteAddress().getPort();
63             LOGGER.debug("Incoming connection from (remote address): {}:{} --> :{}",
64                             switchAddress.toString(), remotePort, port);
65
66             if (!getSwitchConnectionHandler().accept(switchAddress)) {
67                 ch.disconnect();
68                 LOGGER.debug("Incoming connection rejected");
69                 return;
70             }
71         }
72         LOGGER.debug("Incoming connection accepted - building pipeline");
73         allChannels.add(ch);
74         ConnectionFacade connectionFacade = null;
75         connectionFacade = connectionAdapterFactory.createConnectionFacade(ch, null);
76         try {
77             LOGGER.debug("calling plugin: {}", getSwitchConnectionHandler());
78             getSwitchConnectionHandler().onSwitchConnected(connectionFacade);
79             connectionFacade.checkListeners();
80             ch.pipeline().addLast(PipelineHandlers.IDLE_HANDLER.name(), new IdleHandler(getSwitchIdleTimeout(), TimeUnit.MILLISECONDS));
81             boolean tlsPresent = false;
82
83             // If this channel is configured to support SSL it will only support SSL
84             if (getTlsConfiguration() != null) {
85                 tlsPresent = true;
86                 SslContextFactory sslFactory = new SslContextFactory(getTlsConfiguration());
87                 SSLEngine engine = sslFactory.getServerContext().createSSLEngine();
88                 engine.setNeedClientAuth(true);
89                 engine.setUseClientMode(false);
90                 SslHandler ssl = new SslHandler(engine);
91                 Future<Channel> handshakeFuture = ssl.handshakeFuture();
92                 final ConnectionFacade finalConnectionFacade = connectionFacade;
93                 handshakeFuture.addListener(new GenericFutureListener<Future<? super Channel>>() {
94                     @Override
95                     public void operationComplete(Future<? super Channel> future) throws Exception {
96                         finalConnectionFacade.fireConnectionReadyNotification();
97                     }
98                 });
99                 ch.pipeline().addLast(PipelineHandlers.SSL_HANDLER.name(), ssl);
100             }
101             ch.pipeline().addLast(PipelineHandlers.OF_FRAME_DECODER.name(),
102                     new OFFrameDecoder(connectionFacade, tlsPresent));
103             ch.pipeline().addLast(PipelineHandlers.OF_VERSION_DETECTOR.name(), new OFVersionDetector());
104             OFDecoder ofDecoder = new OFDecoder();
105             ofDecoder.setDeserializationFactory(getDeserializationFactory());
106             ch.pipeline().addLast(PipelineHandlers.OF_DECODER.name(), ofDecoder);
107             OFEncoder ofEncoder = new OFEncoder();
108             ofEncoder.setSerializationFactory(getSerializationFactory());
109             ch.pipeline().addLast(PipelineHandlers.OF_ENCODER.name(), ofEncoder);
110             ch.pipeline().addLast(PipelineHandlers.DELEGATING_INBOUND_HANDLER.name(), new DelegatingInboundHandler(connectionFacade));
111             if (!tlsPresent) {
112                 connectionFacade.fireConnectionReadyNotification();
113             }
114         } catch (Exception e) {
115             LOGGER.warn("Failed to initialize channel", e);
116             ch.close();
117         }
118     }
119
120     /**
121      * @return iterator through active connections
122      */
123     public Iterator<Channel> getConnectionIterator() {
124         return allChannels.iterator();
125     }
126
127     /**
128      * @return amount of active channels
129      */
130     public int size() {
131         return allChannels.size();
132     }
133 }