Add method to register listener for unknown msg
[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 import io.netty.util.concurrent.Future;
16 import io.netty.util.concurrent.GenericFutureListener;
17 import java.net.InetAddress;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.concurrent.TimeUnit;
21 import javax.net.ssl.SSLEngine;
22 import org.opendaylight.openflowjava.protocol.impl.core.connection.ConnectionAdapterFactory;
23 import org.opendaylight.openflowjava.protocol.impl.core.connection.ConnectionAdapterFactoryImpl;
24 import org.opendaylight.openflowjava.protocol.impl.core.connection.ConnectionFacade;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
27
28 /**
29  * Initializes TCP / TLS channel.
30  * @author michal.polkorab
31  */
32 public class TcpChannelInitializer extends ProtocolChannelInitializer<SocketChannel> {
33
34     private static final Logger LOG = LoggerFactory.getLogger(TcpChannelInitializer.class);
35     private final DefaultChannelGroup allChannels;
36     private final ConnectionAdapterFactory connectionAdapterFactory;
37
38     /**
39      * Default constructor.
40      */
41     public TcpChannelInitializer() {
42         this( new DefaultChannelGroup("netty-receiver", null), new ConnectionAdapterFactoryImpl() );
43     }
44
45     /**
46      * Testing constructor.
47      */
48     protected TcpChannelInitializer( final DefaultChannelGroup channelGroup, final ConnectionAdapterFactory connAdaptorFactory ) {
49         allChannels = channelGroup ;
50         connectionAdapterFactory = connAdaptorFactory ;
51     }
52
53     @Override
54     protected void initChannel(final SocketChannel ch) {
55         if (ch.remoteAddress() != null) {
56             final InetAddress switchAddress = ch.remoteAddress().getAddress();
57             final int port = ch.localAddress().getPort();
58             final int remotePort = ch.remoteAddress().getPort();
59             LOG.debug("Incoming connection from (remote address): {}:{} --> :{}",
60                             switchAddress.toString(), remotePort, port);
61
62             if (!getSwitchConnectionHandler().accept(switchAddress)) {
63                 ch.disconnect();
64                 LOG.debug("Incoming connection rejected");
65                 return;
66             }
67         }
68         LOG.debug("Incoming connection accepted - building pipeline");
69         allChannels.add(ch);
70         ConnectionFacade connectionFacade = null;
71         connectionFacade = connectionAdapterFactory.createConnectionFacade(ch, null, useBarrier());
72         try {
73             LOG.debug("Calling OF plugin: {}", getSwitchConnectionHandler());
74             getSwitchConnectionHandler().onSwitchConnected(connectionFacade);
75             connectionFacade.checkListeners();
76             ch.pipeline().addLast(PipelineHandlers.IDLE_HANDLER.name(),
77                     new IdleHandler(getSwitchIdleTimeout(), TimeUnit.MILLISECONDS));
78             boolean tlsPresent = false;
79
80             // If this channel is configured to support SSL it will only support SSL
81             if (getTlsConfiguration() != null) {
82                 tlsPresent = true;
83                 final SslContextFactory sslFactory = new SslContextFactory(getTlsConfiguration());
84                 final SSLEngine engine = sslFactory.getServerContext().createSSLEngine();
85                 engine.setNeedClientAuth(true);
86                 engine.setUseClientMode(false);
87                 List<String> suitesList = getTlsConfiguration().getCipherSuites();
88                 if (suitesList != null && !suitesList.isEmpty()) {
89                     LOG.debug("Requested Cipher Suites are: {}", suitesList);
90                     String[] suites = suitesList.toArray(new String[suitesList.size()]);
91                     engine.setEnabledCipherSuites(suites);
92                     LOG.debug("Cipher suites enabled in SSLEngine are: {}", engine.getEnabledCipherSuites().toString());
93                 }
94                 final SslHandler ssl = new SslHandler(engine);
95                 final Future<Channel> handshakeFuture = ssl.handshakeFuture();
96                 final ConnectionFacade finalConnectionFacade = connectionFacade;
97                 handshakeFuture.addListener(new GenericFutureListener<Future<? super Channel>>() {
98                     @Override
99                     public void operationComplete(final Future<? super Channel> future) throws Exception {
100                         finalConnectionFacade.fireConnectionReadyNotification();
101                     }
102                 });
103                 ch.pipeline().addLast(PipelineHandlers.SSL_HANDLER.name(), ssl);
104             }
105             ch.pipeline().addLast(PipelineHandlers.OF_FRAME_DECODER.name(),
106                     new OFFrameDecoder(connectionFacade, tlsPresent));
107             ch.pipeline().addLast(PipelineHandlers.OF_VERSION_DETECTOR.name(), new OFVersionDetector());
108             final OFDecoder ofDecoder = new OFDecoder();
109             ofDecoder.setDeserializationFactory(getDeserializationFactory());
110             ch.pipeline().addLast(PipelineHandlers.OF_DECODER.name(), ofDecoder);
111             final OFEncoder ofEncoder = new OFEncoder();
112             ofEncoder.setSerializationFactory(getSerializationFactory());
113             ch.pipeline().addLast(PipelineHandlers.OF_ENCODER.name(), ofEncoder);
114             ch.pipeline().addLast(PipelineHandlers.DELEGATING_INBOUND_HANDLER.name(),
115                     new DelegatingInboundHandler(connectionFacade));
116             if (!tlsPresent) {
117                 connectionFacade.fireConnectionReadyNotification();
118             }
119         } catch (final Exception e) {
120             LOG.warn("Failed to initialize channel", e);
121             ch.close();
122         }
123     }
124
125     /**
126      * @return iterator through active connections
127      */
128     public Iterator<Channel> getConnectionIterator() {
129         return allChannels.iterator();
130     }
131
132     /**
133      * @return amount of active channels
134      */
135     public int size() {
136         return allChannels.size();
137     }
138 }