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.FutureListener;
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.channel.ClientChannel;
25 import org.opendaylight.netconf.shaded.sshd.client.future.AuthFuture;
26 import org.opendaylight.netconf.shaded.sshd.client.future.ConnectFuture;
27 import org.opendaylight.netconf.shaded.sshd.client.future.OpenFuture;
28 import org.opendaylight.netconf.shaded.sshd.client.session.ClientSession;
29 import org.opendaylight.netconf.shaded.sshd.core.CoreModuleProperties;
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 {
37 private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
39 public static final String SUBSYSTEM = "netconf";
41 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
43 public static final NetconfSshClient DEFAULT_CLIENT;
46 final NetconfSshClient c = new NetconfClientBuilder().build();
47 // Disable default timeouts from mina sshd
48 c.getProperties().put(CoreModuleProperties.AUTH_TIMEOUT.getName(), "0");
49 c.getProperties().put(CoreModuleProperties.IDLE_TIMEOUT.getName(), "0");
50 c.getProperties().put(CoreModuleProperties.NIO2_READ_TIMEOUT.getName(), "0");
51 c.getProperties().put(CoreModuleProperties.TCP_NODELAY.getName(), true);
53 // TODO make configurable, or somehow reuse netty threadpool
54 c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
59 private final AtomicBoolean isDisconnected = new AtomicBoolean();
60 private final AuthenticationHandler authenticationHandler;
61 private final Future<?> negotiationFuture;
62 private final NetconfSshClient sshClient;
64 private AsyncSshHandlerWriter sshWriteAsyncHandler;
66 private NettyAwareChannelSubsystem channel;
67 private ClientSession session;
68 private ChannelPromise connectPromise;
69 private FutureListener<Object> negotiationFutureListener;
71 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient,
72 final Future<?> negotiationFuture) {
73 this.authenticationHandler = requireNonNull(authenticationHandler);
74 this.sshClient = requireNonNull(sshClient);
75 this.negotiationFuture = negotiationFuture;
79 * Constructor of {@code AsyncSshHandler}.
81 * @param authenticationHandler authentication handler
82 * @param sshClient started SshClient
84 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient) {
85 this(authenticationHandler, sshClient, null);
88 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
89 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
93 * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
94 * netconf negotiation.
96 * @param authenticationHandler authentication handler
97 * @param negotiationFuture negotiation future
98 * @return {@code AsyncSshHandler}
100 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
101 final Future<?> negotiationFuture, final @Nullable NetconfSshClient sshClient) {
102 return new AsyncSshHandler(authenticationHandler, sshClient != null ? sshClient : DEFAULT_CLIENT,
107 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
108 sshWriteAsyncHandler.write(ctx, msg, promise);
112 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
113 final SocketAddress localAddress, final ChannelPromise promise) throws IOException {
114 LOG.debug("SSH session connecting on channel {}. promise: {}", ctx.channel(), promise);
115 connectPromise = requireNonNull(promise);
117 if (negotiationFuture != null) {
118 negotiationFutureListener = future -> {
119 if (future.isSuccess()) {
120 promise.setSuccess();
123 //complete connection promise with netconf negotiation future
124 negotiationFuture.addListener(negotiationFutureListener);
127 LOG.debug("Starting SSH to {} on channel: {}", remoteAddress, ctx.channel());
128 sshClient.connect(authenticationHandler.getUsername(), remoteAddress)
129 // FIXME: this is a blocking call, we should handle this with a concurrently-scheduled timeout. We do not
130 // have a Timer ready, so perhaps we should be using the event loop?
131 .verify(ctx.channel().config().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS)
132 .addListener(future -> onConnectComplete(future, ctx));
135 private void onConnectComplete(final ConnectFuture future, final ChannelHandlerContext ctx) {
136 final var cause = future.getException();
138 onOpenFailure(ctx, cause);
142 final var clientSession = future.getSession();
143 LOG.trace("SSH session {} created on channel: {}", clientSession, ctx.channel());
144 verify(clientSession instanceof NettyAwareClientSession, "Unexpected session %s", clientSession);
145 onConnectComplete((NettyAwareClientSession) clientSession, ctx);
148 private synchronized void onConnectComplete(final NettyAwareClientSession clientSession,
149 final ChannelHandlerContext ctx) {
150 session = clientSession;
152 final AuthFuture authFuture;
154 authFuture = authenticationHandler.authenticate(clientSession);
155 } catch (final IOException e) {
156 onOpenFailure(ctx, e);
160 authFuture.addListener(future -> onAuthComplete(future, clientSession, ctx));
163 private void onAuthComplete(final AuthFuture future, final NettyAwareClientSession clientSession,
164 final ChannelHandlerContext ctx) {
165 final var cause = future.getException();
167 onOpenFailure(ctx, new AuthenticationFailedException("Authentication failed", cause));
171 onAuthComplete(clientSession, ctx);
174 private synchronized void onAuthComplete(final NettyAwareClientSession clientSession,
175 final ChannelHandlerContext ctx) {
176 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
177 clientSession.getServerVersion());
179 final OpenFuture openFuture;
181 channel = clientSession.createSubsystemChannel(SUBSYSTEM, ctx);
182 channel.setStreaming(ClientChannel.Streaming.Async);
183 openFuture = channel.open();
184 } catch (final IOException e) {
185 onOpenFailure(ctx, e);
189 openFuture.addListener(future -> onOpenComplete(future, ctx));
192 private void onOpenComplete(final OpenFuture future, final ChannelHandlerContext ctx) {
193 final var cause = future.getException();
195 onOpenFailure(ctx, cause);
202 private synchronized void onOpenComplete(final ChannelHandlerContext ctx) {
203 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
205 if (negotiationFuture == null) {
206 connectPromise.setSuccess();
209 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
210 ctx.fireChannelActive();
211 channel.onClose(() -> disconnect(ctx, ctx.newPromise()));
214 private synchronized void onOpenFailure(final ChannelHandlerContext ctx, final Throwable cause) {
215 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), cause);
217 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
218 if (!connectPromise.isDone()) {
219 connectPromise.setFailure(cause);
222 disconnect(ctx, ctx.newPromise());
226 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
227 disconnect(ctx, promise);
231 public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
232 if (isDisconnected.compareAndSet(false, true)) {
233 safelyDisconnect(ctx, promise);
237 @SuppressWarnings("checkstyle:IllegalCatch")
238 private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
239 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
240 ctx.channel(), connectPromise);
242 // If we have already succeeded and the session was dropped after,
243 // 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 connection promise is not already set, it means negotiation failed
253 //we must set connection promise to failure
254 if (!connectPromise.isDone()) {
255 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
258 //Remove listener from negotiation future, we don't want notifications
259 //from negotiation anymore
260 if (negotiationFuture != null) {
261 negotiationFuture.removeListener(negotiationFutureListener);
264 if (session != null && !session.isClosed() && !session.isClosing()) {
265 session.close(false).addListener(future -> {
266 synchronized (this) {
267 if (!future.isClosed()) {
275 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
276 // to cleanup its resources e.g. Socket that it tries to open in its constructor
277 // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
278 // TODO better solution would be to implement custom ChannelFactory + Channel
279 // that will use mina SSH lib internally: port this to custom channel implementation
281 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
282 super.disconnect(ctx, ctx.newPromise());
283 } catch (final Exception e) {
284 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
287 if (channel != null) {
288 //TODO: see if calling just close() is sufficient
289 //channel.close(false);
293 promise.setSuccess();
294 LOG.debug("SSH session closed on channel: {}", ctx.channel());