org.apache.sshd.common.FactoryManager Java Examples

The following examples show how to use org.apache.sshd.common.FactoryManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NetconfSessionMinaImpl.java    From onos with Apache License 2.0 8 votes vote down vote up
private void startClient() throws IOException {
    log.info("Creating NETCONF session to {}",
            deviceInfo.getDeviceId());

    client = SshClient.setUpDefaultClient();
    if (idleTimeout != NetconfControllerImpl.netconfIdleTimeout) {
        client.getProperties().putIfAbsent(FactoryManager.IDLE_TIMEOUT,
                TimeUnit.SECONDS.toMillis(idleTimeout));
        client.getProperties().putIfAbsent(FactoryManager.NIO2_READ_TIMEOUT,
                TimeUnit.SECONDS.toMillis(idleTimeout + 15L));
    }
    client.start();
    client.setKeyPairProvider(new SimpleGeneratorHostKeyProvider());
    startSession();

    disconnected = false;
}
 
Example #2
Source File: AsyncAuthTestBase.java    From termd with Apache License 2.0 7 votes vote down vote up
public void startServer(Integer timeout) throws Exception {
  if (server != null) {
    throw failure("Server already started");
  }
  server = SshServer.setUpDefaultServer();
  if (timeout != null) {
    server.getProperties().put(FactoryManager.AUTH_TIMEOUT, timeout.toString());
  }
  server.setPort(5000);
  server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
  server.setPasswordAuthenticator(new PasswordAuthenticator() {
    @Override
    public boolean authenticate(String username, String password, ServerSession session) throws PasswordChangeRequiredException {
      return authenticator.authenticate(username, password, session);
    }
  });
  server.setShellFactory(new EchoShellFactory());
  server.setServiceFactories(Arrays.asList(ServerConnectionServiceFactory.INSTANCE, AsyncUserAuthServiceFactory.INSTANCE));
  server.start();
}
 
Example #3
Source File: KeepAliveTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshd = setupTestServer();
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.IDLE_TIMEOUT, TIMEOUT);
    sshd.setShellFactory(new TestEchoShellFactory());
    sshd.start();
    port = sshd.getPort();
}
 
Example #4
Source File: SSHServerTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 10000L)
public void call() throws Exception {
    final SshClient client = SshClient.setUpDefaultClient();
    client.start();
    try {
        final ClientSession session = client.connect("jonathan", "localhost", 4222).verify().getSession();
        session.addPasswordIdentity("secret");
        session.auth().verify(FactoryManager.DEFAULT_AUTH_TIMEOUT);

        final ClientChannel channel = session.createChannel("shell");
        ByteArrayOutputStream sent = new ByteArrayOutputStream();
        PipedOutputStream pipedIn = new TeePipedOutputStream(sent);
        channel.setIn(new PipedInputStream(pipedIn));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        channel.setOut(out);
        channel.setErr(err);
        channel.open();

        pipedIn.write("properties\r\n".getBytes());
        pipedIn.flush();

        pipedIn.write("exit\r\n".getBytes());
        pipedIn.flush();

        channel.waitFor(Collections.singleton(ClientChannelEvent.CLOSED), 0);
        channel.close(false);
        client.stop();

        assertTrue(new String(sent.toByteArray()).contains("properties\r\nexit\r\n"));
        assertTrue(new String(out.toByteArray()).contains("ServerService(id=ssh)"));
    } catch (Exception e) {
        e.printStackTrace();
        fail();
    }
}
 
Example #5
Source File: AsyncAuthTestBase.java    From termd with Apache License 2.0 5 votes vote down vote up
public void startServer(Integer timeout) throws Exception {
  if (server != null) {
    throw failure("Server already started");
  }
  server = SshServer.setUpDefaultServer();
  if (timeout != null) {
    server.getProperties().put(FactoryManager.AUTH_TIMEOUT, timeout.toString());
  }
  server.setPort(5000);
  server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
  server.setPasswordAuthenticator((username, password, sess) -> authenticator.authenticate(username, password, sess));
  server.setShellFactory(new EchoShellFactory());
  server.setServiceFactories(Arrays.asList(ServerConnectionServiceFactory.INSTANCE, AsyncUserAuthServiceFactory.INSTANCE));
  server.start();
}
 
