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,
106 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
107 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
109 if (negotiationFuture == null) {
110 connectPromise.setSuccess();
113 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
114 ctx.fireChannelActive();
115 channel.onClose(() -> disconnect(ctx, ctx.newPromise()));
118 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
119 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
121 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
122 if (!connectPromise.isDone()) {
123 connectPromise.setFailure(error);
126 disconnect(ctx, ctx.newPromise());
130 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
131 sshWriteAsyncHandler.write(ctx, msg, promise);
135 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
136 final SocketAddress localAddress, final ChannelPromise promise) throws IOException {
137 LOG.debug("SSH session connecting on channel {}. promise: {}", ctx.channel(), promise);
138 connectPromise = requireNonNull(promise);
140 if (negotiationFuture != null) {
141 negotiationFutureListener = future -> {
142 if (future.isSuccess()) {
143 promise.setSuccess();
146 //complete connection promise with netconf negotiation future
147 negotiationFuture.addListener(negotiationFutureListener);
150 LOG.debug("Starting SSH to {} on channel: {}", remoteAddress, ctx.channel());
151 sshClient.connect(authenticationHandler.getUsername(), remoteAddress)
152 // FIXME: this is a blocking call, we should handle this with a concurrently-scheduled timeout. We do not
153 // have a Timer ready, so perhaps we should be using the event loop?
154 .verify(ctx.channel().config().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS)
155 .addListener(future -> onConnectComplete(future, ctx));
158 private void onConnectComplete(final ConnectFuture future, final ChannelHandlerContext ctx) {
159 final var cause = future.getException();
161 handleSshSetupFailure(ctx, cause);
165 final var clientSession = future.getSession();
166 LOG.trace("SSH session {} created on channel: {}", clientSession, ctx.channel());
167 verify(clientSession instanceof NettyAwareClientSession, "Unexpected session %s", clientSession);
168 onConnectComplete((NettyAwareClientSession) clientSession, ctx);
171 private synchronized void onConnectComplete(final NettyAwareClientSession clientSession,
172 final ChannelHandlerContext ctx) {
173 session = clientSession;
175 final AuthFuture authFuture;
177 authFuture = authenticationHandler.authenticate(clientSession);
178 } catch (final IOException e) {
179 handleSshSetupFailure(ctx, e);
183 authFuture.addListener(future -> onAuthComplete(future, clientSession, ctx));
186 private void onAuthComplete(final AuthFuture future, final NettyAwareClientSession clientSession,
187 final ChannelHandlerContext ctx) {
188 final var cause = future.getException();
190 handleSshSetupFailure(ctx, new AuthenticationFailedException("Authentication failed", cause));
194 onAuthComplete(clientSession, ctx);
197 private synchronized void onAuthComplete(final NettyAwareClientSession clientSession,
198 final ChannelHandlerContext ctx) {
199 LOG.debug("SSH session authenticated on channel: {}, server version: {}", 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 handleSshSetupFailure(ctx, e);
212 openFuture.addListener(future -> onOpenComplete(future, ctx));
215 private void onOpenComplete(final OpenFuture future, final ChannelHandlerContext ctx) {
216 final var cause = future.getException();
218 handleSshSetupFailure(ctx, cause);
222 handleSshChanelOpened(ctx);
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());