149ccf16f9910dfbf38a866f5c0d89fbda50c7b6
[netconf.git] / netconf / netconf-netty-util / src / main / java / org / opendaylight / netconf / nettyutil / handler / ssh / client / AsyncSshHandler.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netconf.nettyutil.handler.ssh.client;
10
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;
27
28 /**
29  * Netty SSH handler class. Acts as interface between Netty and SSH library.
30  */
31 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
32     private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
33
34     public static final String SUBSYSTEM = "netconf";
35
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;
39
40     public static final SshClient DEFAULT_CLIENT;
41
42     static {
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));
46
47         // TODO make configurable, or somehow reuse netty threadpool
48         c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
49         c.start();
50         DEFAULT_CLIENT = c;
51     }
52
53     private final AuthenticationHandler authenticationHandler;
54     private final SshClient sshClient;
55     private Future<?> negotiationFuture;
56
57     private AsyncSshHandlerReader sshReadAsyncListener;
58     private AsyncSshHandlerWriter sshWriteAsyncHandler;
59
60     private ClientChannel channel;
61     private ClientSession session;
62     private ChannelPromise connectPromise;
63     private GenericFutureListener negotiationFutureListener;
64
65     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient,
66             final Future<?> negotiationFuture) {
67         this(authenticationHandler, sshClient);
68         this.negotiationFuture = negotiationFuture;
69     }
70
71     /**
72      * Constructor of {@code AsyncSshHandler}.
73      *
74      * @param authenticationHandler authentication handler
75      * @param sshClient             started SshClient
76      */
77     public AsyncSshHandler(final AuthenticationHandler authenticationHandler,
78                            final SshClient sshClient) {
79         this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
80         this.sshClient = Preconditions.checkNotNull(sshClient);
81     }
82
83     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
84         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
85     }
86
87     /**
88      * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
89      * netconf negotiation.
90      *
91      * @param authenticationHandler authentication handler
92      * @param negotiationFuture     negotiation future
93      * @return                      {@code AsyncSshHandler}
94      */
95     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
96             final Future<?> negotiationFuture) {
97         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture);
98     }
99
100     private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) throws IOException {
101         LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
102
103         final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
104         sshConnectionFuture.addListener(future -> {
105             if (future.isConnected()) {
106                 handleSshSessionCreated(future, ctx);
107             } else {
108                 handleSshSetupFailure(ctx, future.getException());
109             }
110         });
111     }
112
113     private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
114         try {
115             LOG.trace("SSH session created on channel: {}", ctx.channel());
116
117             session = future.getSession();
118             final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
119             final ClientSession localSession = session;
120             authenticateFuture.addListener(future1 -> {
121                 if (future1.isSuccess()) {
122                     handleSshAuthenticated(localSession, ctx);
123                 } else {
124                     // Exception does not have to be set in the future, add simple exception in such case
125                     final Throwable exception = future1.getException() == null
126                             ? new IllegalStateException("Authentication failed") : future1.getException();
127                     handleSshSetupFailure(ctx, exception);
128                 }
129             });
130         } catch (final IOException e) {
131             handleSshSetupFailure(ctx, e);
132         }
133     }
134
135     private synchronized void handleSshAuthenticated(final ClientSession newSession, final ChannelHandlerContext ctx) {
136         try {
137             LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
138                     newSession.getServerVersion());
139
140             channel = newSession.createSubsystemChannel(SUBSYSTEM);
141             channel.setStreaming(ClientChannel.Streaming.Async);
142             channel.open().addListener(future -> {
143                 if (future.isOpened()) {
144                     handleSshChanelOpened(ctx);
145                 } else {
146                     handleSshSetupFailure(ctx, future.getException());
147                 }
148             });
149
150
151         } catch (final IOException e) {
152             handleSshSetupFailure(ctx, e);
153         }
154     }
155
156     private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
157         LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
158
159         if (negotiationFuture == null) {
160             connectPromise.setSuccess();
161         }
162
163         // TODO we should also read from error stream and at least log from that
164
165         ClientChannel localChannel = channel;
166         sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
167             ctx::fireChannelRead, localChannel.toString(), localChannel.getAsyncOut());
168
169         // if readAsyncListener receives immediate close,
170         // it will close this handler and closing this handler sets channel variable to null
171         if (channel != null) {
172             sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
173             ctx.fireChannelActive();
174         }
175     }
176
177     private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
178         LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
179
180         // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
181         if (!connectPromise.isDone()) {
182             connectPromise.setFailure(error);
183         }
184
185         disconnect(ctx, ctx.newPromise());
186     }
187
188     @Override
189     public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
190         sshWriteAsyncHandler.write(ctx, msg, promise);
191     }
192
193     @Override
194     public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
195                                      final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
196         LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
197         this.connectPromise = promise;
198
199         if (negotiationFuture != null) {
200             negotiationFutureListener = future -> {
201                 if (future.isSuccess()) {
202                     promise.setSuccess();
203                 }
204             };
205             //complete connection promise with netconf negotiation future
206             negotiationFuture.addListener(negotiationFutureListener);
207         }
208         startSsh(ctx, remoteAddress);
209     }
210
211     @Override
212     public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
213         disconnect(ctx, promise);
214     }
215
216     @SuppressWarnings("checkstyle:IllegalCatch")
217     @Override
218     public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
219         LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
220                 ctx.channel(),connectPromise);
221
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();
226         }
227
228         if (sshWriteAsyncHandler != null) {
229             sshWriteAsyncHandler.close();
230         }
231
232         if (sshReadAsyncListener != null) {
233             sshReadAsyncListener.close();
234         }
235
236         //If connection promise is not already set, it means negotiation failed
237         //we must set connection promise to failure
238         if (!connectPromise.isDone()) {
239             connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
240         }
241
242         //Remove listener from negotiation future, we don't want notifications
243         //from negotiation anymore
244         if (negotiationFuture != null) {
245             negotiationFuture.removeListener(negotiationFutureListener);
246         }
247
248         if (session != null && !session.isClosed() && !session.isClosing()) {
249             session.close(false).addListener(future -> {
250                 synchronized (this) {
251                     if (!future.isClosed()) {
252                         session.close(true);
253                     }
254                     session = null;
255                 }
256             });
257         }
258
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
264         try {
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);
269         }
270
271         channel = null;
272         promise.setSuccess();
273         LOG.debug("SSH session closed on channel: {}", ctx.channel());
274     }
275
276 }