Example #6
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
protected ClientSession createNativeSession() throws Exception {
    client = setupTestClient();
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 2048);
    PropertyResolverUtils.updateProperty(client, FactoryManager.MAX_PACKET_SIZE, 256);
    client.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
    client.start();

    ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshPort).verify(7L, TimeUnit.SECONDS).getSession();
    session.addPasswordIdentity(getCurrentTestName());
    session.auth().verify(11L, TimeUnit.SECONDS);
    return session;
}
 
Example #7
Source File: ServerTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticationTimeout() throws Exception {
    final long testAuthTimeout = TimeUnit.SECONDS.toMillis(5L);
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.AUTH_TIMEOUT, testAuthTimeout);

    sshd.start();
    client.start();
    try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()).verify(7L, TimeUnit.SECONDS).getSession()) {
        Collection<ClientSession.ClientSessionEvent> res = s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED), 2L * testAuthTimeout);
        assertTrue("Session should be closed: " + res,
                   res.containsAll(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH)));
    } finally {
        client.stop();
    }
}
 
Example #8
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 5 votes vote down vote up
protected void setUp(long bytesLimit, long timeLimit, long packetsLimit) throws Exception {
    sshd = setupTestServer();
    if (bytesLimit > 0L) {
        PropertyResolverUtils.updateProperty(sshd, FactoryManager.REKEY_BYTES_LIMIT, bytesLimit);
    }
    if (timeLimit > 0L) {
        PropertyResolverUtils.updateProperty(sshd, FactoryManager.REKEY_TIME_LIMIT, timeLimit);
    }
    if (packetsLimit > 0L) {
        PropertyResolverUtils.updateProperty(sshd, FactoryManager.REKEY_PACKETS_LIMIT, packetsLimit);
    }

    sshd.start();
    port = sshd.getPort();
}
 
Example #9
Source File: KeepAliveTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshd = setupTestServer();
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.IDLE_TIMEOUT, TIMEOUT);
    sshd.setShellFactory(new TestEchoShellFactory());
    sshd.start();
    port = sshd.getPort();
}
 
Example #10
Source File: AsyncAuthTestBase.java    From aesh-readline with Apache License 2.0 5 votes vote down vote up
public void startServer(Integer timeout) throws Exception {
  if (server != null) {
    throw failure("Server already started");
  }
  server = SshServer.setUpDefaultServer();
  if (timeout != null) {
    server.setProperties(Collections.singletonMap(FactoryManager.AUTH_TIMEOUT, timeout.toString()));
  }
  server.setPort(5000);
  server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(new File("hostkey.ser").toPath()));
  server.setPasswordAuthenticator((username, password, sess) -> authenticator.authenticate(username, password, sess));
  server.setShellFactory(new EchoShellFactory());
  server.setServiceFactories(Arrays.asList(ServerConnectionServiceFactory.INSTANCE, AsyncUserAuthServiceFactory.INSTANCE));
  server.start();
}
 
Example #11
Source File: KeyReExchangeTest.java    From termd with Apache License 2.0 5 votes vote down vote up
protected void setUp(long bytesLimit, long timeLimit, long packetsLimit) throws Exception {
    sshd = setupTestServer();
    if (bytesLimit > 0L) {
        PropertyResolverUtils.updateProperty(sshd, FactoryManager.REKEY_BYTES_LIMIT, bytesLimit);
    }
    if (timeLimit > 0L) {
        PropertyResolverUtils.updateProperty(sshd, FactoryManager.REKEY_TIME_LIMIT, timeLimit);
    }
    if (packetsLimit > 0L) {
        PropertyResolverUtils.updateProperty(sshd, FactoryManager.REKEY_PACKETS_LIMIT, packetsLimit);
    }

    sshd.start();
    port = sshd.getPort();
}
 
