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
8 package org.opendaylight.netconf.nettyutil.handler.ssh.client;
10 import static com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
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.concurrent.TimeUnit;
21 import java.util.concurrent.atomic.AtomicBoolean;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
24 import org.opendaylight.netconf.shaded.sshd.client.SshClient;
25 import org.opendaylight.netconf.shaded.sshd.client.channel.ClientChannel;
26 import org.opendaylight.netconf.shaded.sshd.client.future.AuthFuture;
27 import org.opendaylight.netconf.shaded.sshd.client.future.ConnectFuture;
28 import org.opendaylight.netconf.shaded.sshd.client.session.ClientSession;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
33 * Netty SSH handler class. Acts as interface between Netty and SSH library.
35 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
36 private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
38 public static final String SUBSYSTEM = "netconf";
40 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
41 // Disable default timeouts from mina sshd
42 private static final long DEFAULT_TIMEOUT = -1L;
44 public static final NetconfSshClient DEFAULT_CLIENT;
47 final NetconfSshClient c = new NetconfClientBuilder().build();
48 c.getProperties().put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
49 c.getProperties().put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
51 // TODO make configurable, or somehow reuse netty threadpool
52 c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
57 private final AtomicBoolean isDisconnected = new AtomicBoolean();
58 private final AuthenticationHandler authenticationHandler;
59 private final Future<?> negotiationFuture;
60 private final NetconfSshClient sshClient;
62 private AsyncSshHandlerWriter sshWriteAsyncHandler;
64 private NettyAwareChannelSubsystem channel;
65 private ClientSession session;
66 private ChannelPromise connectPromise;
67 private GenericFutureListener negotiationFutureListener;
69 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient,
70 final Future<?> negotiationFuture) {
71 this.authenticationHandler = requireNonNull(authenticationHandler);
72 this.sshClient = requireNonNull(sshClient);
73 this.negotiationFuture = negotiationFuture;
77 * Constructor of {@code AsyncSshHandler}.
79 * @param authenticationHandler authentication handler
80 * @param sshClient started SshClient
82 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient) {
83 this(authenticationHandler, sshClient, null);
86 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
87 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
91 * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
92 * netconf negotiation.
94 * @param authenticationHandler authentication handler
95 * @param negotiationFuture negotiation future
96 * @return {@code AsyncSshHandler}
98 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
99 final Future<?> negotiationFuture, final @Nullable NetconfSshClient sshClient) {
100 return new AsyncSshHandler(authenticationHandler, sshClient != null ? sshClient : DEFAULT_CLIENT,
104 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) throws IOException {
105 LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
107 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address)
108 .verify(ctx.channel().config().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
109 sshConnectionFuture.addListener(future -> {
110 if (future.isConnected()) {
111 handleSshSessionCreated(future, ctx);
113 handleSshSetupFailure(ctx, future.getException());
118 private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
120 LOG.trace("SSH session created on channel: {}", ctx.channel());
122 session = future.getSession();
123 verify(session instanceof NettyAwareClientSession, "Unexpected session %s", session);
125 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
126 final NettyAwareClientSession localSession = (NettyAwareClientSession) session;
127 authenticateFuture.addListener(future1 -> {
128 if (future1.isSuccess()) {
129 handleSshAuthenticated(localSession, ctx);
131 handleSshSetupFailure(ctx, new AuthenticationFailedException("Authentication failed",
132 future1.getException()));
135 } catch (final IOException e) {
136 handleSshSetupFailure(ctx, e);
140 private synchronized void handleSshAuthenticated(final NettyAwareClientSession newSession,
141 final ChannelHandlerContext ctx) {
143 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
144 newSession.getServerVersion());
146 channel = newSession.createSubsystemChannel(SUBSYSTEM, ctx);
147 channel.setStreaming(ClientChannel.Streaming.Async);
148 channel.open().addListener(future -> {
149 if (future.isOpened()) {
150 handleSshChanelOpened(ctx);
152 handleSshSetupFailure(ctx, future.getException());
157 } catch (final IOException e) {
158 handleSshSetupFailure(ctx, e);
162 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
163 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
165 if (negotiationFuture == null) {
166 connectPromise.setSuccess();
169 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
170 ctx.fireChannelActive();
171 channel.onClose(() -> disconnect(ctx, ctx.newPromise()));
174 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
175 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
177 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
178 if (!connectPromise.isDone()) {
179 connectPromise.setFailure(error);
182 disconnect(ctx, ctx.newPromise());
186 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
187 sshWriteAsyncHandler.write(ctx, msg, promise);
191 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
192 final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
193 LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
194 this.connectPromise = promise;
196 if (negotiationFuture != null) {
197 negotiationFutureListener = future -> {
198 if (future.isSuccess()) {
199 promise.setSuccess();
202 //complete connection promise with netconf negotiation future
203 negotiationFuture.addListener(negotiationFutureListener);
205 startSsh(ctx, remoteAddress);
209 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
210 disconnect(ctx, promise);
214 public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
215 if (isDisconnected.compareAndSet(false, true)) {
216 safelyDisconnect(ctx, promise);
220 @SuppressWarnings("checkstyle:IllegalCatch")
221 private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
222 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
223 ctx.channel(), connectPromise);
225 // If we have already succeeded and the session was dropped after,
226 // we need to fire inactive to notify reconnect logic
227 if (connectPromise.isSuccess()) {
228 ctx.fireChannelInactive();
231 if (sshWriteAsyncHandler != null) {
232 sshWriteAsyncHandler.close();
235 //If connection promise is not already set, it means negotiation failed
236 //we must set connection promise to failure
237 if (!connectPromise.isDone()) {
238 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
241 //Remove listener from negotiation future, we don't want notifications
242 //from negotiation anymore
243 if (negotiationFuture != null) {
244 negotiationFuture.removeListener(negotiationFutureListener);
247 if (session != null && !session.isClosed() && !session.isClosing()) {
248 session.close(false).addListener(future -> {
249 synchronized (this) {
250 if (!future.isClosed()) {
258 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
259 // to cleanup its resources e.g. Socket that it tries to open in its constructor
260 // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
261 // TODO better solution would be to implement custom ChannelFactory + Channel
262 // that will use mina SSH lib internally: port this to custom channel implementation
264 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
265 super.disconnect(ctx, ctx.newPromise());
266 } catch (final Exception e) {
267 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
270 if (channel != null) {
271 //TODO: see if calling just close() is sufficient
272 //channel.close(false);
276 promise.setSuccess();
277 LOG.debug("SSH session closed on channel: {}", ctx.channel());