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.channel.ChannelHandlerContext;
13 import io.netty.channel.ChannelOutboundHandlerAdapter;
14 import io.netty.channel.ChannelPromise;
15 import java.io.IOException;
16 import java.net.SocketAddress;
17 import org.apache.sshd.ClientChannel;
18 import org.apache.sshd.ClientSession;
19 import org.apache.sshd.SshClient;
20 import org.apache.sshd.client.future.AuthFuture;
21 import org.apache.sshd.client.future.ConnectFuture;
22 import org.apache.sshd.client.future.OpenFuture;
23 import org.apache.sshd.common.future.CloseFuture;
24 import org.apache.sshd.common.future.SshFutureListener;
25 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
30 * Netty SSH handler class. Acts as interface between Netty and SSH library.
32 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
34 private static final Logger logger = LoggerFactory.getLogger(AsyncSshHandler.class);
35 public static final String SUBSYSTEM = "netconf";
37 public static final SshClient DEFAULT_CLIENT = SshClient.setUpDefaultClient();
39 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
42 // TODO make configurable, or somehow reuse netty threadpool
43 DEFAULT_CLIENT.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
44 DEFAULT_CLIENT.start();
47 private final AuthenticationHandler authenticationHandler;
48 private final SshClient sshClient;
50 private AsyncSshHanderReader sshReadAsyncListener;
51 private AsyncSshHandlerWriter sshWriteAsyncHandler;
53 private ClientChannel channel;
54 private ClientSession session;
55 private ChannelPromise connectPromise;
58 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
59 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
64 * @param authenticationHandler
65 * @param sshClient started SshClient
68 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
69 this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
70 this.sshClient = Preconditions.checkNotNull(sshClient);
75 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
76 logger.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
78 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
79 sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
81 public void operationComplete(final ConnectFuture future) {
82 if (future.isConnected()) {
83 handleSshSessionCreated(future, ctx);
85 handleSshSetupFailure(ctx, future.getException());
91 private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
93 logger.trace("SSH session created on channel: {}", ctx.channel());
95 session = future.getSession();
96 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
97 authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
99 public void operationComplete(final AuthFuture future) {
100 if (future.isSuccess()) {
101 handleSshAuthenticated(session, ctx);
103 handleSshSetupFailure(ctx, future.getException());
107 } catch (final IOException e) {
108 handleSshSetupFailure(ctx, e);
112 private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
114 logger.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
116 channel = session.createSubsystemChannel(SUBSYSTEM);
117 channel.setStreaming(ClientChannel.Streaming.Async);
118 channel.open().addListener(new SshFutureListener<OpenFuture>() {
120 public void operationComplete(final OpenFuture future) {
121 if(future.isOpened()) {
122 handleSshChanelOpened(ctx);
124 handleSshSetupFailure(ctx, future.getException());
130 } catch (final IOException e) {
131 handleSshSetupFailure(ctx, e);
135 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
136 logger.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
138 connectPromise.setSuccess();
139 connectPromise = null;
141 sshReadAsyncListener = new AsyncSshHanderReader(this, ctx, channel.getAsyncOut());
142 // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null
143 if(channel != null) {
144 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
145 ctx.fireChannelActive();
149 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
150 logger.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
151 connectPromise.setFailure(e);
152 connectPromise = null;
153 throw new IllegalStateException("Unable to setup SSH connection on channel: " + ctx.channel(), e);
157 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
158 sshWriteAsyncHandler.write(ctx, msg, promise);
162 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
163 this.connectPromise = promise;
164 startSsh(ctx, remoteAddress);
168 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
169 disconnect(ctx, promise);
173 public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
174 if(sshReadAsyncListener != null) {
175 sshReadAsyncListener.close();
178 if(sshWriteAsyncHandler != null) {
179 sshWriteAsyncHandler.close();
182 if(session!= null && !session.isClosed() && !session.isClosing()) {
183 session.close(false).addListener(new SshFutureListener<CloseFuture>() {
185 public void operationComplete(final CloseFuture future) {
186 if (future.isClosed() == false) {
195 promise.setSuccess();
197 logger.debug("SSH session closed on channel: {}", ctx.channel());
198 ctx.fireChannelInactive();