Merge "Revert "Add PasswordCredentialAuth interface""
[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.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;
21 import java.util.Map;
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;
33
34 /**
35  * Netty SSH handler class. Acts as interface between Netty and SSH library.
36  */
37 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
38     private static final Logger LOG = LoggerFactory.getLogger(AsyncSshHandler.class);
39
40     public static final String SUBSYSTEM = "netconf";
41
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;
45
46     public static final SshClient DEFAULT_CLIENT;
47     static {
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));
51
52         final SshClient c = SshClient.setUpDefaultClient();
53
54         c.setProperties(props);
55         // TODO make configurable, or somehow reuse netty threadpool
56         c.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
57         c.start();
58         DEFAULT_CLIENT = c;
59     }
60
61     private final AuthenticationHandler authenticationHandler;
62     private final SshClient sshClient;
63     private Future<?> negotiationFuture;
64
65     private AsyncSshHandlerReader sshReadAsyncListener;
66     private AsyncSshHandlerWriter sshWriteAsyncHandler;
67
68     private ClientChannel channel;
69     private ClientSession session;
70     private ChannelPromise connectPromise;
71     private GenericFutureListener negotiationFutureListener;
72
73     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient,
74             final Future<?> negotiationFuture) throws IOException {
75         this(authenticationHandler, sshClient);
76         this.negotiationFuture = negotiationFuture;
77     }
78
79     /**
80      *
81      * @param authenticationHandler
82      * @param sshClient started SshClient
83      * @throws IOException
84      */
85     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
86         this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
87         this.sshClient = Preconditions.checkNotNull(sshClient);
88     }
89
90     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
91         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
92     }
93
94     /**
95      *
96      * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful netconf
97      * negotiation.
98      *
99      * @param authenticationHandler
100      * @param negotiationFuture
101      * @return
102      * @throws IOException
103      */
104     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
105             final Future<?> negotiationFuture) throws IOException {
106         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT, negotiationFuture);
107     }
108
109     private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
110         LOG.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
111
112         final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
113         sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
114             @Override
115             public void operationComplete(final ConnectFuture future) {
116                 if (future.isConnected()) {
117                     handleSshSessionCreated(future, ctx);
118                 } else {
119                     handleSshSetupFailure(ctx, future.getException());
120                 }
121             }
122         });
123     }
124
125     private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
126         try {
127             LOG.trace("SSH session created on channel: {}", ctx.channel());
128
129             session = future.getSession();
130             final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
131             authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
132                 @Override
133                 public void operationComplete(final AuthFuture future) {
134                     if (future.isSuccess()) {
135                         handleSshAuthenticated(session, ctx);
136                     } else {
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);
142                     }
143                 }
144             });
145         } catch (final IOException e) {
146             handleSshSetupFailure(ctx, e);
147         }
148     }
149
150     private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
151         try {
152             LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
153
154             channel = session.createSubsystemChannel(SUBSYSTEM);
155             channel.setStreaming(ClientChannel.Streaming.Async);
156             channel.open().addListener(new SshFutureListener<OpenFuture>() {
157                 @Override
158                 public void operationComplete(final OpenFuture future) {
159                     if(future.isOpened()) {
160                         handleSshChanelOpened(ctx);
161                     } else {
162                         handleSshSetupFailure(ctx, future.getException());
163                     }
164                 }
165             });
166
167
168         } catch (final IOException e) {
169             handleSshSetupFailure(ctx, e);
170         }
171     }
172
173     private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
174         LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
175
176         if(negotiationFuture == null) {
177             connectPromise.setSuccess();
178         }
179
180         // TODO we should also read from error stream and at least log from that
181
182         sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() {
183             @Override
184             public void close() throws Exception {
185                 AsyncSshHandler.this.disconnect(ctx, ctx.newPromise());
186             }
187         }, new AsyncSshHandlerReader.ReadMsgHandler() {
188             @Override
189             public void onMessageRead(final ByteBuf msg) {
190                 ctx.fireChannelRead(msg);
191             }
192         }, channel.toString(), channel.getAsyncOut());
193
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();
198         }
199     }
200
201     private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
202         LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
203
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);
207         }
208
209         disconnect(ctx, ctx.newPromise());
210     }
211
212     @Override
213     public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
214         sshWriteAsyncHandler.write(ctx, msg, promise);
215     }
216
217     @Override
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;
221
222         if(negotiationFuture != null) {
223
224             negotiationFutureListener = new GenericFutureListener<Future<?>>() {
225                 @Override
226                 public void operationComplete(final Future<?> future) {
227                     if (future.isSuccess()) {
228                         connectPromise.setSuccess();
229                     }
230                 }
231             };
232             //complete connection promise with netconf negotiation future
233             negotiationFuture.addListener(negotiationFutureListener);
234         }
235         startSsh(ctx, remoteAddress);
236     }
237
238     @Override
239     public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
240         disconnect(ctx, promise);
241     }
242
243     @Override
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);
246
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();
250         }
251
252         if(sshWriteAsyncHandler != null) {
253             sshWriteAsyncHandler.close();
254         }
255
256         if(sshReadAsyncListener != null) {
257             sshReadAsyncListener.close();
258         }
259
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"));
264         }
265
266         //Remove listener from negotiation future, we don't want notifications
267         //from negotiation anymore
268         if(negotiationFuture != null) {
269             negotiationFuture.removeListener(negotiationFutureListener);
270         }
271
272         if(session!= null && !session.isClosed() && !session.isClosing()) {
273             session.close(false).addListener(new SshFutureListener<CloseFuture>() {
274                 @Override
275                 public void operationComplete(final CloseFuture future) {
276                     if (future.isClosed() == false) {
277                         session.close(true);
278                     }
279                     session = null;
280                 }
281             });
282         }
283
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
287         try {
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);
292         }
293
294         channel = null;
295         promise.setSuccess();
296         LOG.debug("SSH session closed on channel: {}", ctx.channel());
297     }
298
299 }