You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mina.apache.org by lg...@apache.org on 2015/08/25 06:38:16 UTC
[2/4] mina-sshd git commit: [SSHD-555] Add ChannelListener support
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
index dbe8b2b..36cbbe3 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java
@@ -36,11 +36,15 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import java.util.Set;
+import java.util.TreeMap;
+import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
import org.apache.sshd.client.auth.UserAuth;
import org.apache.sshd.client.auth.UserAuthKeyboardInteractive;
@@ -54,15 +58,22 @@ import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.future.OpenFuture;
import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.client.subsystem.SubsystemClient;
+import org.apache.sshd.client.subsystem.sftp.SftpClient;
+import org.apache.sshd.common.Factory;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.FactoryManagerUtils;
import org.apache.sshd.common.NamedFactory;
+import org.apache.sshd.common.NamedResource;
import org.apache.sshd.common.RuntimeSshException;
import org.apache.sshd.common.Service;
import org.apache.sshd.common.SshConstants;
import org.apache.sshd.common.SshException;
import org.apache.sshd.common.channel.AbstractChannel;
import org.apache.sshd.common.channel.Channel;
+import org.apache.sshd.common.channel.ChannelListener;
+import org.apache.sshd.common.channel.ChannelListenerManager;
+import org.apache.sshd.common.channel.TestChannelListener;
import org.apache.sshd.common.cipher.BuiltinCiphers;
import org.apache.sshd.common.future.CloseFuture;
import org.apache.sshd.common.future.SshFutureListener;
@@ -75,9 +86,11 @@ import org.apache.sshd.common.keyprovider.KeyPairProvider;
import org.apache.sshd.common.session.AbstractSession;
import org.apache.sshd.common.session.ConnectionService;
import org.apache.sshd.common.session.Session;
+import org.apache.sshd.common.session.SessionListener;
import org.apache.sshd.common.subsystem.sftp.SftpConstants;
import org.apache.sshd.common.util.GenericUtils;
import org.apache.sshd.common.util.Transformer;
+import org.apache.sshd.common.util.ValidateUtils;
import org.apache.sshd.common.util.buffer.Buffer;
import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
import org.apache.sshd.common.util.io.NoCloseOutputStream;
@@ -95,6 +108,7 @@ import org.apache.sshd.server.session.ServerConnectionServiceFactory;
import org.apache.sshd.server.session.ServerSession;
import org.apache.sshd.server.session.ServerUserAuthService;
import org.apache.sshd.server.session.ServerUserAuthServiceFactory;
+import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory;
import org.apache.sshd.util.AsyncEchoShellFactory;
import org.apache.sshd.util.BaseTestSupport;
import org.apache.sshd.util.BogusPasswordAuthenticator;
@@ -106,6 +120,8 @@ import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* TODO Add javadoc
@@ -121,6 +137,28 @@ public class ClientTest extends BaseTestSupport {
private CountDownLatch authLatch;
private CountDownLatch channelLatch;
+ private final AtomicReference<ClientSession> clientSessionHolder = new AtomicReference<ClientSession>(null);
+ @SuppressWarnings("synthetic-access")
+ private final SessionListener clientSessionListener = new SessionListener() {
+ @Override
+ public void sessionCreated(Session session) {
+ assertObjectInstanceOf("Non client session creation notification", ClientSession.class, session);
+ assertNull("Multiple creation notifications", clientSessionHolder.getAndSet((ClientSession) session));
+ }
+
+ @Override
+ public void sessionEvent(Session session, Event event) {
+ assertObjectInstanceOf("Non client session event notification: " + event, ClientSession.class, session);
+ assertSame("Mismatched client session event instance: " + event, clientSessionHolder.get(), session);
+ }
+
+ @Override
+ public void sessionClosed(Session session) {
+ assertObjectInstanceOf("Non client session closure notification", ClientSession.class, session);
+ assertSame("Mismatched client session closure instance", clientSessionHolder.getAndSet(null), session);
+ }
+ };
+
public ClientTest() {
super();
}
@@ -185,6 +223,8 @@ public class ClientTest extends BaseTestSupport {
port = sshd.getPort();
client = SshClient.setUpDefaultClient();
+ clientSessionHolder.set(null); // just making sure
+ client.addSessionListener(clientSessionListener);
}
@After
@@ -195,6 +235,167 @@ public class ClientTest extends BaseTestSupport {
if (client != null) {
client.stop();
}
+ clientSessionHolder.set(null); // just making sure
+ }
+
+ @Test
+ public void testClientStillActiveIfListenerExceptions() throws Exception {
+ final Map<String, Integer> eventsMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+ final Collection<String> failuresSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
+ final Logger log = LoggerFactory.getLogger(getClass());
+ client.addChannelListener(new ChannelListener() {
+ @Override
+ public void channelOpenSuccess(Channel channel) {
+ handleChannelEvent("OpenSuccess", channel);
+ }
+
+ @Override
+ public void channelOpenFailure(Channel channel, Throwable reason) {
+ assertObjectInstanceOf("Mismatched failure reason type", ChannelFailureException.class, reason);
+
+ String name = ((NamedResource) reason).getName();
+ synchronized(failuresSet) {
+ assertTrue("Re-signalled failure location: " + name, failuresSet.add(name));
+ }
+ }
+
+ @Override
+ public void channelInitialized(Channel channel) {
+ handleChannelEvent("Initialized", channel);
+ }
+
+ @Override
+ public void channelClosed(Channel channel) {
+ handleChannelEvent("Closed", channel);
+ }
+
+ private void handleChannelEvent(String name, Channel channel) {
+ int id = channel.getId();
+ synchronized(eventsMap) {
+ if (eventsMap.put(name, id) != null) {
+ return; // already generated an exception for this event
+ }
+ }
+
+ log.info("handleChannelEvent({})[{}]", name, id);
+ throw new ChannelFailureException(name);
+ }
+ });
+
+ client.start();
+
+ try (ClientSession session = createTestClientSession();
+ PipedOutputStream pipedIn = new PipedOutputStream();
+ InputStream inPipe = new PipedInputStream(pipedIn);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream err = new ByteArrayOutputStream()) {
+ // we expect failures either on channel init or open - the one on close is ignored...
+ for (int retryCount = 0; retryCount <= 3; retryCount++) {
+ try {
+ try(ChannelShell channel = session.createShellChannel()) {
+ channel.setIn(inPipe);
+ channel.setOut(out);
+ channel.setErr(err);
+ channel.open().verify(3L, TimeUnit.SECONDS);
+ break; // 1st success means all methods have been invoked
+ }
+ } catch (IOException e) {
+ synchronized(eventsMap) {
+ eventsMap.remove("Closed"); // since it is called anyway but does not cause an IOException
+ assertTrue("Unexpected failure at retry #" + retryCount, eventsMap.size() < 3);
+ }
+ }
+ }
+ } finally {
+ client.stop();
+ }
+
+ assertEquals("Mismatched total failures count on test end", 3, eventsMap.size());
+ assertEquals("Mismatched open failures count on test end", 1, failuresSet.size());
+ }
+
+ @Test
+ public void testSimpleClientListener() throws Exception {
+ final AtomicReference<Channel> channelHolder = new AtomicReference<>(null);
+ client.addChannelListener(new ChannelListener() {
+ @Override
+ public void channelOpenSuccess(Channel channel) {
+ assertSame("Mismatched opened channel instances", channel, channelHolder.get());
+ }
+
+ @Override
+ public void channelOpenFailure(Channel channel, Throwable reason) {
+ assertSame("Mismatched failed open channel instances", channel, channelHolder.get());
+ }
+
+ @Override
+ public void channelInitialized(Channel channel) {
+ assertNull("Multiple channel initialization notifications", channelHolder.getAndSet(channel));
+ }
+
+ @Override
+ public void channelClosed(Channel channel) {
+ assertSame("Mismatched closed channel instances", channel, channelHolder.getAndSet(null));
+ }
+ });
+ sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
+
+ client.start();
+
+ try (final ClientSession session = createTestClientSession()) {
+ testClientListener(channelHolder, ChannelShell.class, new Factory<ChannelShell>() {
+ @Override
+ public ChannelShell create() {
+ try {
+ return session.createShellChannel();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ testClientListener(channelHolder, ChannelExec.class, new Factory<ChannelExec>() {
+ @Override
+ public ChannelExec create() {
+ try {
+ return session.createExecChannel(getCurrentTestName());
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ testClientListener(channelHolder, SftpClient.class, new Factory<SftpClient>() {
+ @Override
+ public SftpClient create() {
+ try {
+ return session.createSftpClient();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ });
+ } finally {
+ client.stop();
+ }
+ }
+
+ private <C extends Closeable> void testClientListener(AtomicReference<Channel> channelHolder, Class<C> channelType, Factory<? extends C> factory) throws Exception {
+ assertNull(channelType.getSimpleName() + ": Unexpected currently active channel", channelHolder.get());
+
+ try(C instance = factory.create()) {
+ Channel expectedChannel;
+ if (instance instanceof Channel) {
+ expectedChannel = (Channel) instance;
+ } else if (instance instanceof SubsystemClient) {
+ expectedChannel = ((SubsystemClient) instance).getClientChannel();
+ } else {
+ throw new UnsupportedOperationException("Unknown test instance type" + instance.getClass().getSimpleName());
+ }
+
+ Channel actualChannel = channelHolder.get();
+ assertSame("Mismatched listener " + channelType.getSimpleName() + " instances", expectedChannel, actualChannel);
+ }
+
+ assertNull(channelType.getSimpleName() + ": Active channel closure not signalled", channelHolder.get());
}
@Test
@@ -205,23 +406,21 @@ public class ClientTest extends BaseTestSupport {
FactoryManagerUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
+ try (ClientSession session = createTestClientSession();
+ final ChannelShell channel = session.createShellChannel()) {
- try (final ChannelShell channel = session.createShellChannel()) {
- channel.setStreaming(ClientChannel.Streaming.Async);
- channel.open().verify(5L, TimeUnit.SECONDS);
+ channel.setStreaming(ClientChannel.Streaming.Async);
+ channel.open().verify(5L, TimeUnit.SECONDS);
- final byte[] message = "0123456789\n".getBytes(StandardCharsets.UTF_8);
- final int nbMessages = 1000;
+ final byte[] message = "0123456789\n".getBytes(StandardCharsets.UTF_8);
+ final int nbMessages = 1000;
- try (final ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
- final ByteArrayOutputStream baosErr = new ByteArrayOutputStream()) {
- final AtomicInteger writes = new AtomicInteger(nbMessages);
+ try (final ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
+ final ByteArrayOutputStream baosErr = new ByteArrayOutputStream()) {
+ final AtomicInteger writes = new AtomicInteger(nbMessages);
- channel.getAsyncIn().write(new ByteArrayBuffer(message))
- .addListener(new SshFutureListener<IoWriteFuture>() {
+ channel.getAsyncIn().write(new ByteArrayBuffer(message))
+ .addListener(new SshFutureListener<IoWriteFuture>() {
@Override
public void operationComplete(IoWriteFuture future) {
try {
@@ -242,8 +441,8 @@ public class ClientTest extends BaseTestSupport {
}
}
});
- channel.getAsyncOut().read(new ByteArrayBuffer())
- .addListener(new SshFutureListener<IoReadFuture>() {
+ channel.getAsyncOut().read(new ByteArrayBuffer())
+ .addListener(new SshFutureListener<IoReadFuture>() {
@Override
public void operationComplete(IoReadFuture future) {
try {
@@ -261,8 +460,8 @@ public class ClientTest extends BaseTestSupport {
}
}
});
- channel.getAsyncErr().read(new ByteArrayBuffer())
- .addListener(new SshFutureListener<IoReadFuture>() {
+ channel.getAsyncErr().read(new ByteArrayBuffer())
+ .addListener(new SshFutureListener<IoReadFuture>() {
@Override
public void operationComplete(IoReadFuture future) {
try {
@@ -281,210 +480,201 @@ public class ClientTest extends BaseTestSupport {
}
});
- channel.waitFor(ClientChannel.CLOSED, 0);
+ channel.waitFor(ClientChannel.CLOSED, 0);
- assertEquals(nbMessages * message.length, baosOut.size());
- }
+ assertEquals("Mismatched sent and received data size", nbMessages * message.length, baosOut.size());
}
client.close(true);
} finally {
client.stop();
}
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
public void testCommandDeadlock() throws Exception {
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- try (ChannelExec channel = session.createExecChannel(getCurrentTestName());
- OutputStream stdout = new NoCloseOutputStream(System.out);
- OutputStream stderr = new NoCloseOutputStream(System.err)) {
-
- channel.setOut(stdout);
- channel.setErr(stderr);
- channel.open().verify(9L, TimeUnit.SECONDS);
- Thread.sleep(125L);
- try {
- byte[] data = "a".getBytes(StandardCharsets.UTF_8);
- for (int i = 0; i < 100; i++) {
- channel.getInvertedIn().write(data);
- channel.getInvertedIn().flush();
- }
- } catch (SshException e) {
- // That's ok, the channel is being closed by the other side
+ try (ClientSession session = createTestClientSession();
+ ChannelExec channel = session.createExecChannel(getCurrentTestName());
+ OutputStream stdout = new NoCloseOutputStream(System.out);
+ OutputStream stderr = new NoCloseOutputStream(System.err)) {
+
+ channel.setOut(stdout);
+ channel.setErr(stderr);
+ channel.open().verify(9L, TimeUnit.SECONDS);
+ Thread.sleep(125L);
+ try {
+ byte[] data = "a".getBytes(StandardCharsets.UTF_8);
+ OutputStream invertedStream = channel.getInvertedIn();
+ for (int i = 0; i < 100; i++) {
+ invertedStream.write(data);
+ invertedStream.flush();
}
- assertEquals(ClientChannel.CLOSED, channel.waitFor(ClientChannel.CLOSED, 0) & ClientChannel.CLOSED);
- session.close(false).await();
+ } catch (SshException e) {
+ // That's ok, the channel is being closed by the other side
}
+ assertEquals(ClientChannel.CLOSED, channel.waitFor(ClientChannel.CLOSED, 0) & ClientChannel.CLOSED);
+ session.close(false).await();
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
public void testClient() throws Exception {
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- try (ClientChannel channel = session.createShellChannel();
- ByteArrayOutputStream sent = new ByteArrayOutputStream();
- PipedOutputStream pipedIn = new PipedOutputStream();
- PipedInputStream pipedOut = new PipedInputStream(pipedIn)) {
+ try (ClientSession session = createTestClientSession();
+ ClientChannel channel = session.createShellChannel();
+ ByteArrayOutputStream sent = new ByteArrayOutputStream();
+ PipedOutputStream pipedIn = new PipedOutputStream();
+ PipedInputStream pipedOut = new PipedInputStream(pipedIn)) {
- channel.setIn(pipedOut);
+ channel.setIn(pipedOut);
- try (OutputStream teeOut = new TeeOutputStream(sent, pipedIn);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ByteArrayOutputStream err = new ByteArrayOutputStream()) {
+ try (OutputStream teeOut = new TeeOutputStream(sent, pipedIn);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream err = new ByteArrayOutputStream()) {
- channel.setOut(out);
- channel.setErr(err);
- channel.open();
+ channel.setOut(out);
+ channel.setErr(err);
+ channel.open();
- teeOut.write("this is my command\n".getBytes(StandardCharsets.UTF_8));
- teeOut.flush();
+ teeOut.write("this is my command\n".getBytes(StandardCharsets.UTF_8));
+ teeOut.flush();
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < 1000; i++) {
- sb.append("0123456789");
- }
- sb.append("\n");
- teeOut.write(sb.toString().getBytes(StandardCharsets.UTF_8));
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < 1000; i++) {
+ sb.append("0123456789");
+ }
+ sb.append("\n");
+ teeOut.write(sb.toString().getBytes(StandardCharsets.UTF_8));
- teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8));
- teeOut.flush();
+ teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8));
+ teeOut.flush();
- channel.waitFor(ClientChannel.CLOSED, 0);
+ channel.waitFor(ClientChannel.CLOSED, 0);
- channel.close(false);
- client.stop();
+ channel.close(false);
+ client.stop();
- assertArrayEquals(sent.toByteArray(), out.toByteArray());
- }
+ assertArrayEquals("Mismatched sent and received data", sent.toByteArray(), out.toByteArray());
}
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
public void testClientInverted() throws Exception {
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- try (ClientChannel channel = session.createShellChannel();
- ByteArrayOutputStream sent = new ByteArrayOutputStream();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ByteArrayOutputStream err = new ByteArrayOutputStream()) {
-
- channel.setOut(out);
- channel.setErr(err);
- channel.open().verify(9L, TimeUnit.SECONDS);
+ try (ClientSession session = createTestClientSession();
+ ClientChannel channel = session.createShellChannel();
+ ByteArrayOutputStream sent = new ByteArrayOutputStream();
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream err = new ByteArrayOutputStream()) {
- try (OutputStream pipedIn = new TeeOutputStream(sent, channel.getInvertedIn())) {
- pipedIn.write("this is my command\n".getBytes(StandardCharsets.UTF_8));
- pipedIn.flush();
+ channel.setOut(out);
+ channel.setErr(err);
+ channel.open().verify(9L, TimeUnit.SECONDS);
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < 1000; i++) {
- sb.append("0123456789");
- }
- sb.append("\n");
- pipedIn.write(sb.toString().getBytes(StandardCharsets.UTF_8));
+ try (OutputStream pipedIn = new TeeOutputStream(sent, channel.getInvertedIn())) {
+ pipedIn.write("this is my command\n".getBytes(StandardCharsets.UTF_8));
+ pipedIn.flush();
- pipedIn.write("exit\n".getBytes(StandardCharsets.UTF_8));
- pipedIn.flush();
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < 1000; i++) {
+ sb.append("0123456789");
}
+ sb.append("\n");
+ pipedIn.write(sb.toString().getBytes(StandardCharsets.UTF_8));
- channel.waitFor(ClientChannel.CLOSED, 0);
+ pipedIn.write("exit\n".getBytes(StandardCharsets.UTF_8));
+ pipedIn.flush();
+ }
- channel.close(false);
- client.stop();
+ channel.waitFor(ClientChannel.CLOSED, 0);
- assertArrayEquals(sent.toByteArray(), out.toByteArray());
- }
+ channel.close(false);
+ client.stop();
+
+ assertArrayEquals("Mismatched sent and received data", sent.toByteArray(), out.toByteArray());
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
public void testClientWithCustomChannel() throws Exception {
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- try (ChannelShell channel = new ChannelShell();
- ByteArrayOutputStream sent = new ByteArrayOutputStream();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ByteArrayOutputStream err = new ByteArrayOutputStream()) {
-
- session.getService(ConnectionService.class).registerChannel(channel);
- channel.setOut(out);
- channel.setErr(err);
- channel.open().verify(5L, TimeUnit.SECONDS);
- channel.close(false).await();
- }
+ try (ClientSession session = createTestClientSession();
+ ChannelShell channel = new ChannelShell();
+ ByteArrayOutputStream sent = new ByteArrayOutputStream();
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream err = new ByteArrayOutputStream()) {
+
+ session.getService(ConnectionService.class).registerChannel(channel);
+ channel.setOut(out);
+ channel.setErr(err);
+ channel.open().verify(5L, TimeUnit.SECONDS);
+ channel.close(false).await();
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
public void testClientClosingStream() throws Exception {
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- try (ClientChannel channel = session.createShellChannel();
- ByteArrayOutputStream sent = new ByteArrayOutputStream();
- PipedOutputStream pipedIn = new PipedOutputStream();
- InputStream inPipe = new PipedInputStream(pipedIn);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ByteArrayOutputStream err = new ByteArrayOutputStream()) {
-
- channel.setIn(inPipe);
- channel.setOut(out);
- channel.setErr(err);
- channel.open();
-
- try (OutputStream teeOut = new TeeOutputStream(sent, pipedIn)) {
- teeOut.write("this is my command\n".getBytes(StandardCharsets.UTF_8));
- teeOut.flush();
-
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < 1000; i++) {
- sb.append("0123456789");
- }
- sb.append("\n");
- teeOut.write(sb.toString().getBytes(StandardCharsets.UTF_8));
+ try (ClientSession session = createTestClientSession();
+ ClientChannel channel = session.createShellChannel();
+ ByteArrayOutputStream sent = new ByteArrayOutputStream();
+ PipedOutputStream pipedIn = new PipedOutputStream();
+ InputStream inPipe = new PipedInputStream(pipedIn);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream err = new ByteArrayOutputStream()) {
+
+ channel.setIn(inPipe);
+ channel.setOut(out);
+ channel.setErr(err);
+ channel.open();
+
+ try (OutputStream teeOut = new TeeOutputStream(sent, pipedIn)) {
+ teeOut.write("this is my command\n".getBytes(StandardCharsets.UTF_8));
+ teeOut.flush();
+
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < 1000; i++) {
+ sb.append("0123456789");
}
+ sb.append("\n");
+ teeOut.write(sb.toString().getBytes(StandardCharsets.UTF_8));
+ }
- channel.waitFor(ClientChannel.CLOSED, 0);
+ channel.waitFor(ClientChannel.CLOSED, 0);
- channel.close(false);
- client.stop();
+ channel.close(false);
+ client.stop();
- assertArrayEquals(sent.toByteArray(), out.toByteArray());
- }
+ assertArrayEquals("Mismatched sent and received data", sent.toByteArray(), out.toByteArray());
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -496,79 +686,73 @@ public class ClientTest extends BaseTestSupport {
// FactoryManagerUtils.updateProperty(sshd, SshServer.MAX_PACKET_SIZE, 0x1000);
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- try (ClientChannel channel = session.createShellChannel();
- ByteArrayOutputStream sent = new ByteArrayOutputStream();
- PipedOutputStream pipedIn = new PipedOutputStream();
- InputStream inPipe = new PipedInputStream(pipedIn);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ByteArrayOutputStream err = new ByteArrayOutputStream()) {
-
- channel.setIn(inPipe);
- channel.setOut(out);
- channel.setErr(err);
- channel.open().verify(9L, TimeUnit.SECONDS);
-
-
- int bytes = 0;
- byte[] data = "01234567890123456789012345678901234567890123456789\n".getBytes(StandardCharsets.UTF_8);
- long t0 = System.currentTimeMillis();
- try (OutputStream teeOut = new TeeOutputStream(sent, pipedIn)) {
- for (int i = 0; i < 10000; i++) {
- teeOut.write(data);
- teeOut.flush();
- bytes += data.length;
- if ((bytes & 0xFFF00000) != ((bytes - data.length) & 0xFFF00000)) {
- System.out.println("Bytes written: " + bytes);
- }
- }
- teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8));
+ try (ClientSession session = createTestClientSession();
+ ClientChannel channel = session.createShellChannel();
+ ByteArrayOutputStream sent = new ByteArrayOutputStream();
+ PipedOutputStream pipedIn = new PipedOutputStream();
+ InputStream inPipe = new PipedInputStream(pipedIn);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream err = new ByteArrayOutputStream()) {
+
+ channel.setIn(inPipe);
+ channel.setOut(out);
+ channel.setErr(err);
+ channel.open().verify(9L, TimeUnit.SECONDS);
+
+ int bytes = 0;
+ byte[] data = "01234567890123456789012345678901234567890123456789\n".getBytes(StandardCharsets.UTF_8);
+ long t0 = System.currentTimeMillis();
+ try (OutputStream teeOut = new TeeOutputStream(sent, pipedIn)) {
+ for (int i = 0; i < 10000; i++) {
+ teeOut.write(data);
teeOut.flush();
+ bytes += data.length;
+ if ((bytes & 0xFFF00000) != ((bytes - data.length) & 0xFFF00000)) {
+ System.out.println("Bytes written: " + bytes);
+ }
}
- long t1 = System.currentTimeMillis();
-
- System.out.println("Sent " + (bytes / 1024) + " Kb in " + (t1 - t0) + " ms");
+ teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8));
+ teeOut.flush();
+ }
- System.out.println("Waiting for channel to be closed");
+ long t1 = System.currentTimeMillis();
+ System.out.println("Sent " + (bytes / 1024) + " Kb in " + (t1 - t0) + " ms");
- channel.waitFor(ClientChannel.CLOSED, 0);
-
- channel.close(false);
- client.stop();
+ System.out.println("Waiting for channel to be closed");
+ channel.waitFor(ClientChannel.CLOSED, 0);
+ channel.close(false);
+ client.stop();
- assertArrayEquals(sent.toByteArray(), out.toByteArray());
- //assertArrayEquals(sent.toByteArray(), out.toByteArray());
- }
+ assertArrayEquals("Mismatched sent and received data", sent.toByteArray(), out.toByteArray());
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test(expected = SshException.class)
public void testOpenChannelOnClosedSession() throws Exception {
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
+ try (ClientSession session = createTestClientSession();
+ ClientChannel channel = session.createShellChannel()) {
- try (ClientChannel channel = session.createShellChannel()) {
- session.close(false);
+ session.close(false);
+ assertNull("Session closure not signalled", clientSessionHolder.get());
- try (PipedOutputStream pipedIn = new PipedOutputStream();
- InputStream inPipe = new PipedInputStream(pipedIn);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ByteArrayOutputStream err = new ByteArrayOutputStream()) {
+ try (PipedOutputStream pipedIn = new PipedOutputStream();
+ InputStream inPipe = new PipedInputStream(pipedIn);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream err = new ByteArrayOutputStream()) {
- channel.setIn(inPipe);
- channel.setOut(out);
- channel.setErr(err);
- channel.open();
- }
+ channel.setIn(inPipe);
+ channel.setOut(out);
+ channel.setErr(err);
+ channel.open();
}
+ } finally {
+ client.stop();
}
}
@@ -578,10 +762,12 @@ public class ClientTest extends BaseTestSupport {
client.start();
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
session.addPasswordIdentity(getCurrentTestName());
AuthFuture authFuture = session.auth();
CloseFuture closeFuture = session.close(false);
+
authLatch.countDown();
assertTrue("Authentication writing not completed in time", authFuture.await(11L, TimeUnit.SECONDS));
assertTrue("Session closing not complete in time", closeFuture.await(8L, TimeUnit.SECONDS));
@@ -590,35 +776,35 @@ public class ClientTest extends BaseTestSupport {
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
public void testCloseCleanBeforeChannelOpened() throws Exception {
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- try (ClientChannel channel = session.createShellChannel();
- InputStream inp = new ByteArrayInputStream(GenericUtils.EMPTY_BYTE_ARRAY);
- OutputStream out = new ByteArrayOutputStream();
- OutputStream err = new ByteArrayOutputStream()) {
+ try (ClientSession session = createTestClientSession();
+ ClientChannel channel = session.createShellChannel();
+ InputStream inp = new ByteArrayInputStream(GenericUtils.EMPTY_BYTE_ARRAY);
+ OutputStream out = new ByteArrayOutputStream();
+ OutputStream err = new ByteArrayOutputStream()) {
- channel.setIn(inp);
- channel.setOut(out);
- channel.setErr(err);
+ channel.setIn(inp);
+ channel.setOut(out);
+ channel.setErr(err);
- OpenFuture openFuture = channel.open();
- CloseFuture closeFuture = session.close(false);
- assertTrue("Channel not open in time", openFuture.await(11L, TimeUnit.SECONDS));
- assertTrue("Session closing not complete in time", closeFuture.await(8L, TimeUnit.SECONDS));
- assertTrue("Not open", openFuture.isOpened());
- assertTrue("Not closed", closeFuture.isClosed());
- }
+ OpenFuture openFuture = channel.open();
+ CloseFuture closeFuture = session.close(false);
+ assertTrue("Channel not open in time", openFuture.await(11L, TimeUnit.SECONDS));
+ assertTrue("Session closing not complete in time", closeFuture.await(8L, TimeUnit.SECONDS));
+ assertTrue("Not open", openFuture.isOpened());
+ assertTrue("Not closed", closeFuture.isClosed());
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -626,27 +812,25 @@ public class ClientTest extends BaseTestSupport {
channelLatch = new CountDownLatch(1);
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
+ try (ClientSession session = createTestClientSession();
+ ClientChannel channel = session.createShellChannel();
+ InputStream inp = new ByteArrayInputStream(GenericUtils.EMPTY_BYTE_ARRAY);
+ OutputStream out = new ByteArrayOutputStream();
+ OutputStream err = new ByteArrayOutputStream()) {
- try (ClientChannel channel = session.createShellChannel();
- InputStream inp = new ByteArrayInputStream(GenericUtils.EMPTY_BYTE_ARRAY);
- OutputStream out = new ByteArrayOutputStream();
- OutputStream err = new ByteArrayOutputStream()) {
+ channel.setIn(inp);
+ channel.setOut(out);
+ channel.setErr(err);
- channel.setIn(inp);
- channel.setOut(out);
- channel.setErr(err);
+ OpenFuture openFuture = channel.open();
+ CloseFuture closeFuture = session.close(true);
+ assertNull("Session closure not signalled", clientSessionHolder.get());
- OpenFuture openFuture = channel.open();
- CloseFuture closeFuture = session.close(true);
- channelLatch.countDown();
- assertTrue("Channel not open in time", openFuture.await(11L, TimeUnit.SECONDS));
- assertTrue("Session closing not complete in time", closeFuture.await(8L, TimeUnit.SECONDS));
- assertNotNull("No open exception", openFuture.getException());
- assertTrue("Not closed", closeFuture.isClosed());
- }
+ channelLatch.countDown();
+ assertTrue("Channel not open in time", openFuture.await(11L, TimeUnit.SECONDS));
+ assertTrue("Session closing not complete in time", closeFuture.await(8L, TimeUnit.SECONDS));
+ assertNotNull("No open exception", openFuture.getException());
+ assertTrue("Not closed", closeFuture.isClosed());
} finally {
client.stop();
}
@@ -657,12 +841,14 @@ public class ClientTest extends BaseTestSupport {
client.start();
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
session.addPublicKeyIdentity(pair);
session.auth().verify(5L, TimeUnit.SECONDS);
} finally {
client.stop();
}
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -671,15 +857,20 @@ public class ClientTest extends BaseTestSupport {
client.start();
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
session.addPublicKeyIdentity(Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA));
session.auth().verify(5L, TimeUnit.SECONDS);
} finally {
client.stop();
}
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
public void testPublicKeyAuthNewWithFailureOnFirstIdentity() throws Exception {
+ SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider();
+ provider.setAlgorithm("RSA");
+
final KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
@Override
@@ -690,16 +881,15 @@ public class ClientTest extends BaseTestSupport {
client.setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(UserAuthPublicKeyFactory.INSTANCE));
client.start();
- SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider();
- provider.setAlgorithm("RSA");
-
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
session.addPublicKeyIdentity(provider.loadKey(KeyPairProvider.SSH_RSA));
session.addPublicKeyIdentity(pair);
session.auth().verify(5L, TimeUnit.SECONDS);
} finally {
client.stop();
}
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -707,12 +897,12 @@ public class ClientTest extends BaseTestSupport {
client.setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(new UserAuthPasswordFactory()));
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
+ try (ClientSession session = createTestClientSession()) {
+ // nothing extra
} finally {
client.stop();
}
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -721,12 +911,14 @@ public class ClientTest extends BaseTestSupport {
client.start();
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
session.addPasswordIdentity(getClass().getSimpleName());
session.addPasswordIdentity(getCurrentTestName());
session.auth().verify(5L, TimeUnit.SECONDS);
} finally {
client.stop();
}
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -734,12 +926,12 @@ public class ClientTest extends BaseTestSupport {
client.setUserAuthFactories(Arrays.<NamedFactory<UserAuth>>asList(UserAuthKeyboardInteractiveFactory.INSTANCE));
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
+ try (ClientSession session = createTestClientSession()) {
+ // nothing extra
} finally {
client.stop();
}
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -748,12 +940,14 @@ public class ClientTest extends BaseTestSupport {
client.start();
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
session.addPasswordIdentity(getClass().getSimpleName());
session.addPasswordIdentity(getCurrentTestName());
session.auth().verify(5L, TimeUnit.SECONDS);
} finally {
client.stop();
}
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test // see SSHD-504
@@ -837,6 +1031,7 @@ public class ClientTest extends BaseTestSupport {
try {
for (int index = 0; index < xformers.size(); index++) {
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled at iteration #" + index, clientSessionHolder.get());
String password = "bad-" + getCurrentTestName() + "-" + index;
session.addPasswordIdentity(password);
@@ -845,13 +1040,15 @@ public class ClientTest extends BaseTestSupport {
assertFalse("Unexpected success for password=" + password, future.isSuccess());
session.removePasswordIdentity(password);
}
+
+ assertNull("Session closure not signalled at iteration #" + index, clientSessionHolder.get());
}
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
+ try (ClientSession session = createTestClientSession()) {
assertTrue("Mismatched prompts evaluation results", mismatchedPrompts.isEmpty());
}
+
+ assertNull("Final session closure not signalled", clientSessionHolder.get());
} finally {
client.stop();
}
@@ -879,6 +1076,8 @@ public class ClientTest extends BaseTestSupport {
client.start();
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
+
AuthFuture future = session.auth();
future.await();
assertTrue("Unexpected authentication success", future.isFailure());
@@ -886,6 +1085,8 @@ public class ClientTest extends BaseTestSupport {
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -899,6 +1100,7 @@ public class ClientTest extends BaseTestSupport {
client.start();
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
session.setUserInteraction(new UserInteraction() {
@Override
public void welcome(String banner) {
@@ -912,6 +1114,7 @@ public class ClientTest extends BaseTestSupport {
return new String[]{getCurrentTestName()};
}
});
+
AuthFuture future = session.auth();
future.await();
assertTrue("Authentication not marked as success", future.isSuccess());
@@ -920,6 +1123,8 @@ public class ClientTest extends BaseTestSupport {
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -932,6 +1137,7 @@ public class ClientTest extends BaseTestSupport {
client.start();
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
session.setUserInteraction(new UserInteraction() {
@Override
public void welcome(String banner) {
@@ -945,6 +1151,7 @@ public class ClientTest extends BaseTestSupport {
return new String[]{"bad#" + attemptId};
}
});
+
AuthFuture future = session.auth();
assertTrue("Authentication not completed in time", future.await(11L, TimeUnit.SECONDS));
assertTrue("Authentication not, marked as failure", future.isFailure());
@@ -952,6 +1159,8 @@ public class ClientTest extends BaseTestSupport {
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -960,36 +1169,35 @@ public class ClientTest extends BaseTestSupport {
try {
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- try (ClientChannel channel = session.createShellChannel();
- PipedOutputStream pipedIn = new PipedOutputStream();
- InputStream inPipe = new PipedInputStream(pipedIn);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ByteArrayOutputStream err = new ByteArrayOutputStream()) {
-
- channel.setIn(inPipe);
- channel.setOut(out);
- channel.setErr(err);
- channel.open().verify(9L, TimeUnit.SECONDS);
-
- // ((AbstractSession) session).disconnect(SshConstants.SSH2_DISCONNECT_BY_APPLICATION, "Cancel");
- AbstractSession cs = (AbstractSession) session;
- Buffer buffer = cs.createBuffer(SshConstants.SSH_MSG_DISCONNECT);
- buffer.putInt(SshConstants.SSH2_DISCONNECT_BY_APPLICATION);
- buffer.putString("Cancel");
- buffer.putString("");
- IoWriteFuture f = cs.writePacket(buffer);
- assertTrue("Packet writing not completed in time", f.await(11L, TimeUnit.SECONDS));
- suspend(cs.getIoSession());
-
- TestEchoShellFactory.TestEchoShell.latch.await();
- }
+ try (ClientSession session = createTestClientSession();
+ ClientChannel channel = session.createShellChannel();
+ PipedOutputStream pipedIn = new PipedOutputStream();
+ InputStream inPipe = new PipedInputStream(pipedIn);
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream err = new ByteArrayOutputStream()) {
+
+ channel.setIn(inPipe);
+ channel.setOut(out);
+ channel.setErr(err);
+ channel.open().verify(9L, TimeUnit.SECONDS);
+
+ // ((AbstractSession) session).disconnect(SshConstants.SSH2_DISCONNECT_BY_APPLICATION, "Cancel");
+ AbstractSession cs = (AbstractSession) session;
+ Buffer buffer = cs.createBuffer(SshConstants.SSH_MSG_DISCONNECT);
+ buffer.putInt(SshConstants.SSH2_DISCONNECT_BY_APPLICATION);
+ buffer.putString("Cancel");
+ buffer.putString("");
+
+ IoWriteFuture f = cs.writePacket(buffer);
+ assertTrue("Packet writing not completed in time", f.await(11L, TimeUnit.SECONDS));
+ suspend(cs.getIoSession());
+
+ TestEchoShellFactory.TestEchoShell.latch.await();
} finally {
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
} finally {
TestEchoShellFactory.TestEchoShell.latch = null;
}
@@ -1015,11 +1223,13 @@ public class ClientTest extends BaseTestSupport {
client.start();
try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
session.waitFor(ClientSession.WAIT_AUTH, TimeUnit.SECONDS.toMillis(10L));
- assertTrue(ok.get());
+ assertTrue("Server key verifier invoked ?", ok.get());
} finally {
client.stop();
}
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -1028,9 +1238,7 @@ public class ClientTest extends BaseTestSupport {
client.getCipherFactories().add(BuiltinCiphers.none);
client.start();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
+ try (ClientSession session = createTestClientSession()) {
assertTrue("Failed to switch to NONE cipher on time", session.switchToNoneCipher().await(5L, TimeUnit.SECONDS));
try (ClientChannel channel = session.createSubsystemChannel(SftpConstants.SFTP_SUBSYSTEM_NAME)) {
@@ -1039,6 +1247,7 @@ public class ClientTest extends BaseTestSupport {
} finally {
client.stop();
}
+ assertNull("Session closure not signalled", clientSessionHolder.get());
}
@Test
@@ -1046,10 +1255,7 @@ public class ClientTest extends BaseTestSupport {
client.start();
Collection<ClientChannel> channels = new LinkedList<>();
- try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) {
- session.addPasswordIdentity(getCurrentTestName());
- session.auth().verify(5L, TimeUnit.SECONDS);
-
+ try (ClientSession session = createTestClientSession()) {
channels.add(session.createChannel(ClientChannel.CHANNEL_SUBSYSTEM, SftpConstants.SFTP_SUBSYSTEM_NAME));
channels.add(session.createChannel(ClientChannel.CHANNEL_EXEC, getCurrentTestName()));
channels.add(session.createChannel(ClientChannel.CHANNEL_SHELL, getClass().getSimpleName()));
@@ -1069,6 +1275,87 @@ public class ClientTest extends BaseTestSupport {
}
client.stop();
}
+
+ assertNull("Session closure not signalled", clientSessionHolder.get());
+ }
+
+ /**
+ * Makes sure that the {@link ChannelListener}s added to the client, session
+ * and channel are <U>cumulative</U> - i.e., all of them invoked
+ * @throws Exception If failed
+ */
+ @Test
+ public void testChannelListenersPropagation() throws Exception {
+ Map<String,TestChannelListener> clientListeners = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
+ addChannelListener(clientListeners, client, new TestChannelListener(client.getClass().getSimpleName()));
+
+ client.start();
+ try (ClientSession session = createTestClientSession()) {
+ addChannelListener(clientListeners, session, new TestChannelListener(session.getClass().getSimpleName()));
+ assertListenerSizes("ClientSessionOpen", clientListeners, 0, 0);
+
+ try (ClientChannel channel = session.createSubsystemChannel(SftpConstants.SFTP_SUBSYSTEM_NAME)) {
+ channel.open().verify(5L, TimeUnit.SECONDS);
+
+ TestChannelListener channelListener = new TestChannelListener(channel.getClass().getSimpleName());
+ // need to emulate them since we are adding the listener AFTER the channel is open
+ channelListener.channelInitialized(channel);
+ channelListener.channelOpenSuccess(channel);
+ channel.addChannelListener(channelListener);
+ assertListenerSizes("ClientChannelOpen", clientListeners, 1, 1);
+ }
+
+ assertListenerSizes("ClientChannelClose", clientListeners, 0, 1);
+ } finally {
+ client.stop();
+ }
+
+ assertListenerSizes("ClientStop", clientListeners, 0, 1);
+ }
+
+ private static void assertListenerSizes(String phase, Map<String,? extends TestChannelListener> listeners, int activeSize, int openSize) {
+ assertListenerSizes(phase, listeners.values(), activeSize, openSize);
+ }
+
+ private static void assertListenerSizes(String phase, Collection<? extends TestChannelListener> listeners, int activeSize, int openSize) {
+ if (GenericUtils.isEmpty(listeners)) {
+ return;
+ }
+
+ for (TestChannelListener l : listeners) {
+ if (activeSize >= 0) {
+ assertEquals(phase + ": mismatched active channels size for " + l.getName() + " listener", activeSize, GenericUtils.size(l.getActiveChannels()));
+ }
+
+ if (openSize >= 0) {
+ assertEquals(phase + ": mismatched open channels size for " + l.getName() + " listener", openSize, GenericUtils.size(l.getOpenChannels()));
+ }
+
+ assertEquals(phase + ": unexpected failed channels size for " + l.getName() + " listener", 0, GenericUtils.size(l.getFailedChannels()));
+ }
+ }
+
+ private static <L extends ChannelListener & NamedResource> void addChannelListener(Map<String,L> listeners, ChannelListenerManager manager, L listener) {
+ String name = listener.getName();
+ assertNull("Duplicate listener named " + name, listeners.put(name, listener));
+ manager.addChannelListener(listener);
+ }
+
+ private ClientSession createTestClientSession() throws IOException {
+ ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession();
+ try {
+ assertNotNull("Client session creation not signalled", clientSessionHolder.get());
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ClientSession returnValue = session;
+ session = null; // avoid 'finally' close
+ return returnValue;
+ } finally {
+ if (session != null) {
+ session.close();
+ }
+ }
}
private void suspend(IoSession ioSession) {
@@ -1099,6 +1386,25 @@ public class ClientTest extends BaseTestSupport {
}
}
+ public static class ChannelFailureException extends RuntimeException implements NamedResource {
+ private static final long serialVersionUID = 1L; // we're not serializing it
+ private final String name;
+
+ public ChannelFailureException(String name) {
+ this.name = ValidateUtils.checkNotNullAndNotEmpty(name, "No event name provided");
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ @Override
+ public String toString() {
+ return getName();
+ }
+ }
+
public static void main(String[] args) throws Exception {
SshClient.main(args);
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/test/java/org/apache/sshd/common/channel/TestChannelListener.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/channel/TestChannelListener.java b/sshd-core/src/test/java/org/apache/sshd/common/channel/TestChannelListener.java
new file mode 100644
index 0000000..0f7c18b
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/common/channel/TestChannelListener.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.common.channel;
+
+import java.util.Collection;
+import java.util.concurrent.CopyOnWriteArraySet;
+
+import org.apache.sshd.common.NamedResource;
+import org.apache.sshd.common.channel.Channel;
+import org.apache.sshd.common.channel.ChannelListener;
+import org.apache.sshd.common.util.logging.AbstractLoggingBean;
+import org.junit.Assert;
+
+/**
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public class TestChannelListener extends AbstractLoggingBean implements ChannelListener, NamedResource {
+ private final String name;
+ private final Collection<Channel> activeChannels = new CopyOnWriteArraySet<>();
+ private final Collection<Channel> openChannels = new CopyOnWriteArraySet<>();
+ private final Collection<Channel> failedChannels = new CopyOnWriteArraySet<>();
+
+ public TestChannelListener() {
+ this("");
+ }
+
+ public TestChannelListener(String discriminator) {
+ super(discriminator);
+ name = discriminator;
+ }
+
+ @Override
+ public String getName() {
+ return name;
+ }
+
+ public Collection<Channel> getActiveChannels() {
+ return activeChannels;
+ }
+
+ @Override
+ public void channelInitialized(Channel channel) {
+ Assert.assertTrue("Same channel instance re-initialized: " + channel, activeChannels.add(channel));
+ log.info("channelInitialized({})", channel);
+ }
+
+ public Collection<Channel> getOpenChannels() {
+ return openChannels;
+ }
+
+ @Override
+ public void channelOpenSuccess(Channel channel) {
+ Assert.assertTrue("Open channel not activated: " + channel, activeChannels.contains(channel));
+ Assert.assertTrue("Same channel instance re-opened: " + channel, openChannels.add(channel));
+ log.info("channelOpenSuccess({})", channel);
+ }
+
+ public Collection<Channel> getFailedChannels() {
+ return failedChannels;
+ }
+
+ @Override
+ public void channelOpenFailure(Channel channel, Throwable reason) {
+ Assert.assertTrue("Failed channel not activated: " + channel, activeChannels.contains(channel));
+ Assert.assertTrue("Same channel instance re-failed: " + channel, failedChannels.add(channel));
+ log.warn("channelOpenFailure({}) {} : {}", channel, reason.getClass().getSimpleName(), reason.getMessage());
+ }
+
+ @Override
+ public void channelClosed(Channel channel) {
+ Assert.assertTrue("Unknown closed channel instance: " + channel, activeChannels.remove(channel));
+ log.info("channelClosed({})", channel);
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "[" + getName() + "]";
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/test/java/org/apache/sshd/common/io/nio2/Nio2ServiceTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/io/nio2/Nio2ServiceTest.java b/sshd-core/src/test/java/org/apache/sshd/common/io/nio2/Nio2ServiceTest.java
index f55a262..002196c 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/io/nio2/Nio2ServiceTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/io/nio2/Nio2ServiceTest.java
@@ -55,7 +55,6 @@ public class Nio2ServiceTest extends BaseTestSupport {
sshd.setKeyPairProvider(Utils.createTestHostKeyProvider());
sshd.setShellFactory(new TestEchoShellFactory());
sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE);
- sshd.setSessionFactory(new org.apache.sshd.server.session.SessionFactory());
sshd.start();
int port = sshd.getPort();
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/test/java/org/apache/sshd/common/signature/AbstractSignatureFactoryTestSupport.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/signature/AbstractSignatureFactoryTestSupport.java b/sshd-core/src/test/java/org/apache/sshd/common/signature/AbstractSignatureFactoryTestSupport.java
index b6a9407..b958ceb 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/signature/AbstractSignatureFactoryTestSupport.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/signature/AbstractSignatureFactoryTestSupport.java
@@ -68,7 +68,6 @@ public abstract class AbstractSignatureFactoryTestSupport extends BaseTestSuppor
public void setUp() throws Exception {
sshd = SshServer.setUpDefaultServer();
sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE);
- sshd.setSessionFactory(new org.apache.sshd.server.session.SessionFactory());
}
@After
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/test/java/org/apache/sshd/deprecated/ClientUserAuthServiceOld.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/deprecated/ClientUserAuthServiceOld.java b/sshd-core/src/test/java/org/apache/sshd/deprecated/ClientUserAuthServiceOld.java
index bff5738..a969502 100644
--- a/sshd-core/src/test/java/org/apache/sshd/deprecated/ClientUserAuthServiceOld.java
+++ b/sshd-core/src/test/java/org/apache/sshd/deprecated/ClientUserAuthServiceOld.java
@@ -188,10 +188,10 @@ public class ClientUserAuthServiceOld extends CloseableUtils.AbstractCloseable i
@Override
protected void preClose() {
- super.preClose();
if (!authFuture.isDone()) {
authFuture.setException(new SshException("Session is closed"));
}
+ super.preClose();
}
public AuthFuture auth(UserAuth userAuth) throws IOException {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/40195ab4/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java
index 97a4b26..59ab3fb 100644
--- a/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java
@@ -82,7 +82,7 @@ public class PublickeyAuthenticatorTest extends BaseTestSupport {
Object result;
try {
result = method.invoke(authenticator, invArgs);
- } catch(InvocationTargetException e) {
+ } catch (InvocationTargetException e) {
Throwable t = e.getTargetException(); // peel of the real exception
System.err.println("Failed (" + t.getClass().getSimpleName() + ")"
+ " to invoke with user=" + useUsername