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