Example #12
Source File: ServerTest.java    From termd with Apache License 2.0 5 votes vote down vote up
@Test
public void testAuthenticationTimeout() throws Exception {
    final long testAuthTimeout = TimeUnit.SECONDS.toMillis(5L);
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.AUTH_TIMEOUT, testAuthTimeout);

    sshd.start();
    client.start();
    try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()).verify(7L, TimeUnit.SECONDS).getSession()) {
        Collection<ClientSession.ClientSessionEvent> res = s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED), 2L * testAuthTimeout);
        assertTrue("Session should be closed: " + res,
                   res.containsAll(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH)));
    } finally {
        client.stop();
    }
}
 
Example #13
Source File: PortForwardingTest.java    From termd with Apache License 2.0 5 votes vote down vote up
protected ClientSession createNativeSession() throws Exception {
    client = setupTestClient();
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 2048);
    PropertyResolverUtils.updateProperty(client, FactoryManager.MAX_PACKET_SIZE, 256);
    client.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
    client.start();

    ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshPort).verify(7L, TimeUnit.SECONDS).getSession();
    session.addPasswordIdentity(getCurrentTestName());
    session.auth().verify(11L, TimeUnit.SECONDS);
    return session;
}
 
Example #14
Source File: WindowTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test
public void testWindowConsumptionWithDirectStreams() throws Exception {
    sshd.setShellFactory(new AsyncEchoShellFactory());
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);

    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ChannelShell channel = session.createShellChannel();
             PipedInputStream inPis = new PipedInputStream();
             PipedOutputStream inPos = new PipedOutputStream(inPis);
             PipedInputStream outPis = new PipedInputStream();
             PipedOutputStream outPos = new PipedOutputStream(outPis)) {

            channel.setIn(inPis);
            channel.setOut(outPos);
            channel.open().verify(7L, TimeUnit.SECONDS);

            try (Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
                Window clientLocal = channel.getLocalWindow();
                Window clientRemote = channel.getRemoteWindow();
                Window serverLocal = serverChannel.getLocalWindow();
                Window serverRemote = serverChannel.getRemoteWindow();

                final String message = "0123456789";
                final int nbMessages = 500;

                try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(inPos));
                     BufferedReader reader = new BufferedReader(new InputStreamReader(outPis))) {
                    for (int i = 0; i < nbMessages; i++) {
                        writer.write(message);
                        writer.write('\n');
                        writer.flush();

                        waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));

                        String line = reader.readLine();
                        assertEquals("Mismatched message at line #" + i, message, line);

                        waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));
                        waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local", TimeUnit.SECONDS.toMillis(3L));
                    }
                }
            }
        }
    } finally {
        client.stop();
    }
}
 
Example #15
Source File: NettyIoServiceFactoryFactory.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public IoServiceFactory create(FactoryManager manager) {
  return new NettyIoServiceFactory(eventLoopGroup, handlerBridge);
}
 
Example #16
Source File: TestServiceFactory.java    From termd with Apache License 2.0 4 votes vote down vote up
public TestServiceFactory(FactoryManager factoryManager, ExecutorService service, boolean shutdownOnExit) {
  super(factoryManager, service, shutdownOnExit);
}
 
Example #17
Source File: TestIoServiceFactoryFactory.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public IoServiceFactory create(FactoryManager manager) {
  return new TestServiceFactory(manager, getExecutorService(), isShutdownOnExit());
}
 
