5132df6e7145f8a5ca9c689a17e6505c2c027420
[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 package org.opendaylight.netconf.nettyutil.handler.ssh.client;
9
10 import static java.util.Objects.requireNonNull;
11
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 java.util.concurrent.TimeUnit;
20 import java.util.concurrent.atomic.AtomicBoolean;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
23 import org.opendaylight.netconf.shaded.sshd.client.SshClient;
24 import org.opendaylight.netconf.shaded.sshd.client.channel.ClientChannel;
25 import org.opendaylight.netconf.shaded.sshd.client.future.AuthFuture;
26 import org.opendaylight.netconf.shaded.sshd.client.future.ConnectFuture;
27 import org.opendaylight.netconf.shaded.sshd.client.session.ClientSession;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
30
31 /**
32  * Netty SSH handler class. Acts as interface between Netty and SSH library.
33  */
34 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
35     private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
36
37     public static final String SUBSYSTEM = "netconf";
38
39     public static final int SSH_DEFAULT_NIO_WORKERS = 8;
40     // Disable default timeouts from mina sshd
41     private static final long DEFAULT_TIMEOUT = -1L;
42
43     public static final SshClient DEFAULT_CLIENT;
44
45     static {
46         final SshClient c = SshClient.setUpDefaultClient();
47         c.getProperties().put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
48         c.getProperties().put(SshClient.IDLE_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
49
50         // TODO make configurable, or somehow reuse netty threadpool
51         c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
52         c.start();
53         DEFAULT_CLIENT = c;
54     }
55
56     private final AtomicBoolean isDisconnected = new AtomicBoolean();
57     private final AuthenticationHandler authenticationHandler;
58     private final SshClient sshClient;
59     private final Future<?> negotiationFuture;
60
61     private AsyncSshHandlerReader sshReadAsyncListener;
62     private AsyncSshHandlerWriter sshWriteAsyncHandler;
63
64     private ClientChannel channel;
65     private ClientSession session;
66     private ChannelPromise connectPromise;
67     private GenericFutureListener negotiationFutureListener;
68
69     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient,
70             final Future<?> negotiationFuture) {
71         this.authenticationHandler = requireNonNull(authenticationHandler);
72         this.sshClient = requireNonNull(sshClient);
73         this.negotiationFuture = negotiationFuture;
74     }
75
76     /**
77      * Constructor of {@code AsyncSshHandler}.
78      *
79      * @param authenticationHandler authentication handler
80      * @param sshClient             started SshClient
81      */
82     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) {
83         this(authenticationHandler, sshClient, null);
84     }
85
86     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) {
87         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
88     }
89
90     /**
91      * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
92      * netconf negotiation.
93      *
94      * @param authenticationHandler authentication handler
95      * @param negotiationFuture     negotiation future
96      * @return                      {@code AsyncSshHandler}
97      */
98     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
99             final Future<?> negotiationFuture, @Nullable final SshClient sshClient) {
100         return new AsyncSshHandler(authenticationHandler, sshClient != null ? sshClient : DEFAULT_CLIENT,
101                 negotiationFuture);
102     }
103
104     private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) throws IOException {
105         LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
106
107         final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address)
108                .verify(ctx.channel().config().getConnectTimeoutMillis(), TimeUnit.MILLISECONDS);
109         sshConnectionFuture.addListener(future -> {
110             if (future.isConnected()) {
111                 handleSshSessionCreated(future, ctx);
112             } else {
113                 handleSshSetupFailure(ctx, future.getException());
114             }
115         });
116     }
117
118     private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
119         try {
120             LOG.trace("SSH session created on channel: {}", ctx.channel());
121
122             session = future.getSession();
123             final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
124             final ClientSession localSession = session;
125             authenticateFuture.addListener(future1 -> {
126                 if (future1.isSuccess()) {
127                     handleSshAuthenticated(localSession, ctx);
128                 } else {
129                     handleSshSetupFailure(ctx, new AuthenticationFailedException("Authentication failed",
130                         future1.getException()));
131                 }
132             });
133         } catch (final IOException e) {
134             handleSshSetupFailure(ctx, e);
135         }
136     }
137
138     private synchronized void handleSshAuthenticated(final ClientSession newSession, final ChannelHandlerContext ctx) {
139         try {
140             LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
141                     newSession.getServerVersion());
142
143             channel = newSession.createSubsystemChannel(SUBSYSTEM);
144             channel.setStreaming(ClientChannel.Streaming.Async);
145             channel.open().addListener(future -> {
146                 if (future.isOpened()) {
147                     handleSshChanelOpened(ctx);
148                 } else {
149                     handleSshSetupFailure(ctx, future.getException());
150                 }
151             });
152
153
154         } catch (final IOException e) {
155             handleSshSetupFailure(ctx, e);
156         }
157     }
158
159     private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
160         LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
161
162         if (negotiationFuture == null) {
163             connectPromise.setSuccess();
164         }
165
166         // TODO we should also read from error stream and at least log from that
167
168         ClientChannel localChannel = channel;
169         sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
170             ctx::fireChannelRead, localChannel.toString(), localChannel.getAsyncOut());
171
172         // if readAsyncListener receives immediate close,
173         // it will close this handler and closing this handler sets channel variable to null
174         if (channel != null) {
175             sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
176             ctx.fireChannelActive();
177         }
178     }
179
180     private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
181         LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
182
183         // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
184         if (!connectPromise.isDone()) {
185             connectPromise.setFailure(error);
186         }
187
188         disconnect(ctx, ctx.newPromise());
189     }
190
191     @Override
192     public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
193         sshWriteAsyncHandler.write(ctx, msg, promise);
194     }
195
196     @Override
197     public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
198                                      final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
199         LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
200         this.connectPromise = promise;
201
202         if (negotiationFuture != null) {
203             negotiationFutureListener = future -> {
204                 if (future.isSuccess()) {
205                     promise.setSuccess();
206                 }
207             };
208             //complete connection promise with netconf negotiation future
209             negotiationFuture.addListener(negotiationFutureListener);
210         }
211         startSsh(ctx, remoteAddress);
212     }
213
214     @Override
215     public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) {
216         disconnect(ctx, promise);
217     }
218
219     @Override
220     public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
221         if (isDisconnected.compareAndSet(false, true)) {
222             safelyDisconnect(ctx, promise);
223         }
224     }
225
226     @SuppressWarnings("checkstyle:IllegalCatch")
227     private synchronized void safelyDisconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
228         LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
229                 ctx.channel(), connectPromise);
230
231         // If we have already succeeded and the session was dropped after,
232         // we need to fire inactive to notify reconnect logic
233         if (connectPromise.isSuccess()) {
234             ctx.fireChannelInactive();
235         }
236
237         if (sshWriteAsyncHandler != null) {
238             sshWriteAsyncHandler.close();
239         }
240
241         if (sshReadAsyncListener != null) {
242             sshReadAsyncListener.close();
243         }
244
245         //If connection promise is not already set, it means negotiation failed
246         //we must set connection promise to failure
247         if (!connectPromise.isDone()) {
248             connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
249         }
250
251         //Remove listener from negotiation future, we don't want notifications
252         //from negotiation anymore
253         if (negotiationFuture != null) {
254             negotiationFuture.removeListener(negotiationFutureListener);
255         }
256
257         if (session != null && !session.isClosed() && !session.isClosing()) {
258             session.close(false).addListener(future -> {
259                 synchronized (this) {
260                     if (!future.isClosed()) {
261                         session.close(true);
262                     }
263                     session = null;
264                 }
265             });
266         }
267
268         // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
269         // to cleanup its resources e.g. Socket that it tries to open in its constructor
270         // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
271         // TODO better solution would be to implement custom ChannelFactory + Channel
272         // that will use mina SSH lib internally: port this to custom channel implementation
273         try {
274             // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
275             super.disconnect(ctx, ctx.newPromise());
276         } catch (final Exception e) {
277             LOG.warn("Unable to cleanup all resources for channel: {}. Ignoring.", ctx.channel(), e);
278         }
279
280         channel = null;
281         promise.setSuccess();
282         LOG.debug("SSH session closed on channel: {}", ctx.channel());
283     }
284 }