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.buffer.ByteBuf;
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.GenericFutureListener;
18 import java.io.IOException;
19 import java.net.SocketAddress;
20 import org.apache.sshd.client.SshClient;
21 import org.apache.sshd.client.channel.ClientChannel;
22 import org.apache.sshd.client.future.AuthFuture;
23 import org.apache.sshd.client.future.ConnectFuture;
24 import org.apache.sshd.client.future.OpenFuture;
25 import org.apache.sshd.client.session.ClientSession;
26 import org.apache.sshd.client.session.ClientSessionCreator;
27 import org.apache.sshd.common.future.CloseFuture;
28 import org.apache.sshd.common.future.SshFutureListener;
29 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
34 * Netty SSH handler class. Acts as interface between Netty and SSH library.
36 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
37 private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
39 public static final String SUBSYSTEM = "netconf";
41 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
42 // Disable default timeouts from mina sshd
43 private static final long DEFAULT_TIMEOUT = -1L;
45 public static final SshClient DEFAULT_CLIENT;
47 final SshClient c = SshClient.setUpDefaultClient();
48 c.getProperties().put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
49 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 AuthenticationHandler authenticationHandler;
57 private final ClientSessionCreator sshClient;
58 private Future<?> negotiationFuture;
60 private AsyncSshHandlerReader sshReadAsyncListener;
61 private AsyncSshHandlerWriter sshWriteAsyncHandler;
63 private ClientChannel channel;
64 private ClientSession session;
65 private ChannelPromise connectPromise;
66 private GenericFutureListener negotiationFutureListener;
68 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final ClientSessionCreator sshClient,
69 final Future<?> negotiationFuture) {
70 this(authenticationHandler, sshClient);
71 this.negotiationFuture = negotiationFuture;
76 * @param authenticationHandler
77 * @param sshClient started SshClient
79 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final ClientSessionCreator sshClient) {
80 this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
81 this.sshClient = Preconditions.checkNotNull(sshClient);
84 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
85 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
94 * @param negotiationFuture
97 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
98 final Future<?> negotiationFuture) {
99 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture);
102 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) throws IOException {
103 LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
105 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
106 sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
108 public void operationComplete(final ConnectFuture future) {
109 if (future.isConnected()) {
110 handleSshSessionCreated(future, ctx);
112 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 authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
126 public void operationComplete(final AuthFuture future) {
127 if (future.isSuccess()) {
128 handleSshAuthenticated(session, ctx);
130 // Exception does not have to be set in the future, add simple exception in such case
131 final Throwable exception = future.getException() == null ?
132 new IllegalStateException("Authentication failed") :
133 future.getException();
134 handleSshSetupFailure(ctx, exception);
138 } catch (final IOException e) {
139 handleSshSetupFailure(ctx, e);
143 private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
145 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
147 channel = session.createSubsystemChannel(SUBSYSTEM);
148 channel.setStreaming(ClientChannel.Streaming.Async);
149 channel.open().addListener(new SshFutureListener<OpenFuture>() {
151 public void operationComplete(final OpenFuture future) {
152 if(future.isOpened()) {
153 handleSshChanelOpened(ctx);
155 handleSshSetupFailure(ctx, future.getException());
161 } catch (final IOException e) {
162 handleSshSetupFailure(ctx, e);
166 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
167 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
169 if(negotiationFuture == null) {
170 connectPromise.setSuccess();
173 // TODO we should also read from error stream and at least log from that
175 sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() {
177 public void close() throws Exception {
178 AsyncSshHandler.this.disconnect(ctx, ctx.newPromise());
180 }, new AsyncSshHandlerReader.ReadMsgHandler() {
182 public void onMessageRead(final ByteBuf msg) {
183 ctx.fireChannelRead(msg);
185 }, channel.toString(), channel.getAsyncOut());
187 // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null
188 if(channel != null) {
189 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
190 ctx.fireChannelActive();
194 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
195 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
197 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
198 if(!connectPromise.isDone()) {
199 connectPromise.setFailure(e);
202 disconnect(ctx, ctx.newPromise());
206 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
207 sshWriteAsyncHandler.write(ctx, msg, promise);
211 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
212 LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
213 this.connectPromise = promise;
215 if(negotiationFuture != null) {
217 negotiationFutureListener = new GenericFutureListener<Future<?>>() {
219 public void operationComplete(final Future<?> future) {
220 if (future.isSuccess()) {
221 connectPromise.setSuccess();
225 //complete connection promise with netconf negotiation future
226 negotiationFuture.addListener(negotiationFutureListener);
228 startSsh(ctx, remoteAddress);
232 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
233 disconnect(ctx, promise);
237 public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
238 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(), connectPromise);
240 // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
241 if(connectPromise.isSuccess()) {
242 ctx.fireChannelInactive();
245 if(sshWriteAsyncHandler != null) {
246 sshWriteAsyncHandler.close();
249 if(sshReadAsyncListener != null) {
250 sshReadAsyncListener.close();
253 //If connection promise is not already set, it means negotiation failed
254 //we must set connection promise to failure
255 if(!connectPromise.isDone()) {
256 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
259 //Remove listener from negotiation future, we don't want notifications
260 //from negotiation anymore
261 if(negotiationFuture != null) {
262 negotiationFuture.removeListener(negotiationFutureListener);
265 if(session!= null && !session.isClosed() && !session.isClosing()) {
266 session.close(false).addListener(new SshFutureListener<CloseFuture>() {
268 public void operationComplete(final CloseFuture future) {
269 if (future.isClosed() == false) {
277 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
278 // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
279 // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
281 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
282 super.disconnect(ctx, ctx.newPromise());
283 } catch (final Exception e) {
284 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
288 promise.setSuccess();
289 LOG.debug("SSH session closed on channel: {}", ctx.channel());