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.checkerframework.checker.lock.qual.GuardedBy;
23 import org.checkerframework.checker.lock.qual.Holding;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
26 import org.opendaylight.netconf.shaded.sshd.client.channel.ClientChannel;
27 import org.opendaylight.netconf.shaded.sshd.client.future.AuthFuture;
28 import org.opendaylight.netconf.shaded.sshd.client.future.ConnectFuture;
29 import org.opendaylight.netconf.shaded.sshd.client.future.OpenFuture;
30 import org.opendaylight.netconf.shaded.sshd.client.session.ClientSession;
31 import org.opendaylight.netconf.shaded.sshd.core.CoreModuleProperties;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
36 * Netty SSH handler class. Acts as interface between Netty and SSH library.
38 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
39 private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
41 public static final String SUBSYSTEM = "netconf";
43 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
45 public static final NetconfSshClient DEFAULT_CLIENT;
48 final NetconfSshClient c = new NetconfClientBuilder().build();
49 // Disable default timeouts from mina sshd
50 c.getProperties().put(CoreModuleProperties.AUTH_TIMEOUT.getName(), "0");
51 c.getProperties().put(CoreModuleProperties.IDLE_TIMEOUT.getName(), "0");
52 c.getProperties().put(CoreModuleProperties.NIO2_READ_TIMEOUT.getName(), "0");
53 c.getProperties().put(CoreModuleProperties.TCP_NODELAY.getName(), true);
55 // TODO make configurable, or somehow reuse netty threadpool
56 c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
61 private final AtomicBoolean isDisconnected = new AtomicBoolean();
62 private final AuthenticationHandler authenticationHandler;
63 private final Future<?> negotiationFuture;
64 private final NetconfSshClient sshClient;
66 // Initialized by connect()
68 private ChannelPromise connectPromise;
70 private AsyncSshHandlerWriter sshWriteAsyncHandler;
71 private NettyAwareChannelSubsystem channel;
72 private ClientSession session;
73 private FutureListener<Object> negotiationFutureListener;
75 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient,
76 final Future<?> negotiationFuture) {
77 this.authenticationHandler = requireNonNull(authenticationHandler);
78 this.sshClient = requireNonNull(sshClient);
79 this.negotiationFuture = negotiationFuture;
83 * Constructor of {@code AsyncSshHandler}.
85 * @param authenticationHandler authentication handler
86 * @param sshClient started SshClient
88 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient) {
89 this(authenticationHandler, sshClient, null);
92 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
93 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
97 * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
98 * netconf negotiation.
100 * @param authenticationHandler authentication handler
101 * @param negotiationFuture negotiation future
102 * @return {@code AsyncSshHandler}
104 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
105 final Future<?> negotiationFuture, final @Nullable NetconfSshClient sshClient) {
106 return new AsyncSshHandler(authenticationHandler, sshClient != null ? sshClient : DEFAULT_CLIENT,
111 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
112 sshWriteAsyncHandler.write(ctx, msg, promise);
116 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
117 final SocketAddress localAddress, final ChannelPromise promise) throws IOException {
118 LOG.debug("SSH session connecting on channel {}. promise: {}", ctx.channel(), promise);
119 connectPromise = requireNonNull(promise);
121 if (negotiationFuture != null) {
122 negotiationFutureListener = future -> {
123 if (future.isSuccess()) {
124 promise.setSuccess();
127 //complete connection promise with netconf negotiation future
128 negotiationFuture.addListener(negotiationFutureListener);
131 LOG.debug("Starting SSH to {} on channel: {}", remoteAddress, ctx.channel());
132 sshClient.connect(authenticationHandler.getUsername(), remoteAddress)
133 // FIXME: this is a blocking call, we should handle this with a concurrently-scheduled timeout. We do not
134 // have a Timer ready, so perhaps we should be using the event loop?
135 .verify(ctx.channel().config().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS)
136 .addListener(future -> onConnectComplete(future, ctx));
139 private synchronized void onConnectComplete(final ConnectFuture connectFuture, final ChannelHandlerContext ctx) {
140 final var cause = connectFuture.getException();
142 onOpenFailure(ctx, cause);
146 final var clientSession = connectFuture.getSession();
147 LOG.trace("SSH session {} created on channel: {}", clientSession, ctx.channel());
148 verify(clientSession instanceof NettyAwareClientSession, "Unexpected session %s", clientSession);
150 final var localSession = (NettyAwareClientSession) clientSession;
151 session = localSession;
153 final AuthFuture authFuture;
155 authFuture = authenticationHandler.authenticate(localSession);
156 } catch (final IOException e) {
157 onOpenFailure(ctx, e);
161 authFuture.addListener(future -> onAuthComplete(future, localSession, ctx));
164 private synchronized void onAuthComplete(final AuthFuture authFuture, final NettyAwareClientSession clientSession,
165 final ChannelHandlerContext ctx) {
166 final var cause = authFuture.getException();
168 onOpenFailure(ctx, new AuthenticationFailedException("Authentication failed", cause));
172 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
173 clientSession.getServerVersion());
175 final OpenFuture openFuture;
177 channel = clientSession.createSubsystemChannel(SUBSYSTEM, ctx);
178 channel.setStreaming(ClientChannel.Streaming.Async);
179 openFuture = channel.open();
180 } catch (final IOException e) {
181 onOpenFailure(ctx, e);
185 openFuture.addListener(future -> onOpenComplete(future, ctx));
188 private synchronized void onOpenComplete(final OpenFuture openFuture, final ChannelHandlerContext ctx) {
189 final var cause = openFuture.getException();
191 onOpenFailure(ctx, cause);
195 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
196 if (negotiationFuture == null) {
197 connectPromise.setSuccess();
200 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
201 ctx.fireChannelActive();
202 channel.onClose(() -> disconnect(ctx, ctx.newPromise()));
206 private void onOpenFailure(final ChannelHandlerContext ctx, final Throwable cause) {
207 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), cause);
209 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
210 if (!connectPromise.isDone()) {
211 connectPromise.setFailure(cause);
214 disconnect(ctx, ctx.newPromise());
218 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
219 disconnect(ctx, promise);
223 public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
224 if (isDisconnected.compareAndSet(false, true)) {
225 ctx.executor().execute(() -> safelyDisconnect(ctx, promise));
229 // This method has the potential to interact with the channel pipeline, for example via fireChannelInactive(). These
230 // callbacks need to complete during execution of this method and therefore this method needs to be executing on
231 // the channel's executor.
232 @SuppressWarnings("checkstyle:IllegalCatch")
233 private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
234 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(),
237 // If we have already succeeded and the session was dropped after,
238 // we need to fire inactive to notify reconnect logic
239 if (connectPromise.isSuccess()) {
240 ctx.fireChannelInactive();
243 if (sshWriteAsyncHandler != null) {
244 sshWriteAsyncHandler.close();
247 //If connection promise is not already set, it means negotiation failed
248 //we must set connection promise to failure
249 if (!connectPromise.isDone()) {
250 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
253 //Remove listener from negotiation future, we don't want notifications
254 //from negotiation anymore
255 if (negotiationFuture != null) {
256 negotiationFuture.removeListener(negotiationFutureListener);
259 if (session != null && !session.isClosed() && !session.isClosing()) {
260 session.close(false).addListener(future -> {
261 synchronized (this) {
262 if (!future.isClosed()) {
270 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
271 // to cleanup its resources e.g. Socket that it tries to open in its constructor
272 // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
273 // TODO better solution would be to implement custom ChannelFactory + Channel
274 // that will use mina SSH lib internally: port this to custom channel implementation
276 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
277 super.disconnect(ctx, ctx.newPromise());
278 } catch (final Exception e) {
279 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
282 if (channel != null) {
283 //TODO: see if calling just close() is sufficient
284 //channel.close(false);
288 promise.setSuccess();
289 LOG.debug("SSH session closed on channel: {}", ctx.channel());