Example #18
Source File: LoadTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("checkstyle:nestedtrydepth")
protected void runClient(String msg) throws Exception {
    try (SshClient client = setupTestClient()) {
        PropertyResolverUtils.updateProperty(client, FactoryManager.MAX_PACKET_SIZE, 1024 * 16);
        PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024 * 8);
        client.setKeyExchangeFactories(Arrays.asList(
                ClientBuilder.DH2KEX.transform(BuiltinDHFactories.dhg1)));
        client.setCipherFactories(Arrays.<NamedFactory<Cipher>>asList(BuiltinCiphers.blowfishcbc));
        client.start();
        try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
            session.addPasswordIdentity(getCurrentTestName());
            session.auth().verify(5L, TimeUnit.SECONDS);

            try (ByteArrayOutputStream out = new ByteArrayOutputStream();
                 ByteArrayOutputStream err = new ByteArrayOutputStream();
                 ClientChannel channel = session.createChannel(Channel.CHANNEL_SHELL)) {
                channel.setOut(out);
                channel.setErr(err);

                try {
                    channel.open().verify(9L, TimeUnit.SECONDS);
                    try (OutputStream pipedIn = channel.getInvertedIn()) {
                        msg += "\nexit\n";
                        pipedIn.write(msg.getBytes(StandardCharsets.UTF_8));
                        pipedIn.flush();
                    }

                    Collection<ClientChannelEvent> result =
                            channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L));
                    assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT));
                } finally {
                    channel.close(false);
                }

                assertArrayEquals("Mismatched message data", msg.getBytes(StandardCharsets.UTF_8), out.toByteArray());
            }
        } finally {
            client.stop();
        }
    }
}
 
Example #19
Source File: WindowTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test
public void testWindowConsumptionWithInvertedStreams() throws Exception {
    sshd.setShellFactory(new AsyncEchoShellFactory());
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ChannelShell channel = session.createShellChannel()) {
            channel.open().verify(5L, TimeUnit.SECONDS);

            try (Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
                Window clientLocal = channel.getLocalWindow();
                Window clientRemote = channel.getRemoteWindow();
                Window serverLocal = serverChannel.getLocalWindow();
                Window serverRemote = serverChannel.getRemoteWindow();

                final String message = "0123456789";
                final int nbMessages = 500;

                try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(channel.getInvertedIn()));
                     BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInvertedOut()))) {

                    for (int i = 0; i < nbMessages; i++) {
                        writer.write(message);
                        writer.write("\n");
                        writer.flush();

                        waitForWindowNotEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));

                        String line = reader.readLine();
                        assertEquals("Mismatched message at line #" + i, message, line);

                        waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));
                        waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local", TimeUnit.SECONDS.toMillis(3L));
                    }
                }
            }
        }
    } finally {
        client.stop();
    }
}
 
Example #20
Source File: PortForwardingTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshd = setupTestServer();
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 2048);
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.MAX_PACKET_SIZE, 256);
    sshd.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
    sshd.start();

    if (!requestsQ.isEmpty()) {
        requestsQ.clear();
    }

    final TcpipForwarderFactory factory = ValidateUtils.checkNotNull(sshd.getTcpipForwarderFactory(), "No TcpipForwarderFactory");
    sshd.setTcpipForwarderFactory(new TcpipForwarderFactory() {
        private final Class<?>[] interfaces = {TcpipForwarder.class};
        private final Map<String, String> method2req = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER) {
            private static final long serialVersionUID = 1L;    // we're not serializing it...

            {
                put("localPortForwardingRequested", TcpipForwardHandler.REQUEST);
                put("localPortForwardingCancelled", CancelTcpipForwardHandler.REQUEST);
            }
        };

        @Override
        public TcpipForwarder create(ConnectionService service) {
            Thread thread = Thread.currentThread();
            ClassLoader cl = thread.getContextClassLoader();

            final TcpipForwarder forwarder = factory.create(service);
            return (TcpipForwarder) Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() {
                @SuppressWarnings("synthetic-access")
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result = method.invoke(forwarder, args);
                    String name = method.getName();
                    String request = method2req.get(name);
                    if (GenericUtils.length(request) > 0) {
                        if (requestsQ.offer(request)) {
                            log.info("Signal " + request);
                        } else {
                            log.error("Failed to offer request=" + request);
                        }
                    }
                    return result;
                }
            });
        }
    });
    sshPort = sshd.getPort();

    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setHandler(new IoHandlerAdapter() {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            IoBuffer recv = (IoBuffer) message;
            IoBuffer sent = IoBuffer.allocate(recv.remaining());
            sent.put(recv);
            sent.flip();
            session.write(sent);
        }
    });
    acceptor.setReuseAddress(true);
    acceptor.bind(new InetSocketAddress(0));
    echoPort = acceptor.getLocalAddress().getPort();
    this.acceptor = acceptor;
}
 
