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.apache.sshd.client.SshClient;
22 import org.apache.sshd.client.channel.ClientChannel;
23 import org.apache.sshd.client.future.AuthFuture;
24 import org.apache.sshd.client.future.ConnectFuture;
25 import org.apache.sshd.client.session.ClientSession;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
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 // Exception does not have to be set in the future, add simple exception in such case
130 final Throwable exception = future1.getException() == null
131 ? new IllegalStateException("Authentication failed") : future1.getException();
132 handleSshSetupFailure(ctx, exception);
135 } catch (final IOException e) {
136 handleSshSetupFailure(ctx, e);
140 private synchronized void handleSshAuthenticated(final ClientSession newSession, final ChannelHandlerContext ctx) {
142 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
143 newSession.getServerVersion());
145 channel = newSession.createSubsystemChannel(SUBSYSTEM);
146 channel.setStreaming(ClientChannel.Streaming.Async);
147 channel.open().addListener(future -> {
148 if (future.isOpened()) {
149 handleSshChanelOpened(ctx);
151 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 // TODO we should also read from error stream and at least log from that
170 ClientChannel localChannel = channel;
171 sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
172 ctx::fireChannelRead, localChannel.toString(), localChannel.getAsyncOut());
174 // if readAsyncListener receives immediate close,
175 // it will close this handler and closing this handler sets channel variable to null
176 if (channel != null) {
177 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
178 ctx.fireChannelActive();
182 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
183 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
185 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
186 if (!connectPromise.isDone()) {
187 connectPromise.setFailure(error);
190 disconnect(ctx, ctx.newPromise());
194 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
195 sshWriteAsyncHandler.write(ctx, msg, promise);
199 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
200 final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
201 LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
202 this.connectPromise = promise;
204 if (negotiationFuture != null) {
205 negotiationFutureListener = future -> {
206 if (future.isSuccess()) {
207 promise.setSuccess();
210 //complete connection promise with netconf negotiation future
211 negotiationFuture.addListener(negotiationFutureListener);
213 startSsh(ctx, remoteAddress);
217 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
218 disconnect(ctx, promise);
222 public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
223 if (isDisconnected.compareAndSet(false, true)) {
224 safelyDisconnect(ctx, promise);
228 @SuppressWarnings("checkstyle:IllegalCatch")
229 private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
230 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
231 ctx.channel(), connectPromise);
233 // If we have already succeeded and the session was dropped after,
234 // we need to fire inactive to notify reconnect logic
235 if (connectPromise.isSuccess()) {
236 ctx.fireChannelInactive();
239 if (sshWriteAsyncHandler != null) {
240 sshWriteAsyncHandler.close();
243 if (sshReadAsyncListener != null) {
244 sshReadAsyncListener.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);
283 promise.setSuccess();
284 LOG.debug("SSH session closed on channel: {}", ctx.channel());