2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.nettyutil.handler.ssh.client;
11 import com.google.common.base.Preconditions;
12 import io.netty.buffer.ByteBuf;
13 import io.netty.channel.ChannelHandlerContext;
14 import io.netty.channel.ChannelOutboundHandlerAdapter;
15 import io.netty.channel.ChannelPromise;
16 import java.io.IOException;
17 import java.net.SocketAddress;
18 import org.apache.sshd.ClientChannel;
19 import org.apache.sshd.ClientSession;
20 import org.apache.sshd.SshClient;
21 import org.apache.sshd.client.future.AuthFuture;
22 import org.apache.sshd.client.future.ConnectFuture;
23 import org.apache.sshd.client.future.OpenFuture;
24 import org.apache.sshd.common.future.CloseFuture;
25 import org.apache.sshd.common.future.SshFutureListener;
26 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
31 * Netty SSH handler class. Acts as interface between Netty and SSH library.
33 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
35 private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
36 public static final String SUBSYSTEM = "netconf";
38 public static final SshClient DEFAULT_CLIENT = SshClient.setUpDefaultClient();
40 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
43 // TODO make configurable, or somehow reuse netty threadpool
44 DEFAULT_CLIENT.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
45 DEFAULT_CLIENT.start();
48 private final AuthenticationHandler authenticationHandler;
49 private final SshClient sshClient;
51 private AsyncSshHandlerReader sshReadAsyncListener;
52 private AsyncSshHandlerWriter sshWriteAsyncHandler;
54 private ClientChannel channel;
55 private ClientSession session;
56 private ChannelPromise connectPromise;
59 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
60 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
65 * @param authenticationHandler
66 * @param sshClient started SshClient
69 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
70 this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
71 this.sshClient = Preconditions.checkNotNull(sshClient);
76 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
77 LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
79 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
80 sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
82 public void operationComplete(final ConnectFuture future) {
83 if (future.isConnected()) {
84 handleSshSessionCreated(future, ctx);
86 handleSshSetupFailure(ctx, future.getException());
92 private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
94 LOG.trace("SSH session created on channel: {}", ctx.channel());
96 session = future.getSession();
97 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
98 authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
100 public void operationComplete(final AuthFuture future) {
101 if (future.isSuccess()) {
102 handleSshAuthenticated(session, ctx);
104 // Exception does not have to be set in the future, add simple exception in such case
105 final Throwable exception = future.getException() == null ?
106 new IllegalStateException("Authentication failed") :
107 future.getException();
108 handleSshSetupFailure(ctx, exception);
112 } catch (final IOException e) {
113 handleSshSetupFailure(ctx, e);
117 private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
119 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
121 channel = session.createSubsystemChannel(SUBSYSTEM);
122 channel.setStreaming(ClientChannel.Streaming.Async);
123 channel.open().addListener(new SshFutureListener<OpenFuture>() {
125 public void operationComplete(final OpenFuture future) {
126 if(future.isOpened()) {
127 handleSshChanelOpened(ctx);
129 handleSshSetupFailure(ctx, future.getException());
135 } catch (final IOException e) {
136 handleSshSetupFailure(ctx, e);
140 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
141 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
143 connectPromise.setSuccess();
145 // TODO we should also read from error stream and at least log from that
147 sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() {
149 public void close() throws Exception {
150 AsyncSshHandler.this.disconnect(ctx, ctx.newPromise());
152 }, new AsyncSshHandlerReader.ReadMsgHandler() {
154 public void onMessageRead(final ByteBuf msg) {
155 ctx.fireChannelRead(msg);
157 }, channel.toString(), channel.getAsyncOut());
159 // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null
160 if(channel != null) {
161 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
162 ctx.fireChannelActive();
166 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
167 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
168 disconnect(ctx, ctx.newPromise());
170 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
171 if(!connectPromise.isDone()) {
172 connectPromise.setFailure(e);
177 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
178 sshWriteAsyncHandler.write(ctx, msg, promise);
182 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
183 LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
184 this.connectPromise = promise;
185 startSsh(ctx, remoteAddress);
189 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
190 disconnect(ctx, promise);
194 public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
195 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(), connectPromise);
197 // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
198 if(connectPromise.isSuccess()) {
199 ctx.fireChannelInactive();
202 if(sshWriteAsyncHandler != null) {
203 sshWriteAsyncHandler.close();
206 if(sshReadAsyncListener != null) {
207 sshReadAsyncListener.close();
210 if(session!= null && !session.isClosed() && !session.isClosing()) {
211 session.close(false).addListener(new SshFutureListener<CloseFuture>() {
213 public void operationComplete(final CloseFuture future) {
214 if (future.isClosed() == false) {
222 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
223 // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
224 // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
226 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
227 super.disconnect(ctx, ctx.newPromise());
228 } catch (final Exception e) {
229 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
233 promise.setSuccess();
234 LOG.debug("SSH session closed on channel: {}", ctx.channel());