Example #21
Source File: WindowTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test
public void testWindowConsumptionWithAsyncStreams() throws Exception {
    sshd.setShellFactory(new AsyncEchoShellFactory());
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);

    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ChannelShell channel = session.createShellChannel()) {
            channel.setStreaming(ClientChannel.Streaming.Async);
            channel.open().verify(5L, TimeUnit.SECONDS);

            try (Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
                Window clientLocal = channel.getLocalWindow();
                Window clientRemote = channel.getRemoteWindow();
                Window serverLocal = serverChannel.getLocalWindow();
                Window serverRemote = serverChannel.getRemoteWindow();

                final String message = "0123456789\n";
                final byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
                final int nbMessages = 500;
                IoOutputStream output = channel.getAsyncIn();
                IoInputStream input = channel.getAsyncOut();
                for (int i = 0; i < nbMessages; i++) {
                    Buffer buffer = new ByteArrayBuffer(bytes);
                    output.write(buffer).verify(5L, TimeUnit.SECONDS);

                    waitForWindowNotEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));

                    Buffer buf = new ByteArrayBuffer(16);
                    IoReadFuture future = input.read(buf);
                    future.verify(5L, TimeUnit.SECONDS);
                    assertEquals("Mismatched available data at line #" + i, message.length(), buf.available());
                    assertEquals("Mismatched data at line #" + i, message, new String(buf.array(), buf.rpos(), buf.available()));

                    waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));
                    waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local", TimeUnit.SECONDS.toMillis(3L));
                }
            }
        }
    } finally {
        client.stop();
    }
}
 
Example #22
Source File: WindowTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test
public void testWindowConsumptionWithDirectStreams() throws Exception {
    sshd.setShellFactory(new AsyncEchoShellFactory());
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);

    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ChannelShell channel = session.createShellChannel();
             PipedInputStream inPis = new PipedInputStream();
             PipedOutputStream inPos = new PipedOutputStream(inPis);
             PipedInputStream outPis = new PipedInputStream();
             PipedOutputStream outPos = new PipedOutputStream(outPis)) {

            channel.setIn(inPis);
            channel.setOut(outPos);
            channel.open().verify(7L, TimeUnit.SECONDS);

            try (Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
                Window clientLocal = channel.getLocalWindow();
                Window clientRemote = channel.getRemoteWindow();
                Window serverLocal = serverChannel.getLocalWindow();
                Window serverRemote = serverChannel.getRemoteWindow();

                final String message = "0123456789";
                final int nbMessages = 500;

                try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(inPos));
                     BufferedReader reader = new BufferedReader(new InputStreamReader(outPis))) {
                    for (int i = 0; i < nbMessages; i++) {
                        writer.write(message);
                        writer.write('\n');
                        writer.flush();

                        waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));

                        String line = reader.readLine();
                        assertEquals("Mismatched message at line #" + i, message, line);

                        waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));
                        waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local", TimeUnit.SECONDS.toMillis(3L));
                    }
                }
            }
        }
    } finally {
        client.stop();
    }
}
 
