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.lang.invoke.MethodHandles;
20 import java.lang.invoke.VarHandle;
21 import java.net.SocketAddress;
22 import java.time.Duration;
23 import java.util.concurrent.TimeUnit;
24 import org.checkerframework.checker.lock.qual.GuardedBy;
25 import org.checkerframework.checker.lock.qual.Holding;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
28 import org.opendaylight.netconf.shaded.sshd.client.channel.ChannelSubsystem;
29 import org.opendaylight.netconf.shaded.sshd.client.channel.ClientChannel;
30 import org.opendaylight.netconf.shaded.sshd.client.future.AuthFuture;
31 import org.opendaylight.netconf.shaded.sshd.client.future.ConnectFuture;
32 import org.opendaylight.netconf.shaded.sshd.client.future.OpenFuture;
33 import org.opendaylight.netconf.shaded.sshd.client.session.ClientSession;
34 import org.opendaylight.netconf.shaded.sshd.core.CoreModuleProperties;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
39 * Netty SSH handler class. Acts as interface between Netty and SSH library.
41 @Deprecated(since = "7.0.0", forRemoval = true)
42 public final class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
43 private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
44 private static final VarHandle DISCONNECTED;
48 DISCONNECTED = MethodHandles.lookup().findVarHandle(AsyncSshHandler.class, "disconnected", boolean.class);
49 } catch (NoSuchFieldException | IllegalAccessException e) {
50 throw new ExceptionInInitializerError(e);
54 public static final String SUBSYSTEM = "netconf";
56 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
58 public static final NetconfSshClient DEFAULT_CLIENT;
61 final var c = new NetconfClientBuilder().build();
62 // Disable default timeouts from mina sshd
63 final var zero = Duration.ofMillis(0);
64 CoreModuleProperties.AUTH_TIMEOUT.set(c, zero);
65 CoreModuleProperties.IDLE_TIMEOUT.set(c, zero);
66 CoreModuleProperties.NIO2_READ_TIMEOUT.set(c, zero);
67 CoreModuleProperties.TCP_NODELAY.set(c, true);
69 // TODO make configurable, or somehow reuse netty threadpool
70 c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
75 private final AuthenticationHandler authenticationHandler;
76 private final Future<?> negotiationFuture;
77 private final NetconfSshClient sshClient;
78 private final String name;
80 // Initialized by connect()
82 private ChannelPromise connectPromise;
84 private AsyncSshHandlerWriter sshWriteAsyncHandler;
85 private ChannelSubsystem channel;
86 private ClientSession session;
87 private FutureListener<Object> negotiationFutureListener;
89 private volatile boolean disconnected;
91 private AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient,
92 final @Nullable Future<?> negotiationFuture, final @Nullable String name) {
93 this.authenticationHandler = requireNonNull(authenticationHandler);
94 this.sshClient = requireNonNull(sshClient);
95 this.negotiationFuture = negotiationFuture;
96 this.name = name != null && !name.isBlank() ? name : "UNNAMED";
99 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient,
100 final @Nullable Future<?> negotiationFuture) {
101 this(authenticationHandler, sshClient, negotiationFuture, null);
105 * Constructor of {@code AsyncSshHandler}.
107 * @param authenticationHandler authentication handler
108 * @param sshClient started SshClient
110 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient) {
111 this(authenticationHandler, sshClient, null);
114 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
115 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
119 * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
120 * netconf negotiation.
122 * @param authenticationHandler authentication handler
123 * @param negotiationFuture negotiation future
124 * @return {@code AsyncSshHandler}
126 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
127 final Future<?> negotiationFuture, final @Nullable NetconfSshClient sshClient,
128 final @Nullable String name) {
129 return new AsyncSshHandler(authenticationHandler, sshClient != null ? sshClient : DEFAULT_CLIENT,
130 negotiationFuture, name);
134 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
135 sshWriteAsyncHandler.write(ctx, msg, promise);
139 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
140 final SocketAddress localAddress, final ChannelPromise promise) throws IOException {
141 LOG.debug("{}: SSH session connecting on channel {}. promise: {}", name, ctx.channel(), promise);
142 connectPromise = requireNonNull(promise);
144 if (negotiationFuture != null) {
145 negotiationFutureListener = future -> {
146 if (future.isSuccess()) {
147 promise.setSuccess();
150 //complete connection promise with netconf negotiation future
151 negotiationFuture.addListener(negotiationFutureListener);
154 LOG.debug("{}: Starting SSH to {} on channel: {}", name, remoteAddress, ctx.channel());
155 sshClient.connect(authenticationHandler.getUsername(), remoteAddress)
156 // FIXME: this is a blocking call, we should handle this with a concurrently-scheduled timeout. We do not
157 // have a Timer ready, so perhaps we should be using the event loop?
158 .verify(ctx.channel().config().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS)
159 .addListener(future -> onConnectComplete(future, ctx));
162 private synchronized void onConnectComplete(final ConnectFuture connectFuture, final ChannelHandlerContext ctx) {
163 final var cause = connectFuture.getException();
165 onOpenFailure(ctx, cause);
169 final var clientSession = connectFuture.getSession();
170 LOG.trace("{}: SSH session {} created on channel: {}", name, clientSession, ctx.channel());
171 verify(clientSession instanceof NettyAwareClientSession, "Unexpected session %s", clientSession);
173 final var localSession = (NettyAwareClientSession) clientSession;
174 session = localSession;
176 final AuthFuture authFuture;
178 authFuture = authenticationHandler.authenticate(localSession);
179 } catch (final IOException e) {
180 onOpenFailure(ctx, e);
184 authFuture.addListener(future -> onAuthComplete(future, localSession, ctx));
187 private synchronized void onAuthComplete(final AuthFuture authFuture, final NettyAwareClientSession clientSession,
188 final ChannelHandlerContext ctx) {
189 final var cause = authFuture.getException();
191 onOpenFailure(ctx, new AuthenticationFailedException("Authentication failed", cause));
195 LOG.debug("{}: Skipping SSH subsystem allocation, channel: {}", name, ctx.channel());
199 LOG.debug("{}: SSH session authenticated on channel: {}, server version: {}", name, ctx.channel(),
200 clientSession.getServerVersion());
202 final OpenFuture openFuture;
204 channel = clientSession.createSubsystemChannel(SUBSYSTEM, ctx);
205 channel.setStreaming(ClientChannel.Streaming.Async);
206 openFuture = channel.open();
207 } catch (final IOException e) {
208 onOpenFailure(ctx, e);
212 openFuture.addListener(future -> ctx.executor().execute(() -> onOpenComplete(future, ctx)));
215 // This callback has to run on the channel's executor because it runs fireChannelActive(), which needs to be
216 // delivered synchronously. If we were to execute on some other thread we would end up delaying the event,
217 // potentially creating havoc in the pipeline.
218 private synchronized void onOpenComplete(final OpenFuture openFuture, final ChannelHandlerContext ctx) {
219 final var cause = openFuture.getException();
221 onOpenFailure(ctx, cause);
225 LOG.trace("{}: Skipping activation, channel: {}", name, ctx.channel());
229 LOG.trace("{}: SSH subsystem channel opened successfully on channel: {}", name, ctx.channel());
230 if (negotiationFuture == null) {
231 connectPromise.setSuccess();
234 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
235 ctx.fireChannelActive();
236 channel.onClose(() -> disconnect(ctx, ctx.newPromise()));
240 private void onOpenFailure(final ChannelHandlerContext ctx, final Throwable cause) {
241 LOG.warn("{}: Unable to setup SSH connection on channel: {}", name, ctx.channel(), cause);
243 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
244 if (!connectPromise.isDone()) {
245 connectPromise.setFailure(cause);
248 disconnect(ctx, ctx.newPromise());
252 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
253 disconnect(ctx, promise);
257 public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
258 if (DISCONNECTED.compareAndSet(this, false, true)) {
259 ctx.executor().execute(() -> safelyDisconnect(ctx, promise));
263 // This method has the potential to interact with the channel pipeline, for example via fireChannelInactive(). These
264 // callbacks need to complete during execution of this method and therefore this method needs to be executing on
265 // the channel's executor.
266 @SuppressWarnings("checkstyle:IllegalCatch")
267 private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
268 LOG.trace("{}: Closing SSH session on channel: {} with connect promise in state: {}", name, ctx.channel(),
271 // If we have already succeeded and the session was dropped after,
272 // we need to fire inactive to notify reconnect logic
273 if (connectPromise.isSuccess()) {
274 ctx.fireChannelInactive();
277 if (sshWriteAsyncHandler != null) {
278 sshWriteAsyncHandler.close();
281 //If connection promise is not already set, it means negotiation failed
282 //we must set connection promise to failure
283 if (!connectPromise.isDone()) {
284 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
287 //Remove listener from negotiation future, we don't want notifications
288 //from negotiation anymore
289 if (negotiationFuture != null) {
290 negotiationFuture.removeListener(negotiationFutureListener);
293 if (session != null && !session.isClosed() && !session.isClosing()) {
294 session.close(false).addListener(future -> {
295 synchronized (this) {
296 if (!future.isClosed()) {
304 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
305 // to cleanup its resources e.g. Socket that it tries to open in its constructor
306 // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
307 // TODO better solution would be to implement custom ChannelFactory + Channel
308 // that will use mina SSH lib internally: port this to custom channel implementation
310 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
311 super.disconnect(ctx, ctx.newPromise());
312 } catch (final Exception e) {
313 LOG.warn("{}: Unable to cleanup all resources for channel: {}. Ignoring.", name, ctx.channel(), e);
316 if (channel != null) {
317 channel.close(false);
320 promise.setSuccess();
321 LOG.debug("{}: SSH session closed on channel: {}", name, ctx.channel());