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) {
144 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
145 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());
158 } catch (final IOException e) {
159 handleSshSetupFailure(ctx, e);
163 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
164 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
166 if (negotiationFuture == null) {
167 connectPromise.setSuccess();
170 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
171 ctx.fireChannelActive();
172 channel.onClose(() -> disconnect(ctx, ctx.newPromise()));
175 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
176 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
178 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
179 if (!connectPromise.isDone()) {
180 connectPromise.setFailure(error);
183 disconnect(ctx, ctx.newPromise());
187 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
188 sshWriteAsyncHandler.write(ctx, msg, promise);
192 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
193 final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
194 LOG.debug("SSH session connecting on channel {}. promise: {}", ctx.channel(), connectPromise);
195 connectPromise = promise;
197 if (negotiationFuture != null) {
198 negotiationFutureListener = future -> {
199 if (future.isSuccess()) {
200 promise.setSuccess();
203 //complete connection promise with netconf negotiation future
204 negotiationFuture.addListener(negotiationFutureListener);
206 startSsh(ctx, remoteAddress);
210 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
211 disconnect(ctx, promise);
215 public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
216 if (isDisconnected.compareAndSet(false, true)) {
217 safelyDisconnect(ctx, promise);
221 @SuppressWarnings("checkstyle:IllegalCatch")
222 private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
223 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
224 ctx.channel(), connectPromise);
226 // If we have already succeeded and the session was dropped after,
227 // we need to fire inactive to notify reconnect logic
228 if (connectPromise.isSuccess()) {
229 ctx.fireChannelInactive();
232 if (sshWriteAsyncHandler != null) {
233 sshWriteAsyncHandler.close();
236 //If connection promise is not already set, it means negotiation failed
237 //we must set connection promise to failure
238 if (!connectPromise.isDone()) {
239 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
242 //Remove listener from negotiation future, we don't want notifications
243 //from negotiation anymore
244 if (negotiationFuture != null) {
245 negotiationFuture.removeListener(negotiationFutureListener);
248 if (session != null && !session.isClosed() && !session.isClosing()) {
249 session.close(false).addListener(future -> {
250 synchronized (this) {
251 if (!future.isClosed()) {
259 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
260 // to cleanup its resources e.g. Socket that it tries to open in its constructor
261 // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
262 // TODO better solution would be to implement custom ChannelFactory + Channel
263 // that will use mina SSH lib internally: port this to custom channel implementation
265 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
266 super.disconnect(ctx, ctx.newPromise());
267 } catch (final Exception e) {
268 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
271 if (channel != null) {
272 //TODO: see if calling just close() is sufficient
273 //channel.close(false);
277 promise.setSuccess();
278 LOG.debug("SSH session closed on channel: {}", ctx.channel());