Example #23
Source File: WindowTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test
public void testWindowConsumptionWithInvertedStreams() throws Exception {
    sshd.setShellFactory(new AsyncEchoShellFactory());
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);
    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ChannelShell channel = session.createShellChannel()) {
            channel.open().verify(5L, TimeUnit.SECONDS);

            try (Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
                Window clientLocal = channel.getLocalWindow();
                Window clientRemote = channel.getRemoteWindow();
                Window serverLocal = serverChannel.getLocalWindow();
                Window serverRemote = serverChannel.getRemoteWindow();

                final String message = "0123456789";
                final int nbMessages = 500;

                try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(channel.getInvertedIn()));
                     BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInvertedOut()))) {

                    for (int i = 0; i < nbMessages; i++) {
                        writer.write(message);
                        writer.write("\n");
                        writer.flush();

                        waitForWindowNotEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));

                        String line = reader.readLine();
                        assertEquals("Mismatched message at line #" + i, message, line);

                        waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));
                        waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local", TimeUnit.SECONDS.toMillis(3L));
                    }
                }
            }
        }
    } finally {
        client.stop();
    }
}
 
Example #24
Source File: TestIoServiceFactoryFactory.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public IoServiceFactory create(FactoryManager manager) {
  return new TestServiceFactory(manager, getExecutorService(), isShutdownOnExit());
}
 
Example #25
Source File: WindowTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Test
public void testWindowConsumptionWithAsyncStreams() throws Exception {
    sshd.setShellFactory(new AsyncEchoShellFactory());
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
    PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);

    client.start();

    try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) {
        session.addPasswordIdentity(getCurrentTestName());
        session.auth().verify(5L, TimeUnit.SECONDS);

        try (ChannelShell channel = session.createShellChannel()) {
            channel.setStreaming(ClientChannel.Streaming.Async);
            channel.open().verify(5L, TimeUnit.SECONDS);

            try (Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
                Window clientLocal = channel.getLocalWindow();
                Window clientRemote = channel.getRemoteWindow();
                Window serverLocal = serverChannel.getLocalWindow();
                Window serverRemote = serverChannel.getRemoteWindow();

                final String message = "0123456789\n";
                final byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
                final int nbMessages = 500;
                IoOutputStream output = channel.getAsyncIn();
                IoInputStream input = channel.getAsyncOut();
                for (int i = 0; i < nbMessages; i++) {
                    Buffer buffer = new ByteArrayBuffer(bytes);
                    output.write(buffer).verify(5L, TimeUnit.SECONDS);

                    waitForWindowNotEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));

                    Buffer buf = new ByteArrayBuffer(16);
                    IoReadFuture future = input.read(buf);
                    future.verify(5L, TimeUnit.SECONDS);
                    assertEquals("Mismatched available data at line #" + i, message.length(), buf.available());
                    assertEquals("Mismatched data at line #" + i, message, new String(buf.array(), buf.rpos(), buf.available()));

                    waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L));
                    waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local", TimeUnit.SECONDS.toMillis(3L));
                }
            }
        }
    } finally {
        client.stop();
    }
}
 
Example #26
Source File: PortForwardingTest.java    From termd with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    sshd = setupTestServer();
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 2048);
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.MAX_PACKET_SIZE, 256);
    sshd.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
    sshd.start();

    if (!requestsQ.isEmpty()) {
        requestsQ.clear();
    }

    final TcpipForwarderFactory factory = ValidateUtils.checkNotNull(sshd.getTcpipForwarderFactory(), "No TcpipForwarderFactory");
    sshd.setTcpipForwarderFactory(new TcpipForwarderFactory() {
        private final Class<?>[] interfaces = {TcpipForwarder.class};
        private final Map<String, String> method2req = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER) {
            private static final long serialVersionUID = 1L;    // we're not serializing it...

            {
                put("localPortForwardingRequested", TcpipForwardHandler.REQUEST);
                put("localPortForwardingCancelled", CancelTcpipForwardHandler.REQUEST);
            }
        };

        @Override
        public TcpipForwarder create(ConnectionService service) {
            Thread thread = Thread.currentThread();
            ClassLoader cl = thread.getContextClassLoader();

            final TcpipForwarder forwarder = factory.create(service);
            return (TcpipForwarder) Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() {
                @SuppressWarnings("synthetic-access")
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result = method.invoke(forwarder, args);
                    String name = method.getName();
                    String request = method2req.get(name);
                    if (GenericUtils.length(request) > 0) {
                        if (requestsQ.offer(request)) {
                            log.info("Signal " + request);
                        } else {
                            log.error("Failed to offer request=" + request);
                        }
                    }
                    return result;
                }
            });
        }
    });
    sshPort = sshd.getPort();

    NioSocketAcceptor acceptor = new NioSocketAcceptor();
    acceptor.setHandler(new IoHandlerAdapter() {
        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            IoBuffer recv = (IoBuffer) message;
            IoBuffer sent = IoBuffer.allocate(recv.remaining());
            sent.put(recv);
            sent.flip();
            session.write(sent);
        }
    });
    acceptor.setReuseAddress(true);
    acceptor.bind(new InetSocketAddress(0));
    echoPort = acceptor.getLocalAddress().getPort();
    this.acceptor = acceptor;
}
 
