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/05/19 12:15:16 UTC
[2/2] mina-sshd git commit: [SSHD-467] Close test resources as soon
as possible using try-finally and try-with-resource
[SSHD-467] Close test resources as soon as possible using try-finally and try-with-resource
Project: http://git-wip-us.apache.org/repos/asf/mina-sshd/repo
Commit: http://git-wip-us.apache.org/repos/asf/mina-sshd/commit/1c51deb3
Tree: http://git-wip-us.apache.org/repos/asf/mina-sshd/tree/1c51deb3
Diff: http://git-wip-us.apache.org/repos/asf/mina-sshd/diff/1c51deb3
Branch: refs/heads/master
Commit: 1c51deb35e8986d80f310ae175020d3ea833badb
Parents: d9ed7ab
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Tue May 19 13:15:02 2015 +0300
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Tue May 19 13:15:02 2015 +0300
----------------------------------------------------------------------
.../java/org/apache/sshd/client/SftpClient.java | 18 +-
.../sshd/client/sftp/SftpFileChannel.java | 1 +
.../common/channel/ChannelOutputStream.java | 39 +-
.../sshd/common/io/nio2/Nio2Acceptor.java | 5 +-
.../test/java/org/apache/sshd/AgentTest.java | 154 ++++----
.../org/apache/sshd/AuthenticationTest.java | 139 +++----
.../test/java/org/apache/sshd/ClientTest.java | 38 ++
.../test/java/org/apache/sshd/EcdsaTest.java | 4 +
.../java/org/apache/sshd/KeyReExchangeTest.java | 42 ++-
.../src/test/java/org/apache/sshd/LoadTest.java | 44 +--
.../src/test/java/org/apache/sshd/MacTest.java | 9 +-
.../org/apache/sshd/PortForwardingLoadTest.java | 362 ++++++++++--------
.../org/apache/sshd/PortForwardingTest.java | 222 ++++++-----
.../test/java/org/apache/sshd/ProxyTest.java | 31 +-
.../src/test/java/org/apache/sshd/ScpTest.java | 140 +++----
.../test/java/org/apache/sshd/ServerTest.java | 36 +-
.../org/apache/sshd/SftpFileSystemTest.java | 163 ++++-----
.../src/test/java/org/apache/sshd/SftpTest.java | 364 ++++++++++---------
.../apache/sshd/SinglePublicKeyAuthTest.java | 58 +--
.../java/org/apache/sshd/SpringConfigTest.java | 25 +-
.../java/org/apache/sshd/WelcomeBannerTest.java | 39 +-
.../java/org/apache/sshd/WindowAdjustTest.java | 41 ++-
.../test/java/org/apache/sshd/WindowTest.java | 240 ++++++------
.../org/apache/sshd/client/kex/KexTest.java | 80 ++--
.../channel/ChannelPipedInputStreamTest.java | 1 -
.../common/util/EventListenerUtilsTest.java | 2 +-
.../server/shell/InvertedShellWrapperTest.java | 36 +-
27 files changed, 1314 insertions(+), 1019 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java b/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
index ce1b00e..b4282b5 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
@@ -18,6 +18,12 @@
*/
package org.apache.sshd.client;
+import static org.apache.sshd.common.sftp.SftpConstants.S_IFDIR;
+import static org.apache.sshd.common.sftp.SftpConstants.S_IFLNK;
+import static org.apache.sshd.common.sftp.SftpConstants.S_IFMT;
+import static org.apache.sshd.common.sftp.SftpConstants.S_IFREG;
+
+import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -26,15 +32,10 @@ import java.util.Collection;
import java.util.EnumSet;
import java.util.concurrent.TimeUnit;
-import static org.apache.sshd.common.sftp.SftpConstants.S_IFDIR;
-import static org.apache.sshd.common.sftp.SftpConstants.S_IFLNK;
-import static org.apache.sshd.common.sftp.SftpConstants.S_IFMT;
-import static org.apache.sshd.common.sftp.SftpConstants.S_IFREG;
-
/**
* @author <a href="http://mina.apache.org">Apache MINA Project</a>
*/
-public interface SftpClient extends AutoCloseable {
+public interface SftpClient extends Closeable {
enum OpenMode {
Read,
@@ -184,11 +185,6 @@ public interface SftpClient extends AutoCloseable {
int getVersion();
- /**
- * Close the client.
- */
- void close() throws IOException;
-
boolean isClosing();
//
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java b/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
index e599793..5f651c2 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
@@ -204,6 +204,7 @@ public class SftpFileChannel extends FileChannel {
@Override
public void force(boolean metaData) throws IOException {
+ // ignored
}
@Override
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelOutputStream.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelOutputStream.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelOutputStream.java
index 19d0bb2..fdc4215 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelOutputStream.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelOutputStream.java
@@ -43,7 +43,7 @@ public class ChannelOutputStream extends OutputStream {
private boolean closed;
private int bufferLength;
private int lastSize;
- private boolean noDelay = false;
+ private boolean noDelay;
public ChannelOutputStream(AbstractChannel channel, Window remoteWindow, Logger log, byte cmd) {
this.channel = channel;
@@ -61,15 +61,18 @@ public class ChannelOutputStream extends OutputStream {
return noDelay;
}
+ @Override
public synchronized void write(int w) throws IOException {
b[0] = (byte) w;
write(b, 0, 1);
}
+ @Override
public synchronized void write(byte[] buf, int s, int l) throws IOException {
if (closed) {
- throw new SshException("Already closed");
+ throw new SshException("write(len=" + l + ") channel already closed");
}
+
while (l > 0) {
// The maximum amount we should admit without flushing again
// is enough to make up one full packet within our allowed
@@ -107,15 +110,16 @@ public class ChannelOutputStream extends OutputStream {
@Override
public synchronized void flush() throws IOException {
if (closed) {
- throw new SshException("Already closed");
+ throw new SshException("flush(length=" + bufferLength + ") - stream is already closed");
}
+
try {
while (bufferLength > 0) {
Buffer buf = buffer;
int total = bufferLength;
int length = Math.min(Math.min(remoteWindow.waitForSpace(), total), remoteWindow.getPacketSize());
int pos = buf.wpos();
- buf.wpos(cmd == SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA ? 14 : 10);
+ buf.wpos((cmd == SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA) ? 14 : 10);
buf.putInt(length);
buf.wpos(buf.wpos() + length);
if (total == length) {
@@ -128,23 +132,34 @@ public class ChannelOutputStream extends OutputStream {
}
lastSize = length;
remoteWindow.waitAndConsume(length);
- log.debug("Send {} on channel {}", cmd == SshConstants.SSH_MSG_CHANNEL_DATA ? "SSH_MSG_CHANNEL_DATA" : "SSH_MSG_CHANNEL_EXTENDED_DATA", channel.getId());
+ if (log.isDebugEnabled()) {
+ log.debug("Send {} on channel {}",
+ (cmd == SshConstants.SSH_MSG_CHANNEL_DATA) ? "SSH_MSG_CHANNEL_DATA" : "SSH_MSG_CHANNEL_EXTENDED_DATA",
+ Integer.valueOf(channel.getId()));
+ }
channel.writePacket(buf);
}
- } catch (WindowClosedException e) {
+ } catch(WindowClosedException e) {
closed = true;
throw e;
- } catch (SshException e) {
- throw e;
- } catch (Exception e) {
- throw new SshException(e);
+ } catch(Exception e) {
+ if (e instanceof IOException) {
+ throw (IOException) e;
+ } else {
+ throw new SshException(e);
+ }
}
}
@Override
public synchronized void close() throws IOException {
- flush();
- closed = true;
+ if (!closed) {
+ try {
+ flush();
+ } finally {
+ closed = true;
+ }
+ }
}
private void newBuffer(int size) {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/main/java/org/apache/sshd/common/io/nio2/Nio2Acceptor.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/nio2/Nio2Acceptor.java b/sshd-core/src/main/java/org/apache/sshd/common/io/nio2/Nio2Acceptor.java
index b38e549..29ba7cf 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/io/nio2/Nio2Acceptor.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/io/nio2/Nio2Acceptor.java
@@ -86,10 +86,13 @@ public class Nio2Acceptor extends Nio2Service implements IoAcceptor {
AsynchronousServerSocketChannel channel = channels.remove(address);
if (channel != null) {
try {
+ log.trace("unbind({})", address);
channel.close();
} catch (IOException e) {
- log.warn("Error unbinding socket", e);
+ log.warn("Error unbinding channel for " + address, e);
}
+ } else {
+ log.trace("No active channel to unbind {}", address);
}
}
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/AgentTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/AgentTest.java b/sshd-core/src/test/java/org/apache/sshd/AgentTest.java
index 041ac15..9424c14 100644
--- a/sshd-core/src/test/java/org/apache/sshd/AgentTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/AgentTest.java
@@ -28,6 +28,7 @@ import java.io.OutputStream;
import java.security.KeyPair;
import java.security.PublicKey;
import java.util.List;
+import java.util.concurrent.TimeUnit;
import org.apache.sshd.agent.SshAgent;
import org.apache.sshd.agent.local.LocalAgentFactory;
@@ -44,6 +45,7 @@ import org.apache.sshd.util.BogusPasswordAuthenticator;
import org.apache.sshd.util.BogusPublickeyAuthenticator;
import org.apache.sshd.util.EchoShellFactory;
import org.apache.sshd.util.Utils;
+import org.junit.Assume;
import org.junit.Test;
public class AgentTest extends BaseTestSupport {
@@ -51,9 +53,7 @@ public class AgentTest extends BaseTestSupport {
@Test
public void testAgent() throws Exception {
// TODO: revisit this test to work without BC
- if (!SecurityUtils.isBouncyCastleRegistered()) {
- return;
- }
+ Assume.assumeTrue("BoncyCastle not registered", SecurityUtils.isBouncyCastleRegistered());
try(AgentServer agent = new AgentServer()) {
String authSocket;
@@ -89,12 +89,7 @@ public class AgentTest extends BaseTestSupport {
@Test
public void testAgentForwarding() throws Exception {
// TODO: revisit this test to work without BC
- if (!SecurityUtils.isBouncyCastleRegistered()) {
- return;
- }
-
- int port1;
- int port2;
+ Assume.assumeTrue("BoncyCastle not registered", SecurityUtils.isBouncyCastleRegistered());
TestEchoShellFactory shellFactory = new TestEchoShellFactory();
ProxyAgentFactory agentFactory = new ProxyAgentFactory();
@@ -103,71 +98,84 @@ public class AgentTest extends BaseTestSupport {
KeyPair pair = createTestKeyPairProvider("dsaprivkey.pem").loadKey(KeyPairProvider.SSH_DSS);
localAgentFactory.getAgent().addIdentity(pair, "smx");
- SshServer sshd1 = SshServer.setUpDefaultServer();
- sshd1.setKeyPairProvider(Utils.createTestHostKeyProvider());
- sshd1.setShellFactory(shellFactory);
- sshd1.setPasswordAuthenticator(new BogusPasswordAuthenticator());
- sshd1.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
- sshd1.setAgentFactory(agentFactory);
- sshd1.start();
- port1 = sshd1.getPort();
-
- SshServer sshd2 = SshServer.setUpDefaultServer();
- sshd2.setKeyPairProvider(Utils.createTestHostKeyProvider());
- sshd2.setShellFactory(new TestEchoShellFactory());
- sshd2.setPasswordAuthenticator(new BogusPasswordAuthenticator());
- sshd2.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
- sshd2.setAgentFactory(new ProxyAgentFactory());
- sshd2.start();
- port2 = sshd2.getPort();
-
- SshClient client1 = SshClient.setUpDefaultClient();
- client1.setAgentFactory(localAgentFactory);
- client1.start();
- ClientSession session1 = client1.connect("smx", "localhost", port1).await().getSession();
- session1.auth().verify();
- ChannelShell channel1 = session1.createShellChannel();
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ByteArrayOutputStream err = new ByteArrayOutputStream();
- channel1.setOut(out);
- channel1.setErr(err);
- channel1.setAgentForwarding(true);
- channel1.open().await();
- OutputStream pipedIn = channel1.getInvertedIn();
-
- synchronized (shellFactory.shell) {
- System.out.println("Possibly waiting for remote shell to start");
- if (!shellFactory.shell.started) {
- shellFactory.shell.wait();
+ try(SshServer sshd1 = SshServer.setUpDefaultServer()) {
+ sshd1.setKeyPairProvider(Utils.createTestHostKeyProvider());
+ sshd1.setShellFactory(shellFactory);
+ sshd1.setPasswordAuthenticator(new BogusPasswordAuthenticator());
+ sshd1.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
+ sshd1.setAgentFactory(agentFactory);
+ sshd1.start();
+ int port1 = sshd1.getPort();
+
+ try(SshServer sshd2 = SshServer.setUpDefaultServer()) {
+ sshd2.setKeyPairProvider(Utils.createTestHostKeyProvider());
+ sshd2.setShellFactory(new TestEchoShellFactory());
+ sshd2.setPasswordAuthenticator(new BogusPasswordAuthenticator());
+ sshd2.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
+ sshd2.setAgentFactory(new ProxyAgentFactory());
+ sshd2.start();
+ int port2 = sshd2.getPort();
+
+ try(SshClient client1 = SshClient.setUpDefaultClient()) {
+ client1.setAgentFactory(localAgentFactory);
+ client1.start();
+
+ try(ClientSession session1 = client1.connect("smx", "localhost", port1).await().getSession()) {
+ session1.auth().verify(5L, TimeUnit.SECONDS);
+
+ try(ChannelShell channel1 = session1.createShellChannel();
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream err = new ByteArrayOutputStream()) {
+
+ channel1.setOut(out);
+ channel1.setErr(err);
+ channel1.setAgentForwarding(true);
+ channel1.open().await();
+
+ try(OutputStream pipedIn = channel1.getInvertedIn()) {
+ synchronized (shellFactory.shell) {
+ System.out.println("Possibly waiting for remote shell to start");
+ if (!shellFactory.shell.started) {
+ shellFactory.shell.wait();
+ }
+ }
+
+ try(SshClient client2 = SshClient.setUpDefaultClient()) {
+ client2.setAgentFactory(agentFactory);
+ client2.getProperties().putAll(shellFactory.shell.getEnvironment().getEnv());
+ client2.start();
+
+ try(ClientSession session2 = client2.connect("smx", "localhost", port2).await().getSession()) {
+ session2.auth().verify(5L, TimeUnit.SECONDS);
+
+ try(ChannelShell channel2 = session2.createShellChannel()) {
+ channel2.setIn(shellFactory.shell.getIn());
+ channel2.setOut(shellFactory.shell.getOut());
+ channel2.setErr(shellFactory.shell.getErr());
+ channel2.setAgentForwarding(true);
+ channel2.open().await();
+
+ pipedIn.write("foo\n".getBytes());
+ pipedIn.flush();
+ }
+
+ Thread.sleep(1000);
+
+ System.out.println(out.toString());
+ System.err.println(err.toString());
+
+ sshd1.stop(true);
+ sshd2.stop(true);
+ client1.stop();
+ client2.stop();
+ }
+ }
+ }
+ }
+ }
+ }
}
}
-
- SshClient client2 = SshClient.setUpDefaultClient();
- client2.setAgentFactory(agentFactory);
- client2.getProperties().putAll(shellFactory.shell.getEnvironment().getEnv());
- client2.start();
- ClientSession session2 = client2.connect("smx", "localhost", port2).await().getSession();
- session2.auth().verify();
- ChannelShell channel2 = session2.createShellChannel();
- channel2.setIn(shellFactory.shell.getIn());
- channel2.setOut(shellFactory.shell.getOut());
- channel2.setErr(shellFactory.shell.getErr());
- channel2.setAgentForwarding(true);
- channel2.open().await();
-
- pipedIn.write("foo\n".getBytes());
- pipedIn.flush();
-
- Thread.sleep(1000);
-
- System.out.println(out.toString());
- System.err.println(err.toString());
-
- sshd1.stop(true);
- sshd2.stop(true);
- client1.stop();
- client2.stop();
-
}
public static class TestEchoShellFactory extends EchoShellFactory {
@@ -189,8 +197,6 @@ public class AgentTest extends BaseTestSupport {
started = true;
notifyAll();
}
-
}
}
-
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java b/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java
index 5a3752e..41ad906 100644
--- a/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java
@@ -78,79 +78,95 @@ public class AuthenticationTest extends BaseTestSupport {
@Test
public void testChangeUser() throws Exception {
- SshClient client = SshClient.setUpDefaultClient();
- client.setServiceFactories(Arrays.asList(
- new ClientUserAuthServiceOld.Factory(),
- new ClientConnectionService.Factory()
- ));
- client.start();
- ClientSession s = client.connect(null, "localhost", port).await().getSession();
- s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
-
- assertFalse(authPassword(s, "user1", "the-password").await().isSuccess());
- assertFalse(authPassword(s, "user2", "the-password").await().isSuccess());
-
- // Note that WAIT_AUTH flag should be false, but since the internal
- // authentication future is not updated, it's still returned
- assertEquals(ClientSession.CLOSED | ClientSession.WAIT_AUTH, s.waitFor(ClientSession.CLOSED, 1000));
- client.stop();
+ try(SshClient client = SshClient.setUpDefaultClient()) {
+ client.setServiceFactories(Arrays.asList(
+ new ClientUserAuthServiceOld.Factory(),
+ new ClientConnectionService.Factory()
+ ));
+
+ client.start();
+
+ try(ClientSession s = client.connect(null, "localhost", port).await().getSession()) {
+ s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
+
+ assertFalse(authPassword(s, "user1", "the-password").await().isSuccess());
+ assertFalse(authPassword(s, "user2", "the-password").await().isSuccess());
+
+ // Note that WAIT_AUTH flag should be false, but since the internal
+ // authentication future is not updated, it's still returned
+ assertEquals(ClientSession.CLOSED | ClientSession.WAIT_AUTH, s.waitFor(ClientSession.CLOSED, 1000));
+ } finally {
+ client.stop();
+ }
+ }
}
@Test
public void testAuthPasswordOnly() throws Exception {
- SshClient client = SshClient.setUpDefaultClient();
- client.setServiceFactories(Arrays.asList(
- new ClientUserAuthServiceOld.Factory(),
- new ClientConnectionService.Factory()
- ));
- client.start();
- ClientSession s = client.connect(null, "localhost", port).await().getSession();
- s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
-
- assertFalse(authPassword(s, "smx", "smx").await().isSuccess());
-
- s.close(true);
- client.stop();
+ try(SshClient client = SshClient.setUpDefaultClient()) {
+ client.setServiceFactories(Arrays.asList(
+ new ClientUserAuthServiceOld.Factory(),
+ new ClientConnectionService.Factory()
+ ));
+ client.start();
+
+ try(ClientSession s = client.connect(null, "localhost", port).await().getSession()) {
+ s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
+
+ assertFalse(authPassword(s, "smx", "smx").await().isSuccess());
+
+ s.close(true);
+ } finally {
+ client.stop();
+ }
+ }
}
@Test
public void testAuthKeyPassword() throws Exception {
- SshClient client = SshClient.setUpDefaultClient();
- client.setServiceFactories(Arrays.asList(
- new ClientUserAuthServiceOld.Factory(),
- new ClientConnectionService.Factory()
- ));
- client.start();
- ClientSession s = client.connect(null, "localhost", port).await().getSession();
- s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
-
- KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
- assertFalse(authPublicKey(s, "smx", pair).await().isSuccess());
-
- assertTrue(authPassword(s, "smx", "smx").await().isSuccess());
-
- s.close(true);
- client.stop();
+ try(SshClient client = SshClient.setUpDefaultClient()) {
+ client.setServiceFactories(Arrays.asList(
+ new ClientUserAuthServiceOld.Factory(),
+ new ClientConnectionService.Factory()
+ ));
+ client.start();
+
+ try(ClientSession s = client.connect(null, "localhost", port).await().getSession()) {
+ s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
+
+ KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
+ assertFalse(authPublicKey(s, "smx", pair).await().isSuccess());
+
+ assertTrue(authPassword(s, "smx", "smx").await().isSuccess());
+ s.close(true);
+ } finally {
+ client.stop();
+ }
+ }
}
@Test
public void testAuthKeyInteractive() throws Exception {
- SshClient client = SshClient.setUpDefaultClient();
- client.setServiceFactories(Arrays.asList(
- new ClientUserAuthServiceOld.Factory(),
- new ClientConnectionService.Factory()
- ));
- client.start();
- ClientSession s = client.connect(null, "localhost", port).await().getSession();
- s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
-
- KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
- assertFalse(authPublicKey(s, "smx", pair).await().isSuccess());
-
- assertTrue(authInteractive(s, "smx", "smx").await().isSuccess());
-
- s.close(true);
- client.stop();
+ try(SshClient client = SshClient.setUpDefaultClient()) {
+ client.setServiceFactories(Arrays.asList(
+ new ClientUserAuthServiceOld.Factory(),
+ new ClientConnectionService.Factory()
+ ));
+ client.start();
+
+ try(ClientSession s = client.connect(null, "localhost", port).await().getSession()) {
+ s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
+
+ KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
+ assertFalse(authPublicKey(s, "smx", pair).await().isSuccess());
+
+ assertTrue(authInteractive(s, "smx", "smx").await().isSuccess());
+
+ s.close(true);
+ } finally {
+ client.stop();
+ }
+ }
}
private AuthFuture authPassword(ClientSession s, String user, String pswd) throws IOException {
@@ -180,5 +196,4 @@ public class AuthenticationTest extends BaseTestSupport {
super.handleMessage(buffer);
}
}
-
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/ClientTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/ClientTest.java b/sshd-core/src/test/java/org/apache/sshd/ClientTest.java
index 872ae6c..2be4a59 100644
--- a/sshd-core/src/test/java/org/apache/sshd/ClientTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/ClientTest.java
@@ -266,6 +266,8 @@ public class ClientTest extends BaseTestSupport {
}
client.close(true);
+ } finally {
+ client.stop();
}
}
@@ -344,6 +346,8 @@ public class ClientTest extends BaseTestSupport {
assertArrayEquals(sent.toByteArray(), out.toByteArray());
}
}
+ } finally {
+ client.stop();
}
}
@@ -386,6 +390,8 @@ public class ClientTest extends BaseTestSupport {
assertArrayEquals(sent.toByteArray(), out.toByteArray());
}
+ } finally {
+ client.stop();
}
}
@@ -452,6 +458,8 @@ public class ClientTest extends BaseTestSupport {
assertArrayEquals(sent.toByteArray(), out.toByteArray());
}
+ } finally {
+ client.stop();
}
}
@@ -510,6 +518,8 @@ public class ClientTest extends BaseTestSupport {
assertArrayEquals(sent.toByteArray(), out.toByteArray());
//assertArrayEquals(sent.toByteArray(), out.toByteArray());
}
+ } finally {
+ client.stop();
}
}
@@ -553,6 +563,8 @@ public class ClientTest extends BaseTestSupport {
closeFuture.await();
assertNotNull("No authentication exception", authFuture.getException());
assertTrue("Future not closed", closeFuture.isClosed());
+ } finally {
+ client.stop();
}
}
@@ -580,6 +592,8 @@ public class ClientTest extends BaseTestSupport {
assertTrue("Not open", openFuture.isOpened());
assertTrue("Not closed", closeFuture.isClosed());
}
+ } finally {
+ client.stop();
}
}
@@ -609,6 +623,8 @@ public class ClientTest extends BaseTestSupport {
assertNotNull("No open exception", openFuture.getException());
assertTrue("Not closed", closeFuture.isClosed());
}
+ } finally {
+ client.stop();
}
}
@@ -620,6 +636,8 @@ public class ClientTest extends BaseTestSupport {
KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
session.addPublicKeyIdentity(pair);
session.auth().verify(5L, TimeUnit.SECONDS);
+ } finally {
+ client.stop();
}
}
@@ -631,6 +649,8 @@ public class ClientTest extends BaseTestSupport {
try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
session.addPublicKeyIdentity(Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA));
session.auth().verify(5L, TimeUnit.SECONDS);
+ } finally {
+ client.stop();
}
}
@@ -650,6 +670,8 @@ public class ClientTest extends BaseTestSupport {
session.addPublicKeyIdentity(new SimpleGeneratorHostKeyProvider(null, "RSA").loadKey(KeyPairProvider.SSH_RSA));
session.addPublicKeyIdentity(pair);
session.auth().verify(5L, TimeUnit.SECONDS);
+ } finally {
+ client.stop();
}
}
@@ -661,6 +683,8 @@ public class ClientTest extends BaseTestSupport {
try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
session.addPasswordIdentity("smx");
session.auth().verify(5L, TimeUnit.SECONDS);
+ } finally {
+ client.stop();
}
}
@@ -673,6 +697,8 @@ public class ClientTest extends BaseTestSupport {
session.addPasswordIdentity("bad");
session.addPasswordIdentity("smx");
session.auth().verify(5L, TimeUnit.SECONDS);
+ } finally {
+ client.stop();
}
}
@@ -684,6 +710,8 @@ public class ClientTest extends BaseTestSupport {
try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
session.addPasswordIdentity("smx");
session.auth().verify(5L, TimeUnit.SECONDS);
+ } finally {
+ client.stop();
}
}
@@ -696,6 +724,8 @@ public class ClientTest extends BaseTestSupport {
session.addPasswordIdentity("bad");
session.addPasswordIdentity("smx");
session.auth().verify(5L, TimeUnit.SECONDS);
+ } finally {
+ client.stop();
}
}
@@ -724,6 +754,8 @@ public class ClientTest extends BaseTestSupport {
future.await();
assertTrue("Unexpected authentication success", future.isFailure());
assertEquals("Mismatched authentication retry count", MAX_PROMPTS, count.get());
+ } finally {
+ client.stop();
}
}
@@ -756,6 +788,8 @@ public class ClientTest extends BaseTestSupport {
assertTrue("Authentication not marked as success", future.isSuccess());
assertFalse("Authentication marked as failure", future.isFailure());
assertEquals("Mismatched authentication attempts count", 1, count.get());
+ } finally {
+ client.stop();
}
}
@@ -786,6 +820,8 @@ public class ClientTest extends BaseTestSupport {
future.await();
assertTrue("Authentication not, marked as failure", future.isFailure());
assertEquals("Mismatched authentication retry count", MAX_PROMPTS, count.get());
+ } finally {
+ client.stop();
}
}
@@ -822,6 +858,8 @@ public class ClientTest extends BaseTestSupport {
TestEchoShellFactory.TestEchoShell.latch.await();
}
+ } finally {
+ client.stop();
}
} finally {
TestEchoShellFactory.TestEchoShell.latch = null;
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java b/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
index 9e59b7a..1111d28 100644
--- a/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
@@ -101,6 +101,8 @@ public class EcdsaTest extends BaseTestSupport {
try(ClientSession s = client.connect("smx", "localhost", port).await().getSession()) {
s.addPasswordIdentity("smx");
s.auth().verify(5L, TimeUnit.SECONDS);
+ } finally {
+ client.stop();
}
}
@@ -129,6 +131,8 @@ public class EcdsaTest extends BaseTestSupport {
try(ClientSession s = client.connect("smx", "localhost", port).await().getSession()) {
s.addPublicKeyIdentity(kp);
s.auth().verify(5L, TimeUnit.SECONDS);
+ } finally {
+ client.stop();
}
}
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
index 5acf117..be798a5 100644
--- a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
@@ -80,23 +80,33 @@ public class KeyReExchangeTest extends BaseTestSupport {
JSch.setConfig("kex", "diffie-hellman-group-exchange-sha1");
JSch sch = new JSch();
com.jcraft.jsch.Session s = sch.getSession("smx", "localhost", port);
- s.setUserInfo(new SimpleUserInfo("smx"));
- s.connect();
- com.jcraft.jsch.Channel c = s.openChannel("shell");
- c.connect();
- OutputStream os = c.getOutputStream();
- InputStream is = c.getInputStream();
- for (int i = 0; i < 10; i++) {
- os.write("this is my command\n".getBytes());
- os.flush();
- byte[] data = new byte[512];
- int len = is.read(data);
- String str = new String(data, 0, len);
- assertEquals("this is my command\n", str);
- s.rekey();
+ try {
+ s.setUserInfo(new SimpleUserInfo("smx"));
+ s.connect();
+
+ com.jcraft.jsch.Channel c = s.openChannel("shell");
+ c.connect();
+ try(OutputStream os = c.getOutputStream();
+ InputStream is = c.getInputStream()) {
+
+ String expected = "this is my command\n";
+ byte[] bytes = expected.getBytes();
+ byte[] data = new byte[bytes.length + Long.SIZE];
+ for (int i = 0; i < 10; i++) {
+ os.write(bytes);
+ os.flush();
+
+ int len = is.read(data);
+ String str = new String(data, 0, len);
+ assertEquals("Mismatched data at iteration " + i,expected, str);
+ s.rekey();
+ }
+ } finally {
+ c.disconnect();
+ }
+ } finally {
+ s.disconnect();
}
- c.disconnect();
- s.disconnect();
}
@Test
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
index 4a4e2ca..a756ef6 100644
--- a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
@@ -25,6 +25,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import org.apache.sshd.common.Cipher;
import org.apache.sshd.common.FactoryManager;
@@ -118,30 +119,31 @@ public class LoadTest extends BaseTestSupport {
SshBuilder.ClientBuilder.DH2KEX.transform(BuiltinDHFactories.dhg1)));
client.setCipherFactories(Arrays.<NamedFactory<Cipher>>asList(BuiltinCiphers.blowfishcbc));
client.start();
- try {
- ClientSession session = client.connect("sshd", "localhost", port).await().getSession();
+ try(ClientSession session = client.connect("sshd", "localhost", port).await().getSession()) {
session.addPasswordIdentity("sshd");
- session.auth().verify();
+ session.auth().verify(5L, TimeUnit.SECONDS);
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- ByteArrayOutputStream err = new ByteArrayOutputStream();
- ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
- channel.setOut(out);
- channel.setErr(err);
- try {
- channel.open().await();
- OutputStream pipedIn = channel.getInvertedIn();
-
- msg += "\nexit\n";
- pipedIn.write(msg.getBytes());
- pipedIn.flush();
-
- channel.waitFor(ClientChannel.CLOSED, 0);
- } finally {
- channel.close(false);
- }
+ try(ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream err = new ByteArrayOutputStream();
+ ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) {
+ channel.setOut(out);
+ channel.setErr(err);
- assertArrayEquals("Mismatched message data", msg.getBytes(), out.toByteArray());
+ try {
+ channel.open().await();
+ try(OutputStream pipedIn = channel.getInvertedIn()) {
+ msg += "\nexit\n";
+ pipedIn.write(msg.getBytes());
+ pipedIn.flush();
+ }
+
+ channel.waitFor(ClientChannel.CLOSED, 0);
+ } finally {
+ channel.close(false);
+ }
+
+ assertArrayEquals("Mismatched message data", msg.getBytes(), out.toByteArray());
+ }
} finally {
client.stop();
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/MacTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/MacTest.java b/sshd-core/src/test/java/org/apache/sshd/MacTest.java
index bba527a..dfd2dc0 100644
--- a/sshd-core/src/test/java/org/apache/sshd/MacTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/MacTest.java
@@ -145,16 +145,19 @@ public class MacTest extends BaseTestSupport {
s.connect();
com.jcraft.jsch.Channel c = s.openChannel("shell");
c.connect();
+
try(OutputStream os = c.getOutputStream();
InputStream is = c.getInputStream()) {
- byte[] data = new byte[512];
+ String expected = "this is my command\n";
+ byte[] bytes = expected.getBytes();
+ byte[] data = new byte[bytes.length + Long.SIZE];
for (int i = 0; i < 10; i++) {
- os.write("this is my command\n".getBytes());
+ os.write(bytes);
os.flush();
int len = is.read(data);
String str = new String(data, 0, len);
- assertEquals("this is my command\n", str);
+ assertEquals("Mismatched data at iteration " + i, expected, str);
}
} finally {
c.disconnect();
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java b/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
index e6d6b41..649eace 100644
--- a/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
@@ -18,6 +18,8 @@
*/
package org.apache.sshd;
+import static org.apache.sshd.util.Utils.getFreePort;
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -31,11 +33,9 @@ import java.net.URL;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.JSchException;
-import com.jcraft.jsch.Session;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpVersion;
@@ -56,22 +56,27 @@ import org.apache.sshd.util.Utils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import static org.apache.sshd.util.Utils.getFreePort;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.Session;
/**
* Port forwarding tests
*/
public class PortForwardingLoadTest extends BaseTestSupport {
-
- private final org.slf4j.Logger log = LoggerFactory.getLogger(getClass());
-
+ private final Logger log = LoggerFactory.getLogger(getClass());
private SshServer sshd;
private int sshPort;
private int echoPort;
private IoAcceptor acceptor;
+ public PortForwardingLoadTest() {
+ super();
+ }
+
@Before
public void setUp() throws Exception {
sshd = SshServer.setUpDefaultServer();
@@ -119,74 +124,91 @@ public class PortForwardingLoadTest extends BaseTestSupport {
"longer Test Data. This is significantly longer Test Data. This is significantly "+
"longer Test Data. This is significantly longer Test Data. This is significantly "+
"longer Test Data. ";
- StringBuilder sb = new StringBuilder();
+ StringBuilder sb = new StringBuilder(PAYLOAD_TMP.length() * 1000);
for (int i = 0; i < 1000; i++) {
sb.append(PAYLOAD_TMP);
}
final String PAYLOAD = sb.toString();
- Session session = createSession();
- final ServerSocket ss = new ServerSocket();
- ss.setReuseAddress(true);
- ss.bind(new InetSocketAddress((InetAddress) null, 0));
- int forwardedPort = ss.getLocalPort();
- int sinkPort = session.setPortForwardingL(0, "localhost", forwardedPort);
- final AtomicInteger conCount = new AtomicInteger(0);
- new Thread() {
- @Override
- public void run() {
- try {
- for (int i = 0; i < NUM_ITERATIONS; ++i) {
- try(Socket s = ss.accept()) {
- conCount.incrementAndGet();
- InputStream is = s.getInputStream();
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ Session session = createSession();
+ try(final ServerSocket ss = new ServerSocket()) {
+ ss.setReuseAddress(true);
+ ss.bind(new InetSocketAddress((InetAddress) null, 0));
+ int forwardedPort = ss.getLocalPort();
+ int sinkPort = session.setPortForwardingL(0, "localhost", forwardedPort);
+ final AtomicInteger conCount = new AtomicInteger(0);
+
+ Thread tAcceptor = new Thread(getCurrentTestName() + "Acceptor") {
+ @SuppressWarnings("synthetic-access")
+ @Override
+ public void run() {
+ try {
byte[] buf = new byte[8192];
- int l;
- while (baos.size() < PAYLOAD.length() && (l = is.read(buf)) > 0) {
- baos.write(buf, 0, l);
- }
- if (!PAYLOAD.equals(baos.toString())) {
- assertEquals(PAYLOAD, baos.toString());
- }
- is = new ByteArrayInputStream(baos.toByteArray());
- OutputStream os = s.getOutputStream();
- while ((l = is.read(buf)) > 0) {
- os.write(buf, 0, l);
+ log.info("Started...");
+ for (int i = 0; i < NUM_ITERATIONS; ++i) {
+ try(Socket s = ss.accept()) {
+ conCount.incrementAndGet();
+
+ try(InputStream sockIn = s.getInputStream();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+
+ int l;
+ while ((baos.size() < PAYLOAD.length()) && ((l = sockIn.read(buf)) > 0)) {
+ baos.write(buf, 0, l);
+ }
+
+ assertEquals("Mismatched received data at iteration #" + i, PAYLOAD, baos.toString());
+
+ try(InputStream inputCopy = new ByteArrayInputStream(baos.toByteArray());
+ OutputStream sockOut = s.getOutputStream()) {
+
+ while ((l = sockIn.read(buf)) > 0) {
+ sockOut.write(buf, 0, l);
+ }
+ }
+ }
+ }
}
+ log.info("Done");
+ } catch (Exception e) {
+ log.error("Failed to complete run loop", e);
}
}
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }.start();
- Thread.sleep(50);
+ };
+ tAcceptor.start();
+ Thread.sleep(50);
+
+ byte[] buf = new byte[8192];
+ byte[] bytes = PAYLOAD.getBytes();
+ for (int i = 0; i < NUM_ITERATIONS; i++) {
+ log.info("Iteration {}", Integer.valueOf(i));
+ try(Socket s = new Socket("localhost", sinkPort);
+ OutputStream sockOut = s.getOutputStream()) {
- for ( int i = 0; i < NUM_ITERATIONS; i++) {
- Socket s = null;
- try {
- LoggerFactory.getLogger(getClass()).info("Iteration {}", i);
- s = new Socket("localhost", sinkPort);
- s.getOutputStream().write(PAYLOAD.getBytes());
- s.getOutputStream().flush();
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buf = new byte[8192];
- int l;
- while (baos.size() < PAYLOAD.length() && (l = s.getInputStream().read(buf)) > 0) {
- baos.write(buf, 0, l);
- }
- assertEquals(PAYLOAD, baos.toString());
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (s != null) {
- s.close();
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+ sockOut.write(bytes);
+ sockOut.flush();
+
+ try(InputStream sockIn = s.getInputStream();
+ ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length)) {
+ int l;
+ while ((baos.size() < PAYLOAD.length()) && ((l = sockIn.read(buf)) > 0)) {
+ baos.write(buf, 0, l);
+ }
+ assertEquals("Mismatched payload at iteration #" + i, PAYLOAD, baos.toString());
+ }
+ } catch (Exception e) {
+ log.error("Error in iteration #" + i, e);
}
}
+ session.delPortForwardingL(sinkPort);
+
+ ss.close();
+ tAcceptor.join(TimeUnit.SECONDS.toMillis(5L));
+ } finally {
+ session.disconnect();
}
- session.delPortForwardingL(sinkPort);
- ss.close();
}
@Test
@@ -199,72 +221,91 @@ public class PortForwardingLoadTest extends BaseTestSupport {
"longer Test Data. This is significantly longer Test Data. This is significantly "+
"longer Test Data. ";
Session session = createSession();
- final ServerSocket ss = new ServerSocket();
- ss.setReuseAddress(true);
- ss.bind(new InetSocketAddress((InetAddress) null, 0));
- int forwardedPort = ss.getLocalPort();
- int sinkPort = getFreePort();
- session.setPortForwardingR(sinkPort, "localhost", forwardedPort);
- final boolean started[] = new boolean[1];
- started[0] = false;
- final AtomicInteger conCount = new AtomicInteger(0);
-
- new Thread() {
- @Override
- public void run() {
- started[0] = true;
- try {
- for (int i = 0; i < NUM_ITERATIONS; ++i) {
- try(Socket s = ss.accept()) {
- conCount.incrementAndGet();
- s.getOutputStream().write(PAYLOAD.getBytes());
- s.getOutputStream().flush();
+ try (final ServerSocket ss = new ServerSocket()) {
+ ss.setReuseAddress(true);
+ ss.bind(new InetSocketAddress((InetAddress) null, 0));
+ int forwardedPort = ss.getLocalPort();
+ int sinkPort = getFreePort();
+ session.setPortForwardingR(sinkPort, "localhost", forwardedPort);
+ final boolean started[] = new boolean[1];
+ started[0] = false;
+ final AtomicInteger conCount = new AtomicInteger(0);
+
+ Thread tWriter = new Thread(getCurrentTestName() + "Writer") {
+ @SuppressWarnings("synthetic-access")
+ @Override
+ public void run() {
+ started[0] = true;
+ try {
+ byte[] bytes=PAYLOAD.getBytes();
+ for (int i = 0; i < NUM_ITERATIONS; ++i) {
+ try(Socket s = ss.accept()) {
+ conCount.incrementAndGet();
+
+ try(OutputStream sockOut=s.getOutputStream()) {
+ sockOut.write(bytes);
+ sockOut.flush();
+ }
+ }
+ }
+ } catch (Exception e) {
+ log.error("Failed to complete run loop", e);
}
}
+ };
+ tWriter.start();
+ Thread.sleep(50);
+ assertTrue("Server not started", started[0]);
+
+ final boolean lenOK[] = new boolean[NUM_ITERATIONS];
+ final boolean dataOK[] = new boolean[NUM_ITERATIONS];
+ byte b2[] = new byte[PAYLOAD.length()];
+ byte b1[] = new byte[b2.length / 2];
+
+ for (int i = 0; i < NUM_ITERATIONS; i++) {
+ final int ii = i;
+ try(Socket s = new Socket("localhost", sinkPort);
+ InputStream sockIn = s.getInputStream()) {
+
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+ int read1 = sockIn.read(b1);
+ String part1 = new String(b1, 0, read1);
+ Thread.sleep(50);
+
+ int read2 = sockIn.read(b2);
+ String part2 = new String(b2, 0, read2);
+ int totalRead = read1 + read2;
+ lenOK[ii] = PAYLOAD.length() == totalRead;
+
+ String readData = part1 + part2;
+ dataOK[ii] = PAYLOAD.equals(readData);
+ if (!lenOK[ii]) {
+ throw new IndexOutOfBoundsException("Mismatched length: expected=" + PAYLOAD.length() + ", actual=" + totalRead);
+ }
+
+ if (!dataOK[ii]) {
+ throw new IllegalStateException("Mismatched content");
+ }
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Failed to complete iteration #" + i, e);
}
}
- }.start();
- Thread.sleep(50);
- assertTrue("Server not started", started[0]);
-
- final boolean lenOK[] = new boolean[NUM_ITERATIONS];
- final boolean dataOK[] = new boolean[NUM_ITERATIONS];
- for ( int i = 0; i < NUM_ITERATIONS; i++) {
- final int ii = i;
- Socket s = null;
- try {
- s = new Socket("localhost", sinkPort);
- byte b1[] = new byte[PAYLOAD.length() / 2];
- byte b2[] = new byte[PAYLOAD.length()];
- int read1 = s.getInputStream().read(b1);
- Thread.sleep(50);
- int read2 = s.getInputStream().read(b2);
- lenOK[ii] = PAYLOAD.length() == read1 + read2;
- dataOK[ii] = PAYLOAD.equals(new String(b1, 0, read1) + new String(b2, 0, read2));
- if (!lenOK[ii] || !dataOK[ii] ) {
- throw new Exception("Bad data");
- }
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- if (s != null) {
- s.close();
- }
+ int ok = 0;
+ for (int i = 0; i < NUM_ITERATIONS; i++) {
+ ok += lenOK[i] ? 1 : 0;
}
+ Thread.sleep(50);
+ for (int i = 0; i < NUM_ITERATIONS; i++) {
+ assertTrue("Bad length at iteration " + i, lenOK[i]);
+ assertTrue("Bad data at iteration " + i, dataOK[i]);
+ }
+ session.delPortForwardingR(forwardedPort);
+ ss.close();
+ tWriter.join(TimeUnit.SECONDS.toMillis(5L));
+ } finally {
+ session.disconnect();
}
- int ok = 0;
- for (int i = 0; i < NUM_ITERATIONS; i++) {
- ok += lenOK[i] ? 1 : 0;
- }
- Thread.sleep(50);
- for (int i = 0; i < NUM_ITERATIONS; i++) {
- assertTrue(lenOK[i]);
- assertTrue(dataOK[i]);
- }
- session.delPortForwardingR(forwardedPort);
- ss.close();
}
@Test
@@ -303,49 +344,50 @@ public class PortForwardingLoadTest extends BaseTestSupport {
final int port = acceptor.getLocalAddress().getPort();
Session session = createSession();
-
- final int forwardedPort1 = session.setPortForwardingL(0, host, port);
- final int forwardedPort2 = getFreePort();
- session.setPortForwardingR(forwardedPort2, "localhost", forwardedPort1);
- System.err.println("URL: http://localhost:" + forwardedPort2);
-
-
- final CountDownLatch latch = new CountDownLatch(nbThread * nbDownloads * nbLoops);
-
- final Thread[] threads = new Thread[nbThread];
- final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>();
- for (int i = 0; i < threads.length; i++) {
- threads[i] = new Thread() {
- @Override
- public void run() {
- for (int j = 0; j < nbLoops; j++) {
- final MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
- final HttpClient client = new HttpClient(mgr);
- client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(100);
- client.getHttpConnectionManager().getParams().setMaxTotalConnections(1000);
- for (int i = 0; i < nbDownloads; i++) {
- try {
- checkHtmlPage(client, new URL("http://localhost:" + forwardedPort2 + path));
- } catch (Throwable e) {
- errors.add(e);
- } finally {
- latch.countDown();
- System.err.println("Remaining: " + latch.getCount());
+ try {
+ final int forwardedPort1 = session.setPortForwardingL(0, host, port);
+ final int forwardedPort2 = getFreePort();
+ session.setPortForwardingR(forwardedPort2, "localhost", forwardedPort1);
+ System.err.println("URL: http://localhost:" + forwardedPort2);
+
+ final CountDownLatch latch = new CountDownLatch(nbThread * nbDownloads * nbLoops);
+ final Thread[] threads = new Thread[nbThread];
+ final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>();
+ for (int i = 0; i < threads.length; i++) {
+ threads[i] = new Thread(getCurrentTestName() + "[" + i + "]") {
+ @Override
+ public void run() {
+ for (int j = 0; j < nbLoops; j++) {
+ final MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
+ final HttpClient client = new HttpClient(mgr);
+ client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(100);
+ client.getHttpConnectionManager().getParams().setMaxTotalConnections(1000);
+ for (int i = 0; i < nbDownloads; i++) {
+ try {
+ checkHtmlPage(client, new URL("http://localhost:" + forwardedPort2 + path));
+ } catch (Throwable e) {
+ errors.add(e);
+ } finally {
+ latch.countDown();
+ System.err.println("Remaining: " + latch.getCount());
+ }
}
+ mgr.shutdown();
}
- mgr.shutdown();
}
- }
- };
- }
- for (int i = 0; i < threads.length; i++) {
- threads[i].start();
- }
- latch.await();
- for (Throwable t : errors) {
- t.printStackTrace();
+ };
+ }
+ for (int i = 0; i < threads.length; i++) {
+ threads[i].start();
+ }
+ latch.await();
+ for (Throwable t : errors) {
+ t.printStackTrace();
+ }
+ assertEquals(0, errors.size());
+ } finally {
+ session.disconnect();
}
- assertEquals(0, errors.size());
}
protected Session createSession() throws JSchException {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java b/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
index 7f85d08..b70c973 100644
--- a/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
@@ -19,11 +19,13 @@
package org.apache.sshd;
import static org.apache.sshd.util.Utils.getFreePort;
+
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.HashSet;
import java.util.Set;
+import java.util.concurrent.TimeUnit;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoAcceptor;
@@ -32,6 +34,7 @@ import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.sshd.client.channel.ChannelDirectTcpip;
import org.apache.sshd.common.FactoryManager;
+import org.apache.sshd.common.FactoryManagerUtils;
import org.apache.sshd.common.SshdSocketAddress;
import org.apache.sshd.util.BaseTestSupport;
import org.apache.sshd.util.BogusForwardingFilter;
@@ -65,8 +68,8 @@ public class PortForwardingTest extends BaseTestSupport {
@Before
public void setUp() throws Exception {
sshd = SshServer.setUpDefaultServer();
- sshd.getProperties().put(FactoryManager.WINDOW_SIZE, "2048");
- sshd.getProperties().put(FactoryManager.MAX_PACKET_SIZE, "256");
+ FactoryManagerUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 2048);
+ FactoryManagerUtils.updateProperty(sshd, FactoryManager.MAX_PACKET_SIZE, 256);
sshd.setKeyPairProvider(Utils.createTestHostKeyProvider());
sshd.setShellFactory(new EchoShellFactory());
sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
@@ -89,7 +92,6 @@ public class PortForwardingTest extends BaseTestSupport {
acceptor.bind(new InetSocketAddress(0));
echoPort = acceptor.getLocalAddress().getPort();
this.acceptor = acceptor;
-
}
@After
@@ -108,22 +110,29 @@ public class PortForwardingTest extends BaseTestSupport {
@Test
public void testRemoteForwarding() throws Exception {
Session session = createSession();
+ try {
+ int forwardedPort = getFreePort();
+ session.setPortForwardingR(forwardedPort, "localhost", echoPort);
+ Thread.sleep(100);
+
+ try(Socket s = new Socket("localhost", forwardedPort)) {
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
- int forwardedPort = getFreePort();
- session.setPortForwardingR(forwardedPort, "localhost", echoPort);
- Thread.sleep(100);
-
- try(Socket s = new Socket("localhost", forwardedPort)) {
- s.getOutputStream().write("Hello".getBytes());
- s.getOutputStream().flush();
- byte[] buf = new byte[1024];
- int n = s.getInputStream().read(buf);
- String res = new String(buf, 0, n);
- assertEquals("Hello", res);
- }
+ String expected = getCurrentTestName();
+ byte[] bytes = expected.getBytes();
+ s.getOutputStream().write(bytes);
+ s.getOutputStream().flush();
- session.delPortForwardingR(forwardedPort);
- session.disconnect();
+ byte[] buf = new byte[bytes.length + Long.SIZE];
+ int n = s.getInputStream().read(buf);
+ String res = new String(buf, 0, n);
+ assertEquals("Mismatched data", expected, res);
+ }
+
+ session.delPortForwardingR(forwardedPort);
+ } finally {
+ session.disconnect();
+ }
}
@Test
@@ -134,12 +143,17 @@ public class PortForwardingTest extends BaseTestSupport {
SshdSocketAddress bound = session.startRemotePortForwarding(remote, local);
try(Socket s = new Socket(bound.getHostName(), bound.getPort())) {
- s.getOutputStream().write("Hello".getBytes());
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+ String expected = getCurrentTestName();
+ byte[] bytes = expected.getBytes();
+ s.getOutputStream().write(bytes);
s.getOutputStream().flush();
- byte[] buf = new byte[1024];
- int n = s.getInputStream().read(buf);
- String res = new String(buf, 0, n);
- assertEquals("Hello", res);
+
+ byte[] buf = new byte[bytes.length + Long.SIZE];
+ int n = s.getInputStream().read(buf);
+ String res = new String(buf, 0, n);
+ assertEquals("Mismatched data", expected, res);
}
session.stopRemotePortForwarding(remote);
@@ -154,15 +168,20 @@ public class PortForwardingTest extends BaseTestSupport {
SshdSocketAddress local = new SshdSocketAddress("localhost", echoPort);
SshdSocketAddress bound = session.startRemotePortForwarding(remote, local);
- byte[] buf = new byte[1024];
-
try(Socket s = new Socket(bound.getHostName(), bound.getPort())) {
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+ String expected = getCurrentTestName();
+ byte[] bytes = expected.getBytes();
+ byte[] buf = new byte[bytes.length + Long.SIZE];
+
for (int i = 0; i < 1000; i++) {
- s.getOutputStream().write("0123456789".getBytes());
+ s.getOutputStream().write(bytes);
s.getOutputStream().flush();
- int n = s.getInputStream().read(buf);
- String res = new String(buf, 0, n);
- assertEquals("0123456789", res);
+
+ int n = s.getInputStream().read(buf);
+ String res = new String(buf, 0, n);
+ assertEquals("Mismatched data at iteration #" + i, expected, res);
}
}
@@ -174,21 +193,29 @@ public class PortForwardingTest extends BaseTestSupport {
@Test
public void testLocalForwarding() throws Exception {
Session session = createSession();
+ try {
+ int forwardedPort = getFreePort();
+ session.setPortForwardingL(forwardedPort, "localhost", echoPort);
+
+ try(Socket s = new Socket("localhost", forwardedPort)) {
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
- int forwardedPort = getFreePort();
- session.setPortForwardingL(forwardedPort, "localhost", echoPort);
+ String expected = getCurrentTestName();
+ byte[] bytes = expected.getBytes();
- try(Socket s = new Socket("localhost", forwardedPort)) {
- s.getOutputStream().write("Hello".getBytes());
- s.getOutputStream().flush();
- byte[] buf = new byte[1024];
- int n = s.getInputStream().read(buf);
- String res = new String(buf, 0, n);
- assertEquals("Hello", res);
- }
+ s.getOutputStream().write(bytes);
+ s.getOutputStream().flush();
- session.delPortForwardingL(forwardedPort);
- session.disconnect();
+ byte[] buf = new byte[bytes.length + Long.SIZE];
+ int n = s.getInputStream().read(buf);
+ String res = new String(buf, 0, n);
+ assertEquals("Mismatched data", expected, res);
+ }
+
+ session.delPortForwardingL(forwardedPort);
+ } finally {
+ session.disconnect();
+ }
}
@Test
@@ -199,12 +226,18 @@ public class PortForwardingTest extends BaseTestSupport {
SshdSocketAddress bound = session.startLocalPortForwarding(local, remote);
try(Socket s = new Socket(bound.getHostName(), bound.getPort())) {
- s.getOutputStream().write("Hello".getBytes());
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+ String expected = getCurrentTestName();
+ byte[] bytes = expected.getBytes();
+
+ s.getOutputStream().write(bytes);
s.getOutputStream().flush();
- byte[] buf = new byte[1024];
- int n = s.getInputStream().read(buf);
- String res = new String(buf, 0, n);
- assertEquals("Hello", res);
+
+ byte[] buf = new byte[bytes.length + Long.SIZE];
+ int n = s.getInputStream().read(buf);
+ String res = new String(buf, 0, n);
+ assertEquals("Mismatched data", expected, res);
}
session.stopLocalPortForwarding(bound);
@@ -235,14 +268,19 @@ public class PortForwardingTest extends BaseTestSupport {
SshdSocketAddress remote = new SshdSocketAddress("localhost", echoPort);
SshdSocketAddress bound = session.startLocalPortForwarding(local, remote);
- byte[] buf = new byte[1024];
+ String expected = getCurrentTestName();
+ byte[] bytes = expected.getBytes();
+ byte[] buf = new byte[bytes.length + Long.SIZE];
try(Socket s = new Socket(bound.getHostName(), bound.getPort())) {
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
for (int i = 0; i < 1000; i++) {
- s.getOutputStream().write("Hello".getBytes());
+ s.getOutputStream().write(bytes);
s.getOutputStream().flush();
- int n = s.getInputStream().read(buf);
- String res = new String(buf, 0, n);
- assertEquals("Hello", res);
+
+ int n = s.getInputStream().read(buf);
+ String res = new String(buf, 0, n);
+ assertEquals("Mismatched data at iteration #" + i, expected, res);
}
}
@@ -259,13 +297,17 @@ public class PortForwardingTest extends BaseTestSupport {
try(ChannelDirectTcpip channel = session.createDirectTcpipChannel(local, remote)) {
channel.open().await();
-
- channel.getInvertedIn().write("Hello".getBytes());
+
+ String expected = getCurrentTestName();
+ byte[] bytes = expected.getBytes();
+
+ channel.getInvertedIn().write(bytes);
channel.getInvertedIn().flush();
- byte[] buf = new byte[1024];
- int n = channel.getInvertedOut().read(buf);
- String res = new String(buf, 0, n);
- assertEquals("Hello", res);
+
+ byte[] buf = new byte[bytes.length + Long.SIZE];
+ int n = channel.getInvertedOut().read(buf);
+ String res = new String(buf, 0, n);
+ assertEquals("Mismatched data", expected, res);
channel.close(false);
}
@@ -276,41 +318,45 @@ public class PortForwardingTest extends BaseTestSupport {
@Test(timeout = 20000)
public void testRemoteForwardingWithDisconnect() throws Exception {
Session session = createSession();
-
- // 1. Create a Port Forward
- int forwardedPort = getFreePort();
- session.setPortForwardingR(forwardedPort, "localhost", echoPort);
-
- // 2. Establish a connection through it
- try(Socket s = new Socket("localhost", forwardedPort)) {
- // 3. Simulate the client going away
- rudelyDisconnectJschSession(session);
+ try {
+ // 1. Create a Port Forward
+ int forwardedPort = getFreePort();
+ session.setPortForwardingR(forwardedPort, "localhost", echoPort);
- // 4. Make sure the NIOprocessor is not stuck
- {
- Thread.sleep(1000);
- // from here, we need to check all the threads running and find a
- // "NioProcessor-"
- // that is stuck on a PortForward.dispose
- ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
- while (root.getParent() != null) {
- root = root.getParent();
- }
- boolean stuck;
- do {
- stuck = false;
- for (Thread t : findThreads(root, "NioProcessor-")) {
- stuck = true;
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // ignored
+ // 2. Establish a connection through it
+ try(Socket s = new Socket("localhost", forwardedPort)) {
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+ // 3. Simulate the client going away
+ rudelyDisconnectJschSession(session);
+
+ // 4. Make sure the NIOprocessor is not stuck
+ {
+ Thread.sleep(1000);
+ // from here, we need to check all the threads running and find a
+ // "NioProcessor-"
+ // that is stuck on a PortForward.dispose
+ ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
+ while (root.getParent() != null) {
+ root = root.getParent();
}
- } while (stuck);
+ boolean stuck;
+ do {
+ stuck = false;
+ for (Thread t : findThreads(root, "NioProcessor-")) {
+ stuck = true;
+ }
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // ignored
+ }
+ } while (stuck);
+ }
+
+ session.delPortForwardingR(forwardedPort);
}
-
- session.delPortForwardingR(forwardedPort);
+ } finally {
session.disconnect();
}
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java b/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java
index ad073ec..dd1bc2f 100644
--- a/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java
@@ -19,9 +19,12 @@
package org.apache.sshd;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
+import java.util.concurrent.TimeUnit;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.service.IoAcceptor;
@@ -97,15 +100,24 @@ public class ProxyTest extends BaseTestSupport {
try(ClientSession session = createNativeSession()) {
SshdSocketAddress dynamic = session.startDynamicPortForwarding(new SshdSocketAddress("localhost", 0));
- byte[] buf = new byte[1024];
- for (int i = 0, l = 0; i < 10; i++) {
+ String expected = getCurrentTestName();
+ byte[] bytes = expected.getBytes();
+ byte[] buf = new byte[bytes.length + Long.SIZE];
+ for (int i = 0; i < 10; i++) {
try(Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("localhost", dynamic.getPort())))) {
s.connect(new InetSocketAddress("localhost", echoPort));
- s.getOutputStream().write("foo".getBytes());
- s.getOutputStream().flush();
- l = s.getInputStream().read(buf);
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+ try(OutputStream sockOut = s.getOutputStream();
+ InputStream sockIn = s.getInputStream()) {
+
+ sockOut.write(bytes);
+ sockOut.flush();
+
+ int l = sockIn.read(buf);
+ assertEquals("Mismatched data at iteration " + i, expected, new String(buf, 0, l));
+ }
}
- assertEquals("foo", new String(buf, 0, l));
}
session.stopDynamicPortForwarding(dynamic);
@@ -113,8 +125,9 @@ public class ProxyTest extends BaseTestSupport {
try {
try(Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("localhost", dynamic.getPort())))) {
s.connect(new InetSocketAddress("localhost", echoPort));
- s.getOutputStream().write("foo".getBytes());
- fail("Expected IOException");
+ s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+ s.getOutputStream().write(bytes);
+ fail("Unexpected success to write proxy data");
}
} catch (IOException e) {
// expected
@@ -137,5 +150,3 @@ public class ProxyTest extends BaseTestSupport {
return session;
}
}
-
-