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