Example #27
Source File: NettyIoServiceFactoryFactory.java    From termd with Apache License 2.0 4 votes vote down vote up
@Override
public IoServiceFactory create(FactoryManager manager) {
  return new NettyIoServiceFactory(eventLoopGroup, handlerBridge);
}
 
Example #28
Source File: TestRemoteUploadTarget.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testConnectionRetry() throws Exception {
  FileRefTestUtil.writePredefinedTextToFile(testFolder.getRoot());
  Record record = createRecord();

  File targetFile = new File(testFolder.getRoot(), "target.txt");

  path = testFolder.getRoot().getAbsolutePath();
  setupServer(path, true);

  RemoteUploadTarget target = new RemoteUploadTarget(getBean(
      scheme.name() + "://localhost:" + port + "/",
      true,
      DataFormat.WHOLE_FILE,
      targetFile.getName(),
      WholeFileExistsAction.TO_ERROR
  ));
  TargetRunner runner = new TargetRunner.Builder(RemoteUploadDTarget.class, target).build();
  // No connections at first
  if (scheme == Scheme.sftp) {
    Assert.assertEquals(0, opened.get());
    Assert.assertEquals(0, closed.get());
  } else if (scheme == Scheme.ftp) {
    Assert.assertEquals(0, ftpServer.getServerContext().getFtpStatistics().getCurrentConnectionNumber());
  }
  runner.runInit();
  // Now we've made one connection
  if (scheme == Scheme.sftp) {
    Assert.assertEquals(1, opened.get());
  } else if (scheme == Scheme.ftp) {
    Assert.assertEquals(1, ftpServer.getServerContext().getFtpStatistics().getCurrentConnectionNumber());
  }
  // Set timeout after being idle to be really quick (1ms)
  if (scheme == Scheme.sftp) {
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.IDLE_TIMEOUT, 1);
  } else if (scheme == Scheme.ftp) {
    ftpServer.getServerContext().getListeners().get("default").getActiveSessions().iterator().next().setMaxIdleTime(1);
  }
  // Wait until that one connection has been closed
  if (scheme == Scheme.sftp) {
    await().atMost(10, TimeUnit.SECONDS).until(() -> Assert.assertEquals(1, closed.get()));
    Assert.assertEquals(1, closed.get());
  } else if (scheme == Scheme.ftp) {
    await().atMost(10, TimeUnit.SECONDS).until(
        () -> Assert.assertEquals(0, ftpServer.getServerContext().getFtpStatistics().getCurrentConnectionNumber()));
    Assert.assertEquals(0, ftpServer.getServerContext().getFtpStatistics().getCurrentConnectionNumber());
  }
  if (scheme == Scheme.sftp) {
    // Unset the timeout config for SFTP because it's global
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.IDLE_TIMEOUT, FactoryManager.DEFAULT_IDLE_TIMEOUT);
  }
  runner.runWrite(Collections.singletonList(record));
  // Now we've opened a new connection
  if (scheme == Scheme.sftp) {
    Assert.assertEquals(2, opened.get());
  } else if (scheme == Scheme.ftp) {
    Assert.assertEquals(1, ftpServer.getServerContext().getFtpStatistics().getCurrentConnectionNumber());
    Assert.assertEquals(2, ftpServer.getServerContext().getFtpStatistics().getTotalConnectionNumber());
  }
  verifyTargetFile(targetFile);
  destroyAndValidate(runner);
}
 
