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
9 package org.opendaylight.netconf.nettyutil.handler.ssh.client;
11 import com.google.common.base.Preconditions;
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 org.apache.sshd.client.SshClient;
20 import org.apache.sshd.client.channel.ClientChannel;
21 import org.apache.sshd.client.future.AuthFuture;
22 import org.apache.sshd.client.future.ConnectFuture;
23 import org.apache.sshd.client.session.ClientSession;
24 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * Netty SSH handler class. Acts as interface between Netty and SSH library.
31 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
32 private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
34 public static final String SUBSYSTEM = "netconf";
36 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
37 // Disable default timeouts from mina sshd
38 private static final long DEFAULT_TIMEOUT = -1L;
40 public static final SshClient DEFAULT_CLIENT;
43 final SshClient c = SshClient.setUpDefaultClient();
44 c.getProperties().put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
45 c.getProperties().put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
47 // TODO make configurable, or somehow reuse netty threadpool
48 c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
53 private final AuthenticationHandler authenticationHandler;
54 private final SshClient sshClient;
55 private Future<?> negotiationFuture;
57 private AsyncSshHandlerReader sshReadAsyncListener;
58 private AsyncSshHandlerWriter sshWriteAsyncHandler;
60 private ClientChannel channel;
61 private ClientSession session;
62 private ChannelPromise connectPromise;
63 private GenericFutureListener negotiationFutureListener;
65 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient,
66 final Future<?> negotiationFuture) throws IOException {
67 this(authenticationHandler, sshClient);
68 this.negotiationFuture = negotiationFuture;
72 * Constructor of {@code AsyncSshHandler}.
74 * @param authenticationHandler authentication handler
75 * @param sshClient started SshClient
76 * @throws IOException if the I/O operation fails
78 public AsyncSshHandler(final AuthenticationHandler authenticationHandler,
79 final SshClient sshClient) throws IOException {
80 this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
81 this.sshClient = Preconditions.checkNotNull(sshClient);
84 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler)
86 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
90 * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
91 * netconf negotiation.
93 * @param authenticationHandler authentication handler
94 * @param negotiationFuture negotiation future
95 * @return {@code AsyncSshHandler}
96 * @throws IOException if the I/O operation fails
98 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
99 final Future<?> negotiationFuture) throws IOException {
100 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture);
103 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) throws IOException {
104 LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
106 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
107 sshConnectionFuture.addListener(future -> {
108 if (future.isConnected()) {
109 handleSshSessionCreated(future, ctx);
111 handleSshSetupFailure(ctx, future.getException());
116 private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
118 LOG.trace("SSH session created on channel: {}", ctx.channel());
120 session = future.getSession();
121 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
122 authenticateFuture.addListener(future1 -> {
123 if (future1.isSuccess()) {
124 handleSshAuthenticated(session, ctx);
126 // Exception does not have to be set in the future, add simple exception in such case
127 final Throwable exception = future1.getException() == null
128 ? new IllegalStateException("Authentication failed") : future1.getException();
129 handleSshSetupFailure(ctx, exception);
132 } catch (final IOException e) {
133 handleSshSetupFailure(ctx, e);
137 private synchronized void handleSshAuthenticated(final ClientSession newSession, final ChannelHandlerContext ctx) {
139 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
140 newSession.getServerVersion());
142 channel = newSession.createSubsystemChannel(SUBSYSTEM);
143 channel.setStreaming(ClientChannel.Streaming.Async);
144 channel.open().addListener(future -> {
145 if (future.isOpened()) {
146 handleSshChanelOpened(ctx);
148 handleSshSetupFailure(ctx, future.getException());
153 } catch (final IOException e) {
154 handleSshSetupFailure(ctx, e);
158 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
159 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
161 if (negotiationFuture == null) {
162 connectPromise.setSuccess();
165 // TODO we should also read from error stream and at least log from that
167 sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
168 msg -> ctx.fireChannelRead(msg), channel.toString(), channel.getAsyncOut());
170 // if readAsyncListener receives immediate close,
171 // it will close this handler and closing this handler sets channel variable to null
172 if (channel != null) {
173 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
174 ctx.fireChannelActive();
178 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
179 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
181 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
182 if (!connectPromise.isDone()) {
183 connectPromise.setFailure(error);
186 disconnect(ctx, ctx.newPromise());
190 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
191 sshWriteAsyncHandler.write(ctx, msg, promise);
195 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
196 final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
197 LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
198 this.connectPromise = promise;
200 if (negotiationFuture != null) {
202 negotiationFutureListener = future -> {
203 if (future.isSuccess()) {
204 connectPromise.setSuccess();
207 //complete connection promise with netconf negotiation future
208 negotiationFuture.addListener(negotiationFutureListener);
210 startSsh(ctx, remoteAddress);
214 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
215 disconnect(ctx, promise);
218 @SuppressWarnings("checkstyle:IllegalCatch")
220 public synchronized void disconnect(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 (sshReadAsyncListener != null) {
235 sshReadAsyncListener.close();
238 //If connection promise is not already set, it means negotiation failed
239 //we must set connection promise to failure
240 if (!connectPromise.isDone()) {
241 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
244 //Remove listener from negotiation future, we don't want notifications
245 //from negotiation anymore
246 if (negotiationFuture != null) {
247 negotiationFuture.removeListener(negotiationFutureListener);
250 if (session != null && !session.isClosed() && !session.isClosing()) {
251 session.close(false).addListener(future -> {
252 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);
272 promise.setSuccess();
273 LOG.debug("SSH session closed on channel: {}", ctx.channel());