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 java.util.HashMap;
22 import org.apache.sshd.ClientChannel;
23 import org.apache.sshd.ClientSession;
24 import org.apache.sshd.SshClient;
25 import org.apache.sshd.client.future.AuthFuture;
26 import org.apache.sshd.client.future.ConnectFuture;
27 import org.apache.sshd.client.future.OpenFuture;
28 import org.apache.sshd.common.future.CloseFuture;
29 import org.apache.sshd.common.future.SshFutureListener;
30 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
35 * Netty SSH handler class. Acts as interface between Netty and SSH library.
37 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
38 private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
40 public static final String SUBSYSTEM = "netconf";
42 public static final int SSH_DEFAULT_NIO_WORKERS = 8;
43 // Disable default timeouts from mina sshd
44 private static final long DEFAULT_TIMEOUT = -1L;
46 public static final SshClient DEFAULT_CLIENT;
48 final Map<String, String> props = new HashMap<>();
49 props.put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
50 props.put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
52 final SshClient c = SshClient.setUpDefaultClient();
54 c.setProperties(props);
55 // TODO make configurable, or somehow reuse netty threadpool
56 c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
61 private final AuthenticationHandler authenticationHandler;
62 private final SshClient sshClient;
63 private Future<?> negotiationFuture;
65 private AsyncSshHandlerReader sshReadAsyncListener;
66 private AsyncSshHandlerWriter sshWriteAsyncHandler;
68 private ClientChannel channel;
69 private ClientSession session;
70 private ChannelPromise connectPromise;
71 private GenericFutureListener negotiationFutureListener;
73 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient,
74 final Future<?> negotiationFuture) throws IOException {
75 this(authenticationHandler, sshClient);
76 this.negotiationFuture = negotiationFuture;
81 * @param authenticationHandler
82 * @param sshClient started SshClient
85 public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
86 this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
87 this.sshClient = Preconditions.checkNotNull(sshClient);
92 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
93 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
98 * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful netconf
101 * @param authenticationHandler
102 * @param negotiationFuture
104 * @throws IOException
106 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
107 final Future<?> negotiationFuture) throws IOException {
108 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture);
111 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
112 LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
114 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
115 sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
117 public void operationComplete(final ConnectFuture future) {
118 if (future.isConnected()) {
119 handleSshSessionCreated(future, ctx);
121 handleSshSetupFailure(ctx, future.getException());
127 private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
129 LOG.trace("SSH session created on channel: {}", ctx.channel());
131 session = future.getSession();
132 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
133 authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
135 public void operationComplete(final AuthFuture future) {
136 if (future.isSuccess()) {
137 handleSshAuthenticated(session, ctx);
139 // Exception does not have to be set in the future, add simple exception in such case
140 final Throwable exception = future.getException() == null ?
141 new IllegalStateException("Authentication failed") :
142 future.getException();
143 handleSshSetupFailure(ctx, exception);
147 } catch (final IOException e) {
148 handleSshSetupFailure(ctx, e);
152 private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
154 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
156 channel = session.createSubsystemChannel(SUBSYSTEM);
157 channel.setStreaming(ClientChannel.Streaming.Async);
158 channel.open().addListener(new SshFutureListener<OpenFuture>() {
160 public void operationComplete(final OpenFuture future) {
161 if(future.isOpened()) {
162 handleSshChanelOpened(ctx);
164 handleSshSetupFailure(ctx, future.getException());
170 } catch (final IOException e) {
171 handleSshSetupFailure(ctx, e);
175 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
176 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
178 if(negotiationFuture == null) {
179 connectPromise.setSuccess();
182 // TODO we should also read from error stream and at least log from that
184 sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() {
186 public void close() throws Exception {
187 AsyncSshHandler.this.disconnect(ctx, ctx.newPromise());
189 }, new AsyncSshHandlerReader.ReadMsgHandler() {
191 public void onMessageRead(final ByteBuf msg) {
192 ctx.fireChannelRead(msg);
194 }, channel.toString(), channel.getAsyncOut());
196 // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null
197 if(channel != null) {
198 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
199 ctx.fireChannelActive();
203 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
204 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
206 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
207 if(!connectPromise.isDone()) {
208 connectPromise.setFailure(e);
211 disconnect(ctx, ctx.newPromise());
215 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
216 sshWriteAsyncHandler.write(ctx, msg, promise);
220 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
221 LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
222 this.connectPromise = promise;
224 if(negotiationFuture != null) {
226 negotiationFutureListener = new GenericFutureListener<Future<?>>() {
228 public void operationComplete(final Future<?> future) {
229 if (future.isSuccess()) {
230 connectPromise.setSuccess();
234 //complete connection promise with netconf negotiation future
235 negotiationFuture.addListener(negotiationFutureListener);
237 startSsh(ctx, remoteAddress);
241 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
242 disconnect(ctx, promise);
246 public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
247 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(), connectPromise);
249 // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
250 if(connectPromise.isSuccess()) {
251 ctx.fireChannelInactive();
254 if(sshWriteAsyncHandler != null) {
255 sshWriteAsyncHandler.close();
258 if(sshReadAsyncListener != null) {
259 sshReadAsyncListener.close();
262 //If connection promise is not already set, it means negotiation failed
263 //we must set connection promise to failure
264 if(!connectPromise.isDone()) {
265 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
268 //Remove listener from negotiation future, we don't want notifications
269 //from negotiation anymore
270 if(negotiationFuture != null) {
271 negotiationFuture.removeListener(negotiationFutureListener);
274 if(session!= null && !session.isClosed() && !session.isClosing()) {
275 session.close(false).addListener(new SshFutureListener<CloseFuture>() {
277 public void operationComplete(final CloseFuture future) {
278 if (future.isClosed() == false) {
286 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
287 // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
288 // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
290 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
291 super.disconnect(ctx, ctx.newPromise());
292 } catch (final Exception e) {
293 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
297 promise.setSuccess();
298 LOG.debug("SSH session closed on channel: {}", ctx.channel());