Example #29
Source File: TestRemoteDownloadSource.java    From datacollector with Apache License 2.0 4 votes vote down vote up
@Test
public void testConnectionRetry() throws Exception {
  path = "remote-download-source/parseNoError";
  setupServer(path, false);

  RemoteDownloadSource origin = new TestRemoteDownloadSourceBuilder(scheme, port).build();
  SourceRunner runner = new SourceRunner.Builder(RemoteDownloadDSource.class, origin)
      .addOutputLane("lane")
      .build();
  // No connections at first
  if (scheme == Scheme.sftp) {
    Assert.assertEquals(0, opened.get());
    Assert.assertEquals(0, closed.get());
  } else if (scheme == Scheme.ftp) {
    Assert.assertEquals(0, ftpServer.getServerContext().getFtpStatistics().getCurrentConnectionNumber());
  }
  runner.runInit();
  // Now we've made one connection
  if (scheme == Scheme.sftp) {
    Assert.assertEquals(1, opened.get());
  } else if (scheme == Scheme.ftp) {
    Assert.assertEquals(1, ftpServer.getServerContext().getFtpStatistics().getCurrentConnectionNumber());
  }
  // Set timeout after being idle to be really quick (1ms)
  if (scheme == Scheme.sftp) {
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.IDLE_TIMEOUT, 1);
  } else if (scheme == Scheme.ftp) {
    ftpServer.getServerContext().getListeners().get("default").getActiveSessions().iterator().next().setMaxIdleTime(1);
  }
  // Wait until that one connection has been closed
  if (scheme == Scheme.sftp) {
    await().atMost(10, TimeUnit.SECONDS).until(() -> Assert.assertEquals(1, closed.get()));
    Assert.assertEquals(1, closed.get());
  } else if (scheme == Scheme.ftp) {
    await().atMost(10, TimeUnit.SECONDS).until(
        () -> Assert.assertEquals(0, ftpServer.getServerContext().getFtpStatistics().getCurrentConnectionNumber()));
    Assert.assertEquals(0, ftpServer.getServerContext().getFtpStatistics().getCurrentConnectionNumber());
  }
  if (scheme == Scheme.sftp) {
    // Unset the timeout config for SFTP because it's global
    PropertyResolverUtils.updateProperty(sshd, FactoryManager.IDLE_TIMEOUT, FactoryManager.DEFAULT_IDLE_TIMEOUT);
  }
  StageRunner.Output op = runner.runProduce(RemoteDownloadSource.NOTHING_READ, 1000);
  // Now we've opened a new connection
  if (scheme == Scheme.sftp) {
    Assert.assertEquals(2, opened.get());
  } else if (scheme == Scheme.ftp) {
    Assert.assertEquals(1, ftpServer.getServerContext().getFtpStatistics().getCurrentConnectionNumber());
    Assert.assertEquals(2, ftpServer.getServerContext().getFtpStatistics().getTotalConnectionNumber());
  }
  List<Record> expected = getExpectedRecords();
  List<Record> actual = op.getRecords().get("lane");
  Assert.assertEquals(expected.size(), actual.size());
  for (int i = 0; i < 2; i++) {
    Assert.assertEquals(expected.get(i).get(), actual.get(i).get());
  }
  destroyAndValidate(runner);
}
 
Example #30
Source File: TestServiceFactory.java    From aesh-readline with Apache License 2.0 4 votes vote down vote up
public TestServiceFactory(FactoryManager factoryManager, ExecutorService service, boolean shutdownOnExit) {
  super(factoryManager, service, shutdownOnExit);
}