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.buffer.Unpooled;
14 import io.netty.channel.ChannelHandlerContext;
15 import io.netty.channel.ChannelOutboundHandlerAdapter;
16 import io.netty.channel.ChannelPromise;
17 import java.io.IOException;
18 import java.net.SocketAddress;
19 import org.apache.sshd.ClientChannel;
20 import org.apache.sshd.ClientSession;
21 import org.apache.sshd.SshClient;
22 import org.apache.sshd.client.future.AuthFuture;
23 import org.apache.sshd.client.future.ConnectFuture;
24 import org.apache.sshd.client.future.OpenFuture;
25 import org.apache.sshd.common.future.CloseFuture;
26 import org.apache.sshd.common.future.SshFutureListener;
27 import org.apache.sshd.common.io.IoInputStream;
28 import org.apache.sshd.common.io.IoReadFuture;
29 import org.apache.sshd.common.util.Buffer;
30 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
35 * Netty SSH handler class. Acts as interface between Netty and SSH library.
37 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
39 private static final Logger logger = LoggerFactory.getLogger(AsyncSshHandler.class);
40 public static final String SUBSYSTEM = "netconf";
42 public static final SshClient DEFAULT_CLIENT = SshClient.setUpDefaultClient();
44 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
47 // TODO make configurable, or somehow reuse netty threadpool
48 DEFAULT_CLIENT.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
49 DEFAULT_CLIENT.start();
52 private final AuthenticationHandler authenticationHandler;
53 private final SshClient sshClient;
55 private SshReadAsyncListener sshReadAsyncListener;
56 private ClientChannel channel;
57 private ClientSession session;
58 private ChannelPromise connectPromise;
60 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
61 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
66 * @param authenticationHandler
67 * @param sshClient started SshClient
70 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
71 this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
72 this.sshClient = Preconditions.checkNotNull(sshClient);
77 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
78 logger.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
80 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
81 sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
83 public void operationComplete(final ConnectFuture future) {
84 if (future.isConnected()) {
85 handleSshSessionCreated(future, ctx);
87 handleSshSetupFailure(ctx, future.getException());
93 private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
95 logger.trace("SSH session created on channel: {}", ctx.channel());
97 session = future.getSession();
98 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
99 authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
101 public void operationComplete(final AuthFuture future) {
102 if (future.isSuccess()) {
103 handleSshAuthenticated(session, ctx);
105 handleSshSetupFailure(ctx, future.getException());
109 } catch (final IOException e) {
110 handleSshSetupFailure(ctx, e);
114 private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
116 logger.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
118 channel = session.createSubsystemChannel(SUBSYSTEM);
119 channel.setStreaming(ClientChannel.Streaming.Async);
120 channel.open().addListener(new SshFutureListener<OpenFuture>() {
122 public void operationComplete(final OpenFuture future) {
123 if(future.isOpened()) {
124 handleSshChanelOpened(ctx);
126 handleSshSetupFailure(ctx, future.getException());
132 } catch (final IOException e) {
133 handleSshSetupFailure(ctx, e);
137 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
138 logger.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
140 connectPromise.setSuccess();
141 connectPromise = null;
142 ctx.fireChannelActive();
144 final IoInputStream asyncOut = channel.getAsyncOut();
145 sshReadAsyncListener = new SshReadAsyncListener(ctx, asyncOut);
148 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
149 logger.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
150 connectPromise.setFailure(e);
151 connectPromise = null;
152 throw new IllegalStateException("Unable to setup SSH connection on channel: " + ctx.channel(), e);
156 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
158 if(channel.getAsyncIn().isClosed() || channel.getAsyncIn().isClosing()) {
159 handleSshSessionClosed(ctx);
161 channel.getAsyncIn().write(toBuffer(msg));
162 ((ByteBuf) msg).release();
164 } catch (final Exception e) {
165 logger.warn("Exception while writing to SSH remote on channel {}", ctx.channel(), e);
166 throw new IllegalStateException("Exception while writing to SSH remote on channel " + ctx.channel(),e);
170 private static void handleSshSessionClosed(final ChannelHandlerContext ctx) {
171 logger.debug("SSH session closed on channel: {}", ctx.channel());
172 ctx.fireChannelInactive();
175 private Buffer toBuffer(final Object msg) {
176 // TODO Buffer vs ByteBuf translate, Can we handle that better ?
177 Preconditions.checkState(msg instanceof ByteBuf);
178 final ByteBuf byteBuf = (ByteBuf) msg;
179 final byte[] temp = new byte[byteBuf.readableBytes()];
180 byteBuf.readBytes(temp, 0, byteBuf.readableBytes());
181 return new Buffer(temp);
185 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
186 this.connectPromise = promise;
187 startSsh(ctx, remoteAddress);
191 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
192 disconnect(ctx, promise);
196 public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
197 if(sshReadAsyncListener != null) {
198 sshReadAsyncListener.close();
201 session.close(false).addListener(new SshFutureListener<CloseFuture>() {
203 public void operationComplete(final CloseFuture future) {
204 if(future.isClosed() == false) {
215 * Listener over async input stream from SSH session.
216 * This listeners schedules reads in a loop until the session is closed or read fails.
218 private static class SshReadAsyncListener implements SshFutureListener<IoReadFuture>, AutoCloseable {
219 private static final int BUFFER_SIZE = 8192;
221 private final ChannelHandlerContext ctx;
223 private IoInputStream asyncOut;
225 private IoReadFuture currentReadFuture;
227 public SshReadAsyncListener(final ChannelHandlerContext ctx, final IoInputStream asyncOut) {
229 this.asyncOut = asyncOut;
230 buf = new Buffer(BUFFER_SIZE);
231 asyncOut.read(buf).addListener(this);
235 public synchronized void operationComplete(final IoReadFuture future) {
236 if(future.getException() != null) {
238 if(asyncOut.isClosed() || asyncOut.isClosing()) {
240 handleSshSessionClosed(ctx);
242 logger.warn("Exception while reading from SSH remote on channel {}", ctx.channel(), future.getException());
243 throw new IllegalStateException("Exception while reading from SSH remote on channel " + ctx.channel(), future.getException());
247 if (future.getRead() > 0) {
248 ctx.fireChannelRead(Unpooled.wrappedBuffer(buf.array(), 0, future.getRead()));
250 // Schedule next read
251 buf = new Buffer(BUFFER_SIZE);
252 currentReadFuture = asyncOut.read(buf);
253 currentReadFuture.addListener(this);
258 public synchronized void close() throws Exception {
259 // Remove self as listener on close to prevent reading from closed input
260 if(currentReadFuture != null) {
261 currentReadFuture.removeListener(this);