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);
90 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
91 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
96 * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful netconf
99 * @param authenticationHandler
100 * @param negotiationFuture
102 * @throws IOException
104 public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
105 final Future<?> negotiationFuture) throws IOException {
106 return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture);
109 private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
110 LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
112 final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
113 sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
115 public void operationComplete(final ConnectFuture future) {
116 if (future.isConnected()) {
117 handleSshSessionCreated(future, ctx);
119 handleSshSetupFailure(ctx, future.getException());
125 private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
127 LOG.trace("SSH session created on channel: {}", ctx.channel());
129 session = future.getSession();
130 final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
131 authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
133 public void operationComplete(final AuthFuture future) {
134 if (future.isSuccess()) {
135 handleSshAuthenticated(session, ctx);
137 // Exception does not have to be set in the future, add simple exception in such case
138 final Throwable exception = future.getException() == null ?
139 new IllegalStateException("Authentication failed") :
140 future.getException();
141 handleSshSetupFailure(ctx, exception);
145 } catch (final IOException e) {
146 handleSshSetupFailure(ctx, e);
150 private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
152 LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
154 channel = session.createSubsystemChannel(SUBSYSTEM);
155 channel.setStreaming(ClientChannel.Streaming.Async);
156 channel.open().addListener(new SshFutureListener<OpenFuture>() {
158 public void operationComplete(final OpenFuture future) {
159 if(future.isOpened()) {
160 handleSshChanelOpened(ctx);
162 handleSshSetupFailure(ctx, future.getException());
168 } catch (final IOException e) {
169 handleSshSetupFailure(ctx, e);
173 private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
174 LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
176 if(negotiationFuture == null) {
177 connectPromise.setSuccess();
180 // TODO we should also read from error stream and at least log from that
182 sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() {
184 public void close() throws Exception {
185 AsyncSshHandler.this.disconnect(ctx, ctx.newPromise());
187 }, new AsyncSshHandlerReader.ReadMsgHandler() {
189 public void onMessageRead(final ByteBuf msg) {
190 ctx.fireChannelRead(msg);
192 }, channel.toString(), channel.getAsyncOut());
194 // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null
195 if(channel != null) {
196 sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
197 ctx.fireChannelActive();
201 private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
202 LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
204 // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
205 if(!connectPromise.isDone()) {
206 connectPromise.setFailure(e);
209 disconnect(ctx, ctx.newPromise());
213 public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
214 sshWriteAsyncHandler.write(ctx, msg, promise);
218 public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
219 LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
220 this.connectPromise = promise;
222 if(negotiationFuture != null) {
224 negotiationFutureListener = new GenericFutureListener<Future<?>>() {
226 public void operationComplete(final Future<?> future) {
227 if (future.isSuccess()) {
228 connectPromise.setSuccess();
232 //complete connection promise with netconf negotiation future
233 negotiationFuture.addListener(negotiationFutureListener);
235 startSsh(ctx, remoteAddress);
239 public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
240 disconnect(ctx, promise);
244 public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
245 LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(), connectPromise);
247 // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
248 if(connectPromise.isSuccess()) {
249 ctx.fireChannelInactive();
252 if(sshWriteAsyncHandler != null) {
253 sshWriteAsyncHandler.close();
256 if(sshReadAsyncListener != null) {
257 sshReadAsyncListener.close();
260 //If connection promise is not already set, it means negotiation failed
261 //we must set connection promise to failure
262 if(!connectPromise.isDone()) {
263 connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
266 //Remove listener from negotiation future, we don't want notifications
267 //from negotiation anymore
268 if(negotiationFuture != null) {
269 negotiationFuture.removeListener(negotiationFutureListener);
272 if(session!= null && !session.isClosed() && !session.isClosing()) {
273 session.close(false).addListener(new SshFutureListener<CloseFuture>() {
275 public void operationComplete(final CloseFuture future) {
276 if (future.isClosed() == false) {
284 // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
285 // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
286 // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
288 // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
289 super.disconnect(ctx, ctx.newPromise());
290 } catch (final Exception e) {
291 LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
295 promise.setSuccess();
296 LOG.debug("SSH session closed on channel: {}", ctx.channel());