BUG-1612 Implement mina ssh netconf server endpoint
[controller.git] / opendaylight / netconf / netconf-netty-util / src / main / java / org / opendaylight / controller / 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.controller.netconf.nettyutil.handler.ssh.client;
10
11 import java.io.IOException;
12 import java.net.SocketAddress;
13
14 import org.apache.sshd.ClientChannel;
15 import org.apache.sshd.ClientSession;
16 import org.apache.sshd.SshClient;
17 import org.apache.sshd.client.future.AuthFuture;
18 import org.apache.sshd.client.future.ConnectFuture;
19 import org.apache.sshd.client.future.OpenFuture;
20 import org.apache.sshd.common.future.CloseFuture;
21 import org.apache.sshd.common.future.SshFutureListener;
22 import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 import com.google.common.base.Preconditions;
27
28 import io.netty.buffer.ByteBuf;
29 import io.netty.channel.ChannelHandlerContext;
30 import io.netty.channel.ChannelOutboundHandlerAdapter;
31 import io.netty.channel.ChannelPromise;
32
33 /**
34  * Netty SSH handler class. Acts as interface between Netty and SSH library.
35  */
36 public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
37
38     private static final Logger logger = LoggerFactory.getLogger(AsyncSshHandler.class);
39     public static final String SUBSYSTEM = "netconf";
40
41     public static final SshClient DEFAULT_CLIENT = SshClient.setUpDefaultClient();
42
43     public static final int SSH_DEFAULT_NIO_WORKERS = 8;
44
45     static {
46         // TODO make configurable, or somehow reuse netty threadpool
47         DEFAULT_CLIENT.setNioWorkers(SSH_DEFAULT_NIO_WORKERS);
48         DEFAULT_CLIENT.start();
49     }
50
51     private final AuthenticationHandler authenticationHandler;
52     private final SshClient sshClient;
53
54     private AsyncSshHandlerReader sshReadAsyncListener;
55     private AsyncSshHandlerWriter sshWriteAsyncHandler;
56
57     private ClientChannel channel;
58     private ClientSession session;
59     private ChannelPromise connectPromise;
60
61
62     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
63         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
64     }
65
66     /**
67      *
68      * @param authenticationHandler
69      * @param sshClient started SshClient
70      * @throws IOException
71      */
72     public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
73         this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
74         this.sshClient = Preconditions.checkNotNull(sshClient);
75         // Start just in case
76         sshClient.start();
77     }
78
79     private void startSsh(final ChannelHandlerContext ctx, final SocketAddress address) {
80         logger.debug("Starting SSH to {} on channel: {}", address, ctx.channel());
81
82         final ConnectFuture sshConnectionFuture = sshClient.connect(authenticationHandler.getUsername(), address);
83         sshConnectionFuture.addListener(new SshFutureListener<ConnectFuture>() {
84             @Override
85             public void operationComplete(final ConnectFuture future) {
86                 if (future.isConnected()) {
87                     handleSshSessionCreated(future, ctx);
88                 } else {
89                     handleSshSetupFailure(ctx, future.getException());
90                 }
91             }
92         });
93     }
94
95     private synchronized void handleSshSessionCreated(final ConnectFuture future, final ChannelHandlerContext ctx) {
96         try {
97             logger.trace("SSH session created on channel: {}", ctx.channel());
98
99             session = future.getSession();
100             final AuthFuture authenticateFuture = authenticationHandler.authenticate(session);
101             authenticateFuture.addListener(new SshFutureListener<AuthFuture>() {
102                 @Override
103                 public void operationComplete(final AuthFuture future) {
104                     if (future.isSuccess()) {
105                         handleSshAuthenticated(session, ctx);
106                     } else {
107                         handleSshSetupFailure(ctx, future.getException());
108                     }
109                 }
110             });
111         } catch (final IOException e) {
112             handleSshSetupFailure(ctx, e);
113         }
114     }
115
116     private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
117         try {
118             logger.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
119
120             channel = session.createSubsystemChannel(SUBSYSTEM);
121             channel.setStreaming(ClientChannel.Streaming.Async);
122             channel.open().addListener(new SshFutureListener<OpenFuture>() {
123                 @Override
124                 public void operationComplete(final OpenFuture future) {
125                     if(future.isOpened()) {
126                         handleSshChanelOpened(ctx);
127                     } else {
128                         handleSshSetupFailure(ctx, future.getException());
129                     }
130                 }
131             });
132
133
134         } catch (final IOException e) {
135             handleSshSetupFailure(ctx, e);
136         }
137     }
138
139     private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
140         logger.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
141
142         connectPromise.setSuccess();
143         connectPromise = null;
144
145         // TODO we should also read from error stream and at least log from that
146
147         sshReadAsyncListener = new AsyncSshHandlerReader(new AutoCloseable() {
148             @Override
149             public void close() throws Exception {
150                 AsyncSshHandler.this.disconnect(ctx, ctx.newPromise());
151             }
152         }, new AsyncSshHandlerReader.ReadMsgHandler() {
153             @Override
154             public void onMessageRead(final ByteBuf msg) {
155                 ctx.fireChannelRead(msg);
156             }
157         }, channel.toString(), channel.getAsyncOut());
158
159         // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null
160         if(channel != null) {
161             sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
162             ctx.fireChannelActive();
163         }
164     }
165
166     private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
167         logger.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
168         connectPromise.setFailure(e);
169         connectPromise = null;
170         throw new IllegalStateException("Unable to setup SSH connection on channel: " + ctx.channel(), e);
171     }
172
173     @Override
174     public synchronized void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise) {
175         sshWriteAsyncHandler.write(ctx, msg, promise);
176     }
177
178     @Override
179     public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
180         this.connectPromise = promise;
181         startSsh(ctx, remoteAddress);
182     }
183
184     @Override
185     public void close(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
186         disconnect(ctx, promise);
187     }
188
189     @Override
190     public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
191         if(sshReadAsyncListener != null) {
192             sshReadAsyncListener.close();
193         }
194
195         if(sshWriteAsyncHandler != null) {
196             sshWriteAsyncHandler.close();
197         }
198
199         if(session!= null && !session.isClosed() && !session.isClosing()) {
200             session.close(false).addListener(new SshFutureListener<CloseFuture>() {
201                 @Override
202                 public void operationComplete(final CloseFuture future) {
203                     if (future.isClosed() == false) {
204                         session.close(true);
205                     }
206                     session = null;
207                 }
208             });
209         }
210
211         channel = null;
212         promise.setSuccess();
213
214         logger.debug("SSH session closed on channel: {}", ctx.channel());
215         ctx.fireChannelInactive();
216     }
217
218 }