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.session.ClientSession;
28 import org.opendaylight.netconf.shaded.sshd.core.CoreModuleProperties;
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;
42 public static final NetconfSshClient DEFAULT_CLIENT;
45 final NetconfSshClient c = new NetconfClientBuilder().build();
46 // Disable default timeouts from mina sshd
47 c.getProperties().put(CoreModuleProperties.AUTH_TIMEOUT.getName(), "0");
48 c.getProperties().put(CoreModuleProperties.IDLE_TIMEOUT.getName(), "0");
49 c.getProperties().put(CoreModuleProperties.NIO2_READ_TIMEOUT.getName(), "0");
50 c.getProperties().put(CoreModuleProperties.TCP_NODELAY.getName(), true);
52 // TODO make configurable, or somehow reuse netty threadpool
53 c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
58 private final AtomicBoolean isDisconnected = new AtomicBoolean();
59 private final AuthenticationHandler authenticationHandler;
60 private final Future<?> negotiationFuture;
61 private final NetconfSshClient sshClient;
63 private AsyncSshHandlerWriter sshWriteAsyncHandler;
65 private NettyAwareChannelSubsystem channel;
66 private ClientSession session;
67 private ChannelPromise connectPromise;
68 private FutureListener<Object> negotiationFutureListener;
70 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient,
71 final Future<?> negotiationFuture) {
72 this.authenticationHandler = requireNonNull(authenticationHandler);
73 this.sshClient = requireNonNull(sshClient);
74 this.negotiationFuture = negotiationFuture;
78 * Constructor of {@code AsyncSshHandler}.
80 * @param authenticationHandler authentication handler
81 * @param sshClient started SshClient
83 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final NetconfSshClient sshClient) {
84 this(authenticationHandler, sshClient, null);
87 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
88 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
92 * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
93 * netconf negotiation.
95 * @param authenticationHandler authentication handler
96 * @param negotiationFuture negotiation future
97 * @return {@code AsyncSshHandler}
99 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
100 final Future<?> negotiationFuture, final @Nullable NetconfSshClient sshClient) {
101 return new AsyncSshHandler(authenticationHandler, sshClient != null ? sshClient : DEFAULT_CLIENT,
105 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) throws IOException {
106 LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
108 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address)
109 .verify(ctx.channel().config().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
110 sshConnectionFuture.addListener(future -> {
111 if (future.isConnected()) {
112 handleSshSessionCreated(future, ctx);
114 handleSshSetupFailure(ctx, future.getException());
119 private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
121 LOG.trace("SSH session created on channel: {}", ctx.channel());
123 session = future.getSession();
124 verify(session instanceof NettyAwareClientSession, "Unexpected session %s", session);
126 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
127 final NettyAwareClientSession localSession = (NettyAwareClientSession) session;
128 authenticateFuture.addListener(future1 -> {
129 if (future1.isSuccess()) {
130 handleSshAuthenticated(localSession, ctx);
132 handleSshSetupFailure(ctx, new AuthenticationFailedException("Authentication failed",
133 future1.getException()));
136 } catch (final IOException e) {
137 handleSshSetupFailure(ctx, e);
141 private synchronized void handleSshAuthenticated(final NettyAwareClientSession newSession,
142 final ChannelHandlerContext ctx) {
143 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
144 newSession.getServerVersion());
147 channel = newSession.createSubsystemChannel(SUBSYSTEM, ctx);
148 channel.setStreaming(ClientChannel.Streaming.Async);
149 channel.open().addListener(future -> {
150 if (future.isOpened()) {
151 handleSshChanelOpened(ctx);
153 handleSshSetupFailure(ctx, future.getException());
156 } catch (final IOException e) {
157 handleSshSetupFailure(ctx, e);
161 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
162 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
164 if (negotiationFuture == null) {
165 connectPromise.setSuccess();
168 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
169 ctx.fireChannelActive();
170 channel.onClose(() -> disconnect(ctx, ctx.newPromise()));
173 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
174 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
176 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
177 if (!connectPromise.isDone()) {
178 connectPromise.setFailure(error);
181 disconnect(ctx, ctx.newPromise());
185 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
186 sshWriteAsyncHandler.write(ctx, msg, promise);
190 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
191 final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
192 LOG.debug("SSH session connecting on channel {}. promise: {}", ctx.channel(), promise);
193 connectPromise = requireNonNull(promise);
195 if (negotiationFuture != null) {
196 negotiationFutureListener = future -> {
197 if (future.isSuccess()) {
198 promise.setSuccess();
201 //complete connection promise with netconf negotiation future
202 negotiationFuture.addListener(negotiationFutureListener);
204 startSsh(ctx, remoteAddress);
208 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
209 disconnect(ctx, promise);
213 public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
214 if (isDisconnected.compareAndSet(false, true)) {
215 safelyDisconnect(ctx, promise);
219 @SuppressWarnings("checkstyle:IllegalCatch")
220 private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
221 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
222 ctx.channel(), connectPromise);
224 // If we have already succeeded and the session was dropped after,
225 // we need to fire inactive to notify reconnect logic
226 if (connectPromise.isSuccess()) {
227 ctx.fireChannelInactive();
230 if (sshWriteAsyncHandler != null) {
231 sshWriteAsyncHandler.close();
234 //If connection promise is not already set, it means negotiation failed
235 //we must set connection promise to failure
236 if (!connectPromise.isDone()) {
237 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
240 //Remove listener from negotiation future, we don't want notifications
241 //from negotiation anymore
242 if (negotiationFuture != null) {
243 negotiationFuture.removeListener(negotiationFutureListener);
246 if (session != null && !session.isClosed() && !session.isClosing()) {
247 session.close(false).addListener(future -> {
248 synchronized (this) {
249 if (!future.isClosed()) {
257 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
258 // to cleanup its resources e.g. Socket that it tries to open in its constructor
259 // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
260 // TODO better solution would be to implement custom ChannelFactory + Channel
261 // that will use mina SSH lib internally: port this to custom channel implementation
263 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
264 super.disconnect(ctx, ctx.newPromise());
265 } catch (final Exception e) {
266 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
269 if (channel != null) {
270 //TODO: see if calling just close() is sufficient
271 //channel.close(false);
275 promise.setSuccess();
276 LOG.debug("SSH session closed on channel: {}", ctx.channel());