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.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 io.netty.util.concurrent.Future;
17 import io.netty.util.concurrent.GenericFutureListener;
18 import java.io.IOException;
19 import java.net.SocketAddress;
20 import java.util.HashMap;
21 import org.apache.sshd.ClientChannel;
22 import org.apache.sshd.ClientSession;
23 import org.apache.sshd.SshClient;
24 import org.apache.sshd.client.future.AuthFuture;
25 import org.apache.sshd.client.future.ConnectFuture;
26 import org.apache.sshd.client.future.OpenFuture;
27 import org.apache.sshd.common.future.CloseFuture;
28 import org.apache.sshd.common.future.SshFutureListener;
29 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
34 * Netty SSH handler class. Acts as interface between Netty and SSH library.
36 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
38 public static final String SUBSYSTEM = "netconf";
39 public static final SshClient DEFAULT_CLIENT = SshClient.setUpDefaultClient();
40 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
41 private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
42 // Disable default timeouts from mina sshd
43 private static final long DEFAULT_TIMEOUT = -1L;
46 DEFAULT_CLIENT.setProperties(new HashMap<String, String>(){
48 put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
49 put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
52 // TODO make configurable, or somehow reuse netty threadpool
53 DEFAULT_CLIENT.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
54 DEFAULT_CLIENT.start();
57 private final AuthenticationHandler authenticationHandler;
58 private final SshClient sshClient;
59 private Future negotiationFuture;
61 private AsyncSshHandlerReader sshReadAsyncListener;
62 private AsyncSshHandlerWriter sshWriteAsyncHandler;
64 private ClientChannel channel;
65 private ClientSession session;
66 private ChannelPromise connectPromise;
67 private GenericFutureListener negotiationFutureListener;
70 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient, final Future negotiationFuture) throws IOException {
71 this(authenticationHandler, sshClient);
72 this.negotiationFuture = negotiationFuture;
77 * @param authenticationHandler
78 * @param sshClient started SshClient
81 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
82 this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
83 this.sshClient = Preconditions.checkNotNull(sshClient);
88 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
89 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
94 * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful netconf
97 * @param authenticationHandler
98 * @param negotiationFuture
100 * @throws IOException
102 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler, final Future negotiationFuture) throws IOException {
103 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture);
106 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
107 LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
109 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
110 sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
112 public void operationComplete(final ConnectFuture future) {
113 if (future.isConnected()) {
114 handleSshSessionCreated(future, ctx);
116 handleSshSetupFailure(ctx, future.getException());
122 private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
124 LOG.trace("SSH session created on channel: {}", ctx.channel());
126 session = future.getSession();
127 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
128 authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
130 public void operationComplete(final AuthFuture future) {
131 if (future.isSuccess()) {
132 handleSshAuthenticated(session, ctx);
134 // Exception does not have to be set in the future, add simple exception in such case
135 final Throwable exception = future.getException() == null ?
136 new IllegalStateException("Authentication failed") :
137 future.getException();
138 handleSshSetupFailure(ctx, exception);
142 } catch (final IOException e) {
143 handleSshSetupFailure(ctx, e);
147 private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
149 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
151 channel = session.createSubsystemChannel(SUBSYSTEM);
152 channel.setStreaming(ClientChannel.Streaming.Async);
153 channel.open().addListener(new SshFutureListener<OpenFuture>() {
155 public void operationComplete(final OpenFuture future) {
156 if(future.isOpened()) {
157 handleSshChanelOpened(ctx);
159 handleSshSetupFailure(ctx, future.getException());
165 } catch (final IOException e) {
166 handleSshSetupFailure(ctx, e);
170 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
171 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
173 if(negotiationFuture == null) {
174 connectPromise.setSuccess();
177 // TODO we should also read from error stream and at least log from that
179 sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() {
181 public void close() throws Exception {
182 AsyncSshHandler.this.disconnect(ctx, ctx.newPromise());
184 }, new AsyncSshHandlerReader.ReadMsgHandler() {
186 public void onMessageRead(final ByteBuf msg) {
187 ctx.fireChannelRead(msg);
189 }, channel.toString(), channel.getAsyncOut());
191 // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null
192 if(channel != null) {
193 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
194 ctx.fireChannelActive();
198 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
199 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
201 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
202 if(!connectPromise.isDone()) {
203 connectPromise.setFailure(e);
206 disconnect(ctx, ctx.newPromise());
210 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
211 sshWriteAsyncHandler.write(ctx, msg, promise);
215 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
216 LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
217 this.connectPromise = promise;
219 if(negotiationFuture != null) {
221 negotiationFutureListener = new GenericFutureListener<Future<Object>>() {
223 public void operationComplete(Future future) throws Exception {
224 if (future.isSuccess())
225 connectPromise.setSuccess();
228 //complete connection promise with netconf negotiation future
229 negotiationFuture.addListener(negotiationFutureListener);
231 startSsh(ctx, remoteAddress);
235 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
236 disconnect(ctx, promise);
240 public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
241 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(), connectPromise);
243 // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
244 if(connectPromise.isSuccess()) {
245 ctx.fireChannelInactive();
248 if(sshWriteAsyncHandler != null) {
249 sshWriteAsyncHandler.close();
252 if(sshReadAsyncListener != null) {
253 sshReadAsyncListener.close();
256 //If connection promise is not already set, it means negotiation failed
257 //we must set connection promise to failure
258 if(!connectPromise.isDone()) {
259 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
262 //Remove listener from negotiation future, we don't want notifications
263 //from negotiation anymore
264 if(negotiationFuture != null) {
265 negotiationFuture.removeListener(negotiationFutureListener);
268 if(session!= null && !session.isClosed() && !session.isClosing()) {
269 session.close(false).addListener(new SshFutureListener<CloseFuture>() {
271 public void operationComplete(final CloseFuture future) {
272 if (future.isClosed() == false) {
280 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
281 // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
282 // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
284 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
285 super.disconnect(ctx, ctx.newPromise());
286 } catch (final Exception e) {
287 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
291 promise.setSuccess();
292 LOG.debug("SSH session closed on channel: {}", ctx.channel());