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 java.util.Objects.requireNonNull;
12 import io.netty.channel.ChannelHandlerContext;
13 import io.netty.channel.ChannelOutboundHandlerAdapter;
14 import io.netty.channel.ChannelPromise;
15 import io.netty.util.concurrent.Future;
16 import io.netty.util.concurrent.GenericFutureListener;
17 import java.io.IOException;
18 import java.net.SocketAddress;
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.atomic.AtomicBoolean;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
23 import org.opendaylight.netconf.shaded.sshd.client.SshClient;
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.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
32 * Netty SSH handler class. Acts as interface between Netty and SSH library.
34 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
35 private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
37 public static final String SUBSYSTEM = "netconf";
39 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
40 // Disable default timeouts from mina sshd
41 private static final long DEFAULT_TIMEOUT = -1L;
43 public static final SshClient DEFAULT_CLIENT;
46 final SshClient c = SshClient.setUpDefaultClient();
47 c.getProperties().put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
48 c.getProperties().put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
50 // TODO make configurable, or somehow reuse netty threadpool
51 c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
56 private final AtomicBoolean isDisconnected = new AtomicBoolean();
57 private final AuthenticationHandler authenticationHandler;
58 private final SshClient sshClient;
59 private final Future<?> negotiationFuture;
61 private AsyncSshHandlerReader sshReadAsyncListener;
62 private AsyncSshHandlerWriter sshWriteAsyncHandler;
64 private ClientChannel channel;
65 private ClientSession session;
66 private ChannelPromise connectPromise;
67 private GenericFutureListener negotiationFutureListener;
69 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient,
70 final Future<?> negotiationFuture) {
71 this.authenticationHandler = requireNonNull(authenticationHandler);
72 this.sshClient = requireNonNull(sshClient);
73 this.negotiationFuture = negotiationFuture;
77 * Constructor of {@code AsyncSshHandler}.
79 * @param authenticationHandler authentication handler
80 * @param sshClient started SshClient
82 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) {
83 this(authenticationHandler, sshClient, null);
86 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
87 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
91 * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
92 * netconf negotiation.
94 * @param authenticationHandler authentication handler
95 * @param negotiationFuture negotiation future
96 * @return {@code AsyncSshHandler}
98 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
99 final Future<?> negotiationFuture, @Nullable final SshClient sshClient) {
100 return new AsyncSshHandler(authenticationHandler, sshClient != null ? sshClient : DEFAULT_CLIENT,
104 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) throws IOException {
105 LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
107 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address)
108 .verify(ctx.channel().config().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
109 sshConnectionFuture.addListener(future -> {
110 if (future.isConnected()) {
111 handleSshSessionCreated(future, ctx);
113 handleSshSetupFailure(ctx, future.getException());
118 private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
120 LOG.trace("SSH session created on channel: {}", ctx.channel());
122 session = future.getSession();
123 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
124 final ClientSession localSession = session;
125 authenticateFuture.addListener(future1 -> {
126 if (future1.isSuccess()) {
127 handleSshAuthenticated(localSession, ctx);
129 handleSshSetupFailure(ctx, new AuthenticationFailedException("Authentication failed",
130 future1.getException()));
133 } catch (final IOException e) {
134 handleSshSetupFailure(ctx, e);
138 private synchronized void handleSshAuthenticated(final ClientSession newSession, final ChannelHandlerContext ctx) {
140 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
141 newSession.getServerVersion());
143 channel = newSession.createSubsystemChannel(SUBSYSTEM);
144 channel.setStreaming(ClientChannel.Streaming.Async);
145 channel.open().addListener(future -> {
146 if (future.isOpened()) {
147 handleSshChanelOpened(ctx);
149 handleSshSetupFailure(ctx, future.getException());
154 } catch (final IOException e) {
155 handleSshSetupFailure(ctx, e);
159 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
160 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
162 if (negotiationFuture == null) {
163 connectPromise.setSuccess();
166 // TODO we should also read from error stream and at least log from that
168 ClientChannel localChannel = channel;
169 sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
170 ctx::fireChannelRead, localChannel.toString(), localChannel.getAsyncOut());
172 // if readAsyncListener receives immediate close,
173 // it will close this handler and closing this handler sets channel variable to null
174 if (channel != null) {
175 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
176 ctx.fireChannelActive();
180 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
181 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
183 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
184 if (!connectPromise.isDone()) {
185 connectPromise.setFailure(error);
188 disconnect(ctx, ctx.newPromise());
192 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
193 sshWriteAsyncHandler.write(ctx, msg, promise);
197 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
198 final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
199 LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
200 this.connectPromise = promise;
202 if (negotiationFuture != null) {
203 negotiationFutureListener = future -> {
204 if (future.isSuccess()) {
205 promise.setSuccess();
208 //complete connection promise with netconf negotiation future
209 negotiationFuture.addListener(negotiationFutureListener);
211 startSsh(ctx, remoteAddress);
215 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
216 disconnect(ctx, promise);
220 public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
221 if (isDisconnected.compareAndSet(false, true)) {
222 safelyDisconnect(ctx, promise);
226 @SuppressWarnings("checkstyle:IllegalCatch")
227 private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
228 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
229 ctx.channel(), connectPromise);
231 // If we have already succeeded and the session was dropped after,
232 // we need to fire inactive to notify reconnect logic
233 if (connectPromise.isSuccess()) {
234 ctx.fireChannelInactive();
237 if (sshWriteAsyncHandler != null) {
238 sshWriteAsyncHandler.close();
241 if (sshReadAsyncListener != null) {
242 sshReadAsyncListener.close();
245 //If connection promise is not already set, it means negotiation failed
246 //we must set connection promise to failure
247 if (!connectPromise.isDone()) {
248 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
251 //Remove listener from negotiation future, we don't want notifications
252 //from negotiation anymore
253 if (negotiationFuture != null) {
254 negotiationFuture.removeListener(negotiationFutureListener);
257 if (session != null && !session.isClosed() && !session.isClosing()) {
258 session.close(false).addListener(future -> {
259 synchronized (this) {
260 if (!future.isClosed()) {
268 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
269 // to cleanup its resources e.g. Socket that it tries to open in its constructor
270 // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
271 // TODO better solution would be to implement custom ChannelFactory + Channel
272 // that will use mina SSH lib internally: port this to custom channel implementation
274 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
275 super.disconnect(ctx, ctx.newPromise());
276 } catch (final Exception e) {
277 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
281 promise.setSuccess();
282 LOG.debug("SSH session closed on channel: {}", ctx.channel());