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 synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
107 LOG.trace("SSH session created on channel: {}", ctx.channel());
109 session = future.getSession();
110 verify(session instanceof NettyAwareClientSession, "Unexpected session %s", session);
112 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
113 final NettyAwareClientSession localSession = (NettyAwareClientSession) session;
114 authenticateFuture.addListener(future1 -> {
115 if (future1.isSuccess()) {
116 handleSshAuthenticated(localSession, ctx);
118 handleSshSetupFailure(ctx, new AuthenticationFailedException("Authentication failed",
119 future1.getException()));
122 } catch (final IOException e) {
123 handleSshSetupFailure(ctx, e);
127 private synchronized void handleSshAuthenticated(final NettyAwareClientSession newSession,
128 final ChannelHandlerContext ctx) {
129 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
130 newSession.getServerVersion());
133 channel = newSession.createSubsystemChannel(SUBSYSTEM, ctx);
134 channel.setStreaming(ClientChannel.Streaming.Async);
135 channel.open().addListener(future -> {
136 if (future.isOpened()) {
137 handleSshChanelOpened(ctx);
139 handleSshSetupFailure(ctx, future.getException());
142 } catch (final IOException e) {
143 handleSshSetupFailure(ctx, e);
147 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
148 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
150 if (negotiationFuture == null) {
151 connectPromise.setSuccess();
154 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
155 ctx.fireChannelActive();
156 channel.onClose(() -> disconnect(ctx, ctx.newPromise()));
159 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
160 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
162 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
163 if (!connectPromise.isDone()) {
164 connectPromise.setFailure(error);
167 disconnect(ctx, ctx.newPromise());
171 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
172 sshWriteAsyncHandler.write(ctx, msg, promise);
176 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
177 final SocketAddress localAddress, final ChannelPromise promise) throws IOException {
178 LOG.debug("SSH session connecting on channel {}. promise: {}", ctx.channel(), promise);
179 connectPromise = requireNonNull(promise);
181 if (negotiationFuture != null) {
182 negotiationFutureListener = future -> {
183 if (future.isSuccess()) {
184 promise.setSuccess();
187 //complete connection promise with netconf negotiation future
188 negotiationFuture.addListener(negotiationFutureListener);
191 LOG.debug("Starting SSH to {} on channel: {}", remoteAddress, ctx.channel());
192 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), remoteAddress)
193 // FIXME: this is a blocking call, we should handle this with a concurrently-scheduled timeout. We do not
194 // have a Timer ready, so perhaps we should be using the event loop?
195 .verify(ctx.channel().config().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
196 sshConnectionFuture.addListener(future -> {
197 if (future.isConnected()) {
198 handleSshSessionCreated(future, ctx);
200 handleSshSetupFailure(ctx, future.getException());
206 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
207 disconnect(ctx, promise);
211 public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
212 if (isDisconnected.compareAndSet(false, true)) {
213 safelyDisconnect(ctx, promise);
217 @SuppressWarnings("checkstyle:IllegalCatch")
218 private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
219 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
220 ctx.channel(), connectPromise);
222 // If we have already succeeded and the session was dropped after,
223 // we need to fire inactive to notify reconnect logic
224 if (connectPromise.isSuccess()) {
225 ctx.fireChannelInactive();
228 if (sshWriteAsyncHandler != null) {
229 sshWriteAsyncHandler.close();
232 //If connection promise is not already set, it means negotiation failed
233 //we must set connection promise to failure
234 if (!connectPromise.isDone()) {
235 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
238 //Remove listener from negotiation future, we don't want notifications
239 //from negotiation anymore
240 if (negotiationFuture != null) {
241 negotiationFuture.removeListener(negotiationFutureListener);
244 if (session != null && !session.isClosed() && !session.isClosing()) {
245 session.close(false).addListener(future -> {
246 synchronized (this) {
247 if (!future.isClosed()) {
255 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
256 // to cleanup its resources e.g. Socket that it tries to open in its constructor
257 // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
258 // TODO better solution would be to implement custom ChannelFactory + Channel
259 // that will use mina SSH lib internally: port this to custom channel implementation
261 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
262 super.disconnect(ctx, ctx.newPromise());
263 } catch (final Exception e) {
264 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
267 if (channel != null) {
268 //TODO: see if calling just close() is sufficient
269 //channel.close(false);
273 promise.setSuccess();
274 LOG.debug("SSH session closed on channel: {}", ctx.channel());