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 2019/12/05 17:44:30 UTC

[mina-sshd] branch master updated (725e30c -> 69caf00)

This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git.


    from 725e30c  Upgraded Spring integration version to 5.2.1
     new 1de0f8b  [SSHD-956] Fixed return value of SessionHelper#checkForTimeouts in case session is being closed
     new 9a0d8a9  [SSHD-956] Using System#nanoTime to measure session idle/authentication timeouts
     new b40e1e5  Moved Closeable inheritance from Session to SessionContext
     new 9cf3fea  Moved isServerSession() indicator from Session to SessionContext
     new 6211fc3  Moved current cipher/MAC/compression information getters from Session to SessionContext
     new 30bcff4  Minor code changes for GenericUtils
     new cdefd19  Return a case-insensitive NavigableSet<String> for AclCapabilities#decodeAclCapabilities
     new 69371dd  Using more liberal sizing of internal maps used by StandardEnvironment
     new 69caf00  Using plain Session instead of AbstractSession where possible

The 9 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 CHANGES.md                                         |  4 ++
 .../apache/sshd/common/session/SessionContext.java | 45 +++++++++++++-
 .../org/apache/sshd/common/util/GenericUtils.java  | 69 +++++++++++-----------
 .../org/apache/sshd/common/session/Session.java    | 45 +-------------
 .../session/helpers/AbstractConnectionService.java | 22 +++----
 .../sshd/common/session/helpers/SessionHelper.java | 47 ++++++++++-----
 .../session/helpers/SessionTimeoutListener.java    | 31 +++++-----
 .../java/org/apache/sshd/server/Environment.java   |  2 +-
 .../apache/sshd/server/StandardEnvironment.java    |  4 +-
 .../client/simple/SimpleSessionClientTest.java     | 18 ++++--
 .../java/org/apache/sshd/server/ServerTest.java    | 58 ++++++++++++------
 .../sftp/extensions/AclSupportedParser.java        | 13 ++--
 12 files changed, 203 insertions(+), 155 deletions(-)


[mina-sshd] 01/09: [SSHD-956] Fixed return value of SessionHelper#checkForTimeouts in case session is being closed

Posted by lg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 1de0f8be4c3b275f4b8935c9c295df12a2390ef3
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Nov 28 20:03:39 2019 +0200

    [SSHD-956] Fixed return value of SessionHelper#checkForTimeouts in case session is being closed
---
 .../sshd/common/session/helpers/SessionHelper.java |  8 +++++---
 .../session/helpers/SessionTimeoutListener.java    | 24 +++++++++++-----------
 2 files changed, 17 insertions(+), 15 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java
index d18d803..baf056d 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java
@@ -225,13 +225,14 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
         if ((!isOpen()) || isClosing() || isClosed()) {
             if (log.isDebugEnabled()) {
                 log.debug("checkForTimeouts({}) session closing", this);
-                return TimeoutIndicator.NONE;
             }
+            return TimeoutIndicator.NONE;
         }
 
         // If already detected a timeout don't check again
         TimeoutIndicator result = timeoutStatus.get();
-        TimeoutStatus status = (result == null) ? TimeoutStatus.NoTimeout : result.getStatus();
+        TimeoutStatus status =
+            (result == null) ? TimeoutStatus.NoTimeout : result.getStatus();
         if ((status != null) && (status != TimeoutStatus.NoTimeout)) {
             if (log.isDebugEnabled()) {
                 log.debug("checkForTimeouts({}) already detected {}", this, result);
@@ -289,7 +290,8 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
         timeoutStatus.set(result);
 
         disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR,
-            "Detected " + status + " after " + result.getExpiredValue() + "/" + result.getThresholdValue() + " ms.");
+            "Detected " + status + " after " + result.getExpiredValue()
+            + "/" + result.getThresholdValue() + " ms.");
         return result;
     }
 
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java
index 0da3e66..bcd69c1 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java
@@ -31,8 +31,10 @@ import org.apache.sshd.common.util.logging.AbstractLoggingBean;
  *
  * @see org.apache.sshd.common.session.helpers.AbstractSession#checkForTimeouts()
  */
-public class SessionTimeoutListener extends AbstractLoggingBean implements SessionListener, Runnable {
-    private final Set<AbstractSession> sessions = new CopyOnWriteArraySet<>();
+public class SessionTimeoutListener
+        extends AbstractLoggingBean
+        implements SessionListener, Runnable {
+    protected final Set<SessionHelper> sessions = new CopyOnWriteArraySet<>();
 
     public SessionTimeoutListener() {
         super();
@@ -40,8 +42,9 @@ public class SessionTimeoutListener extends AbstractLoggingBean implements Sessi
 
     @Override
     public void sessionCreated(Session session) {
-        if ((session instanceof AbstractSession) && ((session.getAuthTimeout() > 0L) || (session.getIdleTimeout() > 0L))) {
-            sessions.add((AbstractSession) session);
+        if ((session instanceof SessionHelper)
+                && ((session.getAuthTimeout() > 0L) || (session.getIdleTimeout() > 0L))) {
+            sessions.add((SessionHelper) session);
             if (log.isDebugEnabled()) {
                 log.debug("sessionCreated({}) tracking", session);
             }
@@ -53,14 +56,10 @@ public class SessionTimeoutListener extends AbstractLoggingBean implements Sessi
     }
 
     @Override
-    public void sessionEvent(Session session, Event event) {
-        // ignored
-    }
-
-    @Override
     public void sessionException(Session session, Throwable t) {
         if (log.isDebugEnabled()) {
-            log.debug("sessionException({}) {}: {}", session, t.getClass().getSimpleName(), t.getMessage());
+            log.debug("sessionException({}) {}: {}",
+                session, t.getClass().getSimpleName(), t.getMessage());
         }
         if (log.isTraceEnabled()) {
             log.trace("sessionException(" + session + ") details", t);
@@ -84,11 +83,12 @@ public class SessionTimeoutListener extends AbstractLoggingBean implements Sessi
 
     @Override
     public void run() {
-        for (AbstractSession session : sessions) {
+        for (SessionHelper session : sessions) {
             try {
                 session.checkForTimeouts();
             } catch (Exception e) {
-                log.warn(e.getClass().getSimpleName() + " while checking session=" + session + " timeouts: " + e.getMessage(), e);
+                log.warn(e.getClass().getSimpleName() + " while checking"
+                    + " session=" + session + " timeouts: " + e.getMessage(), e);
             }
         }
     }


[mina-sshd] 08/09: Using more liberal sizing of internal maps used by StandardEnvironment

Posted by lg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 69371dd271ea668a2e9b62121ef302075f156c0a
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Nov 28 20:46:19 2019 +0200

    Using more liberal sizing of internal maps used by StandardEnvironment
---
 .../src/main/java/org/apache/sshd/server/StandardEnvironment.java     | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/server/StandardEnvironment.java b/sshd-core/src/main/java/org/apache/sshd/server/StandardEnvironment.java
index 1e16a3a..0a45d50 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/StandardEnvironment.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/StandardEnvironment.java
@@ -38,9 +38,9 @@ public class StandardEnvironment extends AbstractLoggingBean implements Environm
     private final Map<PtyMode, Integer> ptyModes;
 
     public StandardEnvironment() {
-        listeners = new ConcurrentHashMap<>(3);
+        listeners = new ConcurrentHashMap<>(Signal.SIGNALS.size());
         env = new ConcurrentHashMap<>();
-        ptyModes = new ConcurrentHashMap<>();
+        ptyModes = new ConcurrentHashMap<>(PtyMode.MODES.size());
     }
 
     /*


[mina-sshd] 09/09: Using plain Session instead of AbstractSession where possible

Posted by lg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 69caf00a0dc8bec2eed2bec306ab41a65884690b
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Nov 28 20:57:15 2019 +0200

    Using plain Session instead of AbstractSession where possible
---
 .../session/helpers/AbstractConnectionService.java | 22 +++++++++++-----------
 .../session/helpers/SessionTimeoutListener.java    |  7 ++++---
 2 files changed, 15 insertions(+), 14 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractConnectionService.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractConnectionService.java
index 284d8c5..5bcae35 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractConnectionService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractConnectionService.java
@@ -304,7 +304,7 @@ public abstract class AbstractConnectionService
     @Override
     public ForwardingFilter getForwardingFilter() {
         ForwardingFilter forwarder;
-        AbstractSession session = getSession();
+        Session session = getSession();
         synchronized (forwarderHolder) {
             forwarder = forwarderHolder.get();
             if (forwarder != null) {
@@ -330,7 +330,7 @@ public abstract class AbstractConnectionService
         super.preClose();
     }
 
-    protected ForwardingFilter createForwardingFilter(AbstractSession session) {
+    protected ForwardingFilter createForwardingFilter(Session session) {
         FactoryManager manager =
             Objects.requireNonNull(session.getFactoryManager(), "No factory manager");
         ForwardingFilterFactory factory =
@@ -343,7 +343,7 @@ public abstract class AbstractConnectionService
     @Override
     public X11ForwardSupport getX11ForwardSupport() {
         X11ForwardSupport x11Support;
-        AbstractSession session = getSession();
+        Session session = getSession();
         synchronized (x11ForwardHolder) {
             x11Support = x11ForwardHolder.get();
             if (x11Support != null) {
@@ -361,14 +361,14 @@ public abstract class AbstractConnectionService
         return x11Support;
     }
 
-    protected X11ForwardSupport createX11ForwardSupport(AbstractSession session) {
+    protected X11ForwardSupport createX11ForwardSupport(Session session) {
         return new DefaultX11ForwardSupport(this);
     }
 
     @Override
     public AgentForwardSupport getAgentForwardSupport() {
         AgentForwardSupport agentForward;
-        AbstractSession session = getSession();
+        Session session = getSession();
         synchronized (agentForwardHolder) {
             agentForward = agentForwardHolder.get();
             if (agentForward != null) {
@@ -387,7 +387,7 @@ public abstract class AbstractConnectionService
         return agentForward;
     }
 
-    protected AgentForwardSupport createAgentForwardSupport(AbstractSession session) {
+    protected AgentForwardSupport createAgentForwardSupport(Session session) {
         return new DefaultAgentForwardSupport(this);
     }
 
@@ -405,7 +405,7 @@ public abstract class AbstractConnectionService
 
     @Override
     public int registerChannel(Channel channel) throws IOException {
-        AbstractSession session = getSession();
+        Session session = getSession();
         int maxChannels = this.getIntProperty(MAX_CONCURRENT_CHANNELS_PROP, DEFAULT_MAX_CHANNELS);
         int curSize = channels.size();
         if (curSize > maxChannels) {
@@ -741,7 +741,7 @@ public abstract class AbstractConnectionService
             return handler;
         }
 
-        AbstractSession s = getSession();
+        Session s = getSession();
         return (s == null) ? null : s.resolveUnknownChannelReferenceHandler();
     }
 
@@ -772,7 +772,7 @@ public abstract class AbstractConnectionService
             return;
         }
 
-        AbstractSession session = getSession();
+        Session session = getSession();
         FactoryManager manager = Objects.requireNonNull(session.getFactoryManager(), "No factory manager");
         Channel channel = ChannelFactory.createChannel(session, manager.getChannelFactories(), type);
         if (channel == null) {
@@ -836,7 +836,7 @@ public abstract class AbstractConnectionService
                   this, sender, SshConstants.getOpenErrorCodeName(reasonCode), lang, message);
         }
 
-        AbstractSession session = getSession();
+        Session session = getSession();
         Buffer buf = session.createBuffer(SshConstants.SSH_MSG_CHANNEL_OPEN_FAILURE,
             Long.SIZE + GenericUtils.length(message) + GenericUtils.length(lang));
         buf.putInt(sender);
@@ -863,7 +863,7 @@ public abstract class AbstractConnectionService
             log.debug("globalRequest({}) received SSH_MSG_GLOBAL_REQUEST {} want-reply={}", this, req, wantReply);
         }
 
-        AbstractSession session = getSession();
+        Session session = getSession();
         FactoryManager manager = Objects.requireNonNull(session.getFactoryManager(), "No factory manager");
         Collection<RequestHandler<ConnectionService>> handlers = manager.getGlobalRequestHandlers();
         if (GenericUtils.size(handlers) > 0) {
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java
index bcd69c1..de3d107 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionTimeoutListener.java
@@ -26,10 +26,11 @@ import org.apache.sshd.common.session.SessionListener;
 import org.apache.sshd.common.util.logging.AbstractLoggingBean;
 
 /**
- * Task that iterates over all currently open {@link AbstractSession}s and checks each of them for timeouts. If
- * the {@link AbstractSession} has timed out (either auth or idle timeout), the session will be disconnected.
+ * Task that iterates over all currently open {@link Session}s and checks each of them for timeouts. If
+ * the {@link AbstractSession} has timed out (either authentication or idle timeout), the session
+ * will be disconnected.
  *
- * @see org.apache.sshd.common.session.helpers.AbstractSession#checkForTimeouts()
+ * @see SessionHelper#checkForTimeouts()
  */
 public class SessionTimeoutListener
         extends AbstractLoggingBean


[mina-sshd] 03/09: Moved Closeable inheritance from Session to SessionContext

Posted by lg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit b40e1e5a881d8908ab9a7c5ec1aa10d95d45b773
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Nov 28 20:24:38 2019 +0200

    Moved Closeable inheritance from Session to SessionContext
---
 .../src/main/java/org/apache/sshd/common/session/SessionContext.java  | 4 +++-
 sshd-core/src/main/java/org/apache/sshd/common/session/Session.java   | 4 +---
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java b/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java
index a394868..51c9b00 100644
--- a/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java
@@ -22,6 +22,7 @@ package org.apache.sshd.common.session;
 import java.util.Map;
 
 import org.apache.sshd.common.AttributeStore;
+import org.apache.sshd.common.Closeable;
 import org.apache.sshd.common.auth.UsernameHolder;
 import org.apache.sshd.common.cipher.BuiltinCiphers;
 import org.apache.sshd.common.kex.KexProposalOption;
@@ -38,7 +39,8 @@ public interface SessionContext
         extends ConnectionEndpointsIndicator,
                 UsernameHolder,
                 SessionHeartbeatController,
-                AttributeStore {
+                AttributeStore,
+                Closeable {
     /**
      * Default prefix expected for the client / server identification string
      * @see <A HREF="https://tools.ietf.org/html/rfc4253#section-4.2">RFC 4253 - section 4.2</A>
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java b/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
index 2478727..8b7265a 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
@@ -24,7 +24,6 @@ import java.util.Objects;
 import java.util.concurrent.TimeUnit;
 
 import org.apache.sshd.common.AttributeRepository;
-import org.apache.sshd.common.Closeable;
 import org.apache.sshd.common.FactoryManager;
 import org.apache.sshd.common.FactoryManagerHolder;
 import org.apache.sshd.common.Service;
@@ -64,8 +63,7 @@ public interface Session
                 UnknownChannelReferenceHandlerManager,
                 FactoryManagerHolder,
                 PortForwardingInformationProvider,
-                PacketWriter,
-                Closeable {
+                PacketWriter {
 
     /**
      * Quick indication if this is a server or client session (instead of


[mina-sshd] 02/09: [SSHD-956] Using System#nanoTime to measure session idle/authentication timeouts

Posted by lg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 9a0d8a960e6181982128146f651cc7bb3065bc1e
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Nov 28 20:21:22 2019 +0200

    [SSHD-956] Using System#nanoTime to measure session idle/authentication timeouts
---
 CHANGES.md                                         |  2 +
 .../sshd/common/session/helpers/SessionHelper.java | 39 ++++++++++-----
 .../client/simple/SimpleSessionClientTest.java     | 18 ++++---
 .../java/org/apache/sshd/server/ServerTest.java    | 58 +++++++++++++++-------
 4 files changed, 79 insertions(+), 38 deletions(-)

diff --git a/CHANGES.md b/CHANGES.md
index f656e5d..2d4c669 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -104,3 +104,5 @@ for the server's identification before sending KEX-INIT message.
 * [SSHD-953](https://issues.apache.org/jira/browse/SSHD-953) - Parse and strip quoted command arguments when executing a server-side command via local shell.
 
 * [SSHD-955](https://issues.apache.org/jira/browse/SSHD-955) - Provide configurable control over auto-detected password prompt in client-side `UserAuthKeyboardInteractive` implementation.
+
+* [SSHD-956](https://issues.apache.org/jira/browse/SSHD-956) - Using `System#nanoTime` to measure session idle/authentication timeouts
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java
index baf056d..6003372 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java
@@ -80,6 +80,10 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
     /** Session level lock for regulating access to sensitive data */
     protected final Object sessionLock = new Object();
 
+    // Session timeout measurements
+    protected long authNanoStart = System.nanoTime();
+    protected long idleNanoStart = System.nanoTime();
+
     /** Client or server side */
     private final boolean serverSession;
 
@@ -213,13 +217,13 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
     }
 
     /**
-     * Checks whether the session has timed out (both auth and idle timeouts are checked).
+     * Checks whether the session has timed out (both authentication and idle timeouts are checked).
      * If the session has timed out, a DISCONNECT message will be sent.
      *
      * @return An indication whether timeout has been detected
      * @throws IOException If failed to check
-     * @see #checkAuthenticationTimeout(long, long)
-     * @see #checkIdleTimeout(long, long)
+     * @see #checkAuthenticationTimeout(long, long, long)
+     * @see #checkIdleTimeout(long, long, long)
      */
     protected TimeoutIndicator checkForTimeouts() throws IOException {
         if ((!isOpen()) || isClosing() || isClosed()) {
@@ -241,9 +245,10 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
         }
 
         long now = System.currentTimeMillis();
-        result = checkAuthenticationTimeout(now, getAuthTimeout());
+        long nanoTime = System.nanoTime();
+        result = checkAuthenticationTimeout(now, nanoTime, getAuthTimeout());
         if (result == null) {
-            result = checkIdleTimeout(now, getIdleTimeout());
+            result = checkIdleTimeout(now, nanoTime, getIdleTimeout());
         }
 
         status = (result == null) ? TimeoutStatus.NoTimeout : result.getStatus();
@@ -304,6 +309,7 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
     public long resetAuthTimeout() {
         long value = getAuthTimeoutStart();
         this.authTimeoutStart = System.currentTimeMillis();
+        this.authNanoStart = System.nanoTime();
         return value;
     }
 
@@ -311,15 +317,18 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
      * Checks if authentication timeout expired
      *
      * @param now           The current time in millis
+     * @param nanoTime      {@link System#nanoTime()} value
      * @param authTimeoutMs The configured timeout in millis - if non-positive then no timeout
      * @return A {@link TimeoutIndicator} specifying the timeout status and disconnect reason
      * message if timeout expired, {@code null} or {@code NoTimeout} if no timeout occurred
      * @see #getAuthTimeout()
      */
-    protected TimeoutIndicator checkAuthenticationTimeout(long now, long authTimeoutMs) {
-        long authDiff = now - getAuthTimeoutStart();
-        if ((!isAuthenticated()) && (authTimeoutMs > 0L) && (authDiff > authTimeoutMs)) {
-            return new TimeoutIndicator(TimeoutStatus.AuthTimeout, authTimeoutMs, authDiff);
+    protected TimeoutIndicator checkAuthenticationTimeout(
+            long now, long nanoTime, long authTimeoutMs) {
+        long authDiffNano = nanoTime - authNanoStart;
+        long authDiffMs = TimeUnit.NANOSECONDS.toMillis(authDiffNano);
+        if ((!isAuthenticated()) && (authTimeoutMs > 0L) && (authDiffMs > authTimeoutMs)) {
+            return new TimeoutIndicator(TimeoutStatus.AuthTimeout, authTimeoutMs, authDiffMs);
         } else {
             return null;
         }
@@ -334,15 +343,18 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
      * Checks if idle timeout expired
      *
      * @param now           The current time in millis
+     * @param nanoTime      {@link System#nanoTime()} value
      * @param idleTimeoutMs The configured timeout in millis - if non-positive then no timeout
      * @return A {@link TimeoutIndicator} specifying the timeout status and disconnect reason
      * message if timeout expired, {@code null} or {@code NoTimeout} if no timeout occurred
      * @see #getIdleTimeout()
      */
-    protected TimeoutIndicator checkIdleTimeout(long now, long idleTimeoutMs) {
-        long idleDiff = now - getIdleTimeoutStart();
-        if ((idleTimeoutMs > 0L) && (idleDiff > idleTimeoutMs)) {
-            return new TimeoutIndicator(TimeoutStatus.IdleTimeout, idleTimeoutMs, idleDiff);
+    protected TimeoutIndicator checkIdleTimeout(
+            long now, long nanoTime, long idleTimeoutMs) {
+        long idleDiffNano = nanoTime - idleNanoStart;
+        long idleDiffMs = TimeUnit.NANOSECONDS.toMillis(idleDiffNano);
+        if ((idleTimeoutMs > 0L) && (idleDiffMs > idleTimeoutMs)) {
+            return new TimeoutIndicator(TimeoutStatus.IdleTimeout, idleTimeoutMs, idleDiffMs);
         } else {
             return null;
         }
@@ -352,6 +364,7 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
     public long resetIdleTimeout() {
         long value = getIdleTimeoutStart();
         this.idleTimeoutStart = System.currentTimeMillis();
+        this.idleNanoStart = System.nanoTime();
         return value;
     }
 
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSessionClientTest.java b/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSessionClientTest.java
index a095f81..fb12ffd 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSessionClientTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSessionClientTest.java
@@ -53,7 +53,8 @@ public class SimpleSessionClientTest extends BaseSimpleClientTestSupport {
         sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE);
         client.start();
 
-        try (ClientSession session = simple.sessionLogin(TEST_LOCALHOST, port, getCurrentTestName(), getCurrentTestName())) {
+        try (ClientSession session = simple.sessionLogin(
+                TEST_LOCALHOST, port, getCurrentTestName(), getCurrentTestName())) {
             assertEquals("Mismatched session username", getCurrentTestName(), session.getUsername());
         }
     }
@@ -74,8 +75,10 @@ public class SimpleSessionClientTest extends BaseSimpleClientTestSupport {
         sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE);
         client.start();
 
-        try (ClientSession session = simple.sessionLogin(TEST_LOCALHOST, port, getCurrentTestName(), identity)) {
-            assertEquals("Mismatched session username", getCurrentTestName(), session.getUsername());
+        try (ClientSession session = simple.sessionLogin(
+                TEST_LOCALHOST, port, getCurrentTestName(), identity)) {
+            assertEquals("Mismatched session username",
+                getCurrentTestName(), session.getUsername());
             assertTrue("User identity not queried", identityQueried.get());
         }
     }
@@ -95,7 +98,8 @@ public class SimpleSessionClientTest extends BaseSimpleClientTestSupport {
         client.start();
 
         long nanoStart = System.nanoTime();
-        try (ClientSession session = simple.sessionLogin(TEST_LOCALHOST, port, getCurrentTestName(), getCurrentTestName())) {
+        try (ClientSession session = simple.sessionLogin(
+                TEST_LOCALHOST, port, getCurrentTestName(), getCurrentTestName())) {
             fail("Unexpected connection success");
         } catch (IOException e) {
             long nanoEnd = System.nanoTime();
@@ -110,7 +114,8 @@ public class SimpleSessionClientTest extends BaseSimpleClientTestSupport {
     public void testAuthenticationTimeout() throws Exception {
         // make sure authentication occurs only for passwords
         sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE);
-        PasswordAuthenticator delegate = Objects.requireNonNull(sshd.getPasswordAuthenticator(), "No password authenticator");
+        PasswordAuthenticator delegate = Objects.requireNonNull(
+            sshd.getPasswordAuthenticator(), "No password authenticator");
         sshd.setPasswordAuthenticator((username, password, session) -> {
             try {
                 Thread.sleep(AUTH_TIMEOUT + 150L);
@@ -122,7 +127,8 @@ public class SimpleSessionClientTest extends BaseSimpleClientTestSupport {
         client.start();
 
         long nanoStart = System.nanoTime();
-        try (ClientSession session = simple.sessionLogin(TEST_LOCALHOST, port, getCurrentTestName(), getCurrentTestName())) {
+        try (ClientSession session = simple.sessionLogin(
+                TEST_LOCALHOST, port, getCurrentTestName(), getCurrentTestName())) {
             fail("Unexpected connection success");
         } catch (IOException e) {
             long nanoEnd = System.nanoTime();
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java b/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java
index 62f4371..2666b73 100644
--- a/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java
@@ -89,6 +89,7 @@ import org.junit.Before;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
 import org.junit.runners.MethodSorters;
+import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
@@ -206,13 +207,15 @@ public class ServerTest extends BaseTestSupport {
         AtomicReference<TimeoutIndicator> timeoutHolder = new AtomicReference<>(TimeoutIndicator.NONE);
         sshd.setSessionDisconnectHandler(new SessionDisconnectHandler() {
             @Override
-            public boolean handleTimeoutDisconnectReason(Session session, TimeoutIndicator timeoutStatus)
-                    throws IOException {
+            public boolean handleTimeoutDisconnectReason(
+                    Session session, TimeoutIndicator timeoutStatus)
+                        throws IOException {
                 outputDebugMessage("Session %s timeout reported: %s", session, timeoutStatus);
 
                 TimeoutIndicator prev = timeoutHolder.getAndSet(timeoutStatus);
                 if (prev != TimeoutIndicator.NONE) {
-                    throw new StreamCorruptedException("Multiple timeout disconnects: " + timeoutStatus + " / " + prev);
+                    throw new StreamCorruptedException(
+                        "Multiple timeout disconnects: " + timeoutStatus + " / " + prev);
                 }
                 return false;
             }
@@ -238,7 +241,8 @@ public class ServerTest extends BaseTestSupport {
         }
 
         TimeoutIndicator status = timeoutHolder.getAndSet(null);
-        assertSame("Mismatched timeout status reported", TimeoutIndicator.TimeoutStatus.AuthTimeout, status.getStatus());
+        assertSame("Mismatched timeout status reported",
+            TimeoutIndicator.TimeoutStatus.AuthTimeout, status.getStatus());
     }
 
     @Test
@@ -250,12 +254,14 @@ public class ServerTest extends BaseTestSupport {
         TestEchoShell.latch = new CountDownLatch(1);
         sshd.setSessionDisconnectHandler(new SessionDisconnectHandler() {
             @Override
-            public boolean handleTimeoutDisconnectReason(Session session, TimeoutIndicator timeoutStatus)
-                    throws IOException {
+            public boolean handleTimeoutDisconnectReason(
+                    Session session, TimeoutIndicator timeoutStatus)
+                        throws IOException {
                 outputDebugMessage("Session %s timeout reported: %s", session, timeoutStatus);
                 TimeoutIndicator prev = timeoutHolder.getAndSet(timeoutStatus);
                 if (prev != TimeoutIndicator.NONE) {
-                    throw new StreamCorruptedException("Multiple timeout disconnects: " + timeoutStatus + " / " + prev);
+                    throw new StreamCorruptedException(
+                        "Multiple timeout disconnects: " + timeoutStatus + " / " + prev);
                 }
                 return false;
             }
@@ -314,15 +320,20 @@ public class ServerTest extends BaseTestSupport {
             shell.setErr(err);
             shell.open().verify(9L, TimeUnit.SECONDS);
 
-            assertTrue("No changes in activated channels", channelListener.waitForActiveChannelsChange(5L, TimeUnit.SECONDS));
-            assertTrue("No changes in open channels", channelListener.waitForOpenChannelsChange(5L, TimeUnit.SECONDS));
+            assertTrue("No changes in activated channels",
+                channelListener.waitForActiveChannelsChange(5L, TimeUnit.SECONDS));
+            assertTrue("No changes in open channels",
+                channelListener.waitForOpenChannelsChange(5L, TimeUnit.SECONDS));
 
             long waitStart = System.currentTimeMillis();
             Collection<ClientSession.ClientSessionEvent> res =
                 s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED), 3L * testIdleTimeout);
             long waitEnd = System.currentTimeMillis();
             assertTrue("Invalid session state after " + (waitEnd - waitStart) + " ms: " + res,
-                res.containsAll(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.AUTHED)));
+                res.containsAll(
+                    EnumSet.of(
+                        ClientSession.ClientSessionEvent.CLOSED,
+                        ClientSession.ClientSessionEvent.AUTHED)));
         } finally {
             client.stop();
         }
@@ -344,10 +355,12 @@ public class ServerTest extends BaseTestSupport {
     @Test
     public void testServerIdleTimeoutWithForce() throws Exception {
         final long idleTimeoutValue = TimeUnit.SECONDS.toMillis(5L);
-        PropertyResolverUtils.updateProperty(sshd, FactoryManager.IDLE_TIMEOUT, idleTimeoutValue);
+        PropertyResolverUtils.updateProperty(
+            sshd, FactoryManager.IDLE_TIMEOUT, idleTimeoutValue);
 
         final long disconnectTimeoutValue = TimeUnit.SECONDS.toMillis(2L);
-        PropertyResolverUtils.updateProperty(sshd, FactoryManager.DISCONNECT_TIMEOUT, disconnectTimeoutValue);
+        PropertyResolverUtils.updateProperty(
+            sshd, FactoryManager.DISCONNECT_TIMEOUT, disconnectTimeoutValue);
 
         CountDownLatch latch = new CountDownLatch(1);
         sshd.setCommandFactory((channel, command) -> new StreamCommand(command));
@@ -364,7 +377,8 @@ public class ServerTest extends BaseTestSupport {
 
             @Override
             public void sessionException(Session session, Throwable t) {
-                outputDebugMessage("Session %s exception %s caught: %s", session, t.getClass().getSimpleName(), t.getMessage());
+                outputDebugMessage("Session %s exception %s caught: %s",
+                    session, t.getClass().getSimpleName(), t.getMessage());
             }
 
             @Override
@@ -393,16 +407,21 @@ public class ServerTest extends BaseTestSupport {
             shell.setOut(pos);
             shell.open().verify(5L, TimeUnit.SECONDS);
 
-            assertTrue("No changes in activated channels", channelListener.waitForActiveChannelsChange(5L, TimeUnit.SECONDS));
-            assertTrue("No changes in open channels", channelListener.waitForOpenChannelsChange(5L, TimeUnit.SECONDS));
+            assertTrue("No changes in activated channels",
+                channelListener.waitForActiveChannelsChange(5L, TimeUnit.SECONDS));
+            assertTrue("No changes in open channels",
+                channelListener.waitForOpenChannelsChange(5L, TimeUnit.SECONDS));
 
             try (AbstractSession serverSession = GenericUtils.head(sshd.getActiveSessions())) {
-                AbstractConnectionService service = serverSession.getService(AbstractConnectionService.class);
+                AbstractConnectionService service =
+                    serverSession.getService(AbstractConnectionService.class);
                 Collection<? extends Channel> channels = service.getChannels();
 
                 try (Channel channel = GenericUtils.head(channels)) {
-                    final long maxTimeoutValue = idleTimeoutValue + disconnectTimeoutValue + TimeUnit.SECONDS.toMillis(3L);
-                    final long maxWaitNanos = TimeUnit.MILLISECONDS.toNanos(maxTimeoutValue);
+                    final long maxTimeoutValue =
+                        idleTimeoutValue + disconnectTimeoutValue + TimeUnit.SECONDS.toMillis(3L);
+                    final long maxWaitNanos =
+                        TimeUnit.MILLISECONDS.toNanos(maxTimeoutValue);
                     Window wRemote = channel.getRemoteWindow();
                     for (long totalNanoTime = 0L; wRemote.getSize() > 0;) {
                         long nanoStart = System.nanoTime();
@@ -414,7 +433,8 @@ public class ServerTest extends BaseTestSupport {
                         assertTrue("Waiting for too long on remote window size to reach zero", totalNanoTime < maxWaitNanos);
                     }
 
-                    LoggerFactory.getLogger(getClass()).info("Waiting for session idle timeouts");
+                    Logger logger = LoggerFactory.getLogger(getClass());
+                    logger.info("Waiting for session idle timeouts");
 
                     long t0 = System.currentTimeMillis();
                     latch.await(1L, TimeUnit.MINUTES);


[mina-sshd] 05/09: Moved current cipher/MAC/compression information getters from Session to SessionContext

Posted by lg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 6211fc3a0a26ed48612bbd57906a8a72ac0b9045
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Nov 28 20:29:49 2019 +0200

    Moved current cipher/MAC/compression information getters from Session to SessionContext
---
 CHANGES.md                                         |  2 ++
 .../apache/sshd/common/session/SessionContext.java | 33 ++++++++++++++++++++++
 .../org/apache/sshd/common/session/Session.java    | 33 ----------------------
 3 files changed, 35 insertions(+), 33 deletions(-)

diff --git a/CHANGES.md b/CHANGES.md
index 2d4c669..340d885 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -71,6 +71,8 @@ the message type=30 (old request).
 
 * Client side `UserAuthKeyboardInteractive` allows configurable detection of plain-text password prompt.
 
+* Moved a few informative getters from `Session` to `SessionContext`.
+
 ## Behavioral changes and enhancements
 
 * [SSHD-926](https://issues.apache.org/jira/browse/SSHD-930) - Add support for OpenSSH 'lsetstat@openssh.com' SFTP protocol extension.
diff --git a/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java b/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java
index e73e4b5..d6b257d 100644
--- a/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java
@@ -25,8 +25,11 @@ import org.apache.sshd.common.AttributeStore;
 import org.apache.sshd.common.Closeable;
 import org.apache.sshd.common.auth.UsernameHolder;
 import org.apache.sshd.common.cipher.BuiltinCiphers;
+import org.apache.sshd.common.cipher.CipherInformation;
+import org.apache.sshd.common.compression.CompressionInformation;
 import org.apache.sshd.common.kex.KexProposalOption;
 import org.apache.sshd.common.kex.KexState;
+import org.apache.sshd.common.mac.MacInformation;
 import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.net.ConnectionEndpointsIndicator;
 
@@ -123,6 +126,36 @@ public interface SessionContext
     String getNegotiatedKexParameter(KexProposalOption paramType);
 
     /**
+     * Retrieves current cipher information - <B>Note:</B> may change if
+     * key re-exchange executed
+     *
+     * @param incoming If {@code true} then the cipher for the incoming data,
+     * otherwise for the outgoing data
+     * @return The {@link CipherInformation} - or {@code null} if not negotiated yet.
+     */
+    CipherInformation getCipherInformation(boolean incoming);
+
+    /**
+     * Retrieves current compression information - <B>Note:</B> may change if
+     * key re-exchange executed
+     *
+     * @param incoming If {@code true} then the compression for the incoming data,
+     * otherwise for the outgoing data
+     * @return The {@link CompressionInformation} - or {@code null} if not negotiated yet.
+     */
+    CompressionInformation getCompressionInformation(boolean incoming);
+
+    /**
+     * Retrieves current MAC information - <B>Note:</B> may change if
+     * key re-exchange executed
+     *
+     * @param incoming If {@code true} then the MAC for the incoming data,
+     * otherwise for the outgoing data
+     * @return The {@link MacInformation} - or {@code null} if not negotiated yet.
+     */
+    MacInformation getMacInformation(boolean incoming);
+
+    /**
      * @return {@code true} if session has successfully completed the authentication phase
      */
     boolean isAuthenticated();
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java b/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
index dc6c00c..a9d59d4 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
@@ -30,8 +30,6 @@ import org.apache.sshd.common.Service;
 import org.apache.sshd.common.auth.MutableUserHolder;
 import org.apache.sshd.common.channel.ChannelListenerManager;
 import org.apache.sshd.common.channel.throttle.ChannelStreamPacketWriterResolverManager;
-import org.apache.sshd.common.cipher.CipherInformation;
-import org.apache.sshd.common.compression.CompressionInformation;
 import org.apache.sshd.common.forward.PortForwardingEventListenerManager;
 import org.apache.sshd.common.forward.PortForwardingInformationProvider;
 import org.apache.sshd.common.future.KeyExchangeFuture;
@@ -40,7 +38,6 @@ import org.apache.sshd.common.io.IoWriteFuture;
 import org.apache.sshd.common.io.PacketWriter;
 import org.apache.sshd.common.kex.KexFactoryManager;
 import org.apache.sshd.common.kex.KeyExchange;
-import org.apache.sshd.common.mac.MacInformation;
 import org.apache.sshd.common.session.helpers.TimeoutIndicator;
 import org.apache.sshd.common.util.buffer.Buffer;
 
@@ -66,36 +63,6 @@ public interface Session
                 PacketWriter {
 
     /**
-     * Retrieves current cipher information - <B>Note:</B> may change if
-     * key re-exchange executed
-     *
-     * @param incoming If {@code true} then the cipher for the incoming data,
-     * otherwise for the outgoing data
-     * @return The {@link CipherInformation} - or {@code null} if not negotiated yet.
-     */
-    CipherInformation getCipherInformation(boolean incoming);
-
-    /**
-     * Retrieves current compression information - <B>Note:</B> may change if
-     * key re-exchange executed
-     *
-     * @param incoming If {@code true} then the compression for the incoming data,
-     * otherwise for the outgoing data
-     * @return The {@link CompressionInformation} - or {@code null} if not negotiated yet.
-     */
-    CompressionInformation getCompressionInformation(boolean incoming);
-
-    /**
-     * Retrieves current MAC information - <B>Note:</B> may change if
-     * key re-exchange executed
-     *
-     * @param incoming If {@code true} then the MAC for the incoming data,
-     * otherwise for the outgoing data
-     * @return The {@link MacInformation} - or {@code null} if not negotiated yet.
-     */
-    MacInformation getMacInformation(boolean incoming);
-
-    /**
      * Create a new buffer for the specified SSH packet and reserve the needed space
      * (5 bytes) for the packet header.
      *


[mina-sshd] 07/09: Return a case-insensitive NavigableSet for AclCapabilities#decodeAclCapabilities

Posted by lg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit cdefd1980da89b66bb4bbdd4a33c64a77d45f6ca
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Nov 28 20:43:22 2019 +0200

    Return a case-insensitive NavigableSet<String> for AclCapabilities#decodeAclCapabilities
---
 .../subsystem/sftp/extensions/AclSupportedParser.java       | 13 ++++++++-----
 1 file changed, 8 insertions(+), 5 deletions(-)

diff --git a/sshd-sftp/src/main/java/org/apache/sshd/common/subsystem/sftp/extensions/AclSupportedParser.java b/sshd-sftp/src/main/java/org/apache/sshd/common/subsystem/sftp/extensions/AclSupportedParser.java
index b796ab7..892c9b9 100644
--- a/sshd-sftp/src/main/java/org/apache/sshd/common/subsystem/sftp/extensions/AclSupportedParser.java
+++ b/sshd-sftp/src/main/java/org/apache/sshd/common/subsystem/sftp/extensions/AclSupportedParser.java
@@ -25,6 +25,7 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.NavigableMap;
+import java.util.NavigableSet;
 import java.util.Objects;
 import java.util.Set;
 import java.util.TreeSet;
@@ -58,7 +59,8 @@ public class AclSupportedParser extends AbstractParser<AclCapabilities> {
 
         public AclCapabilities(int capabilities) {
             // Protect against malicious or malformed packets
-            ValidateUtils.checkTrue((capabilities >= 0) && (capabilities < SshConstants.SSH_REQUIRED_PAYLOAD_PACKET_LENGTH_SUPPORT),
+            ValidateUtils.checkTrue(
+                (capabilities >= 0) && (capabilities < SshConstants.SSH_REQUIRED_PAYLOAD_PACKET_LENGTH_SUPPORT),
                 "Illogical ACL capabilities count: %d", capabilities);
             this.capabilities = capabilities;
         }
@@ -111,7 +113,8 @@ public class AclSupportedParser extends AbstractParser<AclCapabilities> {
                 LoggingUtils.generateMnemonicMap(SftpConstants.class, ACL_CAP_NAME_PREFIX);
             private static final NavigableMap<String, Integer> ACL_NAMES_MAP =
                 Collections.unmodifiableNavigableMap(
-                    GenericUtils.flipMap(ACL_VALUES_MAP, GenericUtils.caseInsensitiveMap(), false));
+                    GenericUtils.flipMap(
+                        ACL_VALUES_MAP, GenericUtils.caseInsensitiveMap(), false));
 
             private LazyAclCapabilityNameHolder() {
                 throw new UnsupportedOperationException("No instance allowed");
@@ -157,12 +160,12 @@ public class AclSupportedParser extends AbstractParser<AclCapabilities> {
             }
         }
 
-        public static Set<String> decodeAclCapabilities(int mask) {
+        public static NavigableSet<String> decodeAclCapabilities(int mask) {
             if (mask == 0) {
-                return Collections.emptySet();
+                return Collections.emptyNavigableSet();
             }
 
-            Set<String> caps = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
+            NavigableSet<String> caps = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
             Map<Integer, String> map = getAclCapabilityValuesMap();
             map.forEach((value, name) -> {
                 if ((mask & value) != 0) {


[mina-sshd] 04/09: Moved isServerSession() indicator from Session to SessionContext

Posted by lg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 9cf3feab69077da29bca8ca14899033e0016c274
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Nov 28 20:25:57 2019 +0200

    Moved isServerSession() indicator from Session to SessionContext
---
 .../main/java/org/apache/sshd/common/session/SessionContext.java  | 8 ++++++++
 .../src/main/java/org/apache/sshd/common/session/Session.java     | 8 --------
 2 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java b/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java
index 51c9b00..e73e4b5 100644
--- a/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/session/SessionContext.java
@@ -72,6 +72,14 @@ public interface SessionContext
     byte[] getSessionId();
 
     /**
+     * Quick indication if this is a server or client session (instead of
+     * having to ask {@code instanceof}).
+     *
+     * @return {@code true} if this is a server session
+     */
+    boolean isServerSession();
+
+    /**
      * Retrieve the client version for this session.
      *
      * @return the client version - may be {@code null}/empty if versions not yet exchanged
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java b/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
index 8b7265a..dc6c00c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/Session.java
@@ -66,14 +66,6 @@ public interface Session
                 PacketWriter {
 
     /**
-     * Quick indication if this is a server or client session (instead of
-     * having to ask {@code instanceof}).
-     *
-     * @return {@code true} if this is a server session
-     */
-    boolean isServerSession();
-
-    /**
      * Retrieves current cipher information - <B>Note:</B> may change if
      * key re-exchange executed
      *


[mina-sshd] 06/09: Minor code changes for GenericUtils

Posted by lg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 30bcff4ba1f03ddc41a8237532abda1e17bf487e
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Nov 28 20:42:33 2019 +0200

    Minor code changes for GenericUtils
---
 .../org/apache/sshd/common/util/GenericUtils.java  | 69 +++++++++++-----------
 .../java/org/apache/sshd/server/Environment.java   |  2 +-
 2 files changed, 35 insertions(+), 36 deletions(-)

diff --git a/sshd-common/src/main/java/org/apache/sshd/common/util/GenericUtils.java b/sshd-common/src/main/java/org/apache/sshd/common/util/GenericUtils.java
index ea75c08..7acf1f8 100644
--- a/sshd-common/src/main/java/org/apache/sshd/common/util/GenericUtils.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/util/GenericUtils.java
@@ -287,11 +287,11 @@ public final class GenericUtils {
     }
 
     public static int size(Collection<?> c) {
-        return c == null ? 0 : c.size();
+        return (c == null) ? 0 : c.size();
     }
 
     public static boolean isEmpty(Collection<?> c) {
-        return (c == null) || c.isEmpty();
+        return size(c) <= 0;
     }
 
     public static boolean isNotEmpty(Collection<?> c) {
@@ -299,11 +299,11 @@ public final class GenericUtils {
     }
 
     public static int size(Map<?, ?> m) {
-        return m == null ? 0 : m.size();
+        return (m == null) ? 0 : m.size();
     }
 
     public static boolean isEmpty(Map<?, ?> m) {
-        return (m == null) || m.isEmpty();
+        return size(m) <= 0;
     }
 
     public static boolean isNotEmpty(Map<?, ?> m) {
@@ -312,7 +312,7 @@ public final class GenericUtils {
 
     @SafeVarargs
     public static <T> int length(T... a) {
-        return a == null ? 0 : a.length;
+        return (a == null) ? 0 : a.length;
     }
 
     public static <T> boolean isEmpty(Iterable<? extends T> iter) {
@@ -330,7 +330,7 @@ public final class GenericUtils {
     }
 
     public static <T> boolean isEmpty(Iterator<? extends T> iter) {
-        return iter == null || !iter.hasNext();
+        return (iter == null) || (!iter.hasNext());
     }
 
     public static <T> boolean isNotEmpty(Iterator<? extends T> iter) {
@@ -472,7 +472,8 @@ public final class GenericUtils {
         }
     }
 
-    public static <T> boolean containsAny(Collection<? extends T> coll, Iterable<? extends T> values) {
+    public static <T> boolean containsAny(
+            Collection<? extends T> coll, Iterable<? extends T> values) {
         if (isEmpty(coll)) {
             return false;
         }
@@ -486,13 +487,15 @@ public final class GenericUtils {
         return false;
     }
 
-    public static <T> void forEach(Iterable<? extends T> values, Consumer<? super T> consumer) {
+    public static <T> void forEach(
+            Iterable<? extends T> values, Consumer<? super T> consumer) {
         if (isNotEmpty(values)) {
             values.forEach(consumer);
         }
     }
 
-    public static <T, U> List<U> map(Collection<? extends T> values, Function<? super T, ? extends U> mapper) {
+    public static <T, U> List<U> map(
+            Collection<? extends T> values, Function<? super T, ? extends U> mapper) {
         return stream(values).map(mapper).collect(Collectors.toList());
     }
 
@@ -508,7 +511,9 @@ public final class GenericUtils {
     }
 
     public static <T, K, U> Collector<T, ?, NavigableMap<K, U>> toSortedMap(
-            Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, Comparator<? super K> comparator) {
+            Function<? super T, ? extends K> keyMapper,
+            Function<? super T, ? extends U> valueMapper,
+            Comparator<? super K> comparator) {
         return Collectors.toMap(keyMapper, valueMapper, throwingMerger(), () -> new TreeMap<>(comparator));
     }
 
@@ -587,7 +592,8 @@ public final class GenericUtils {
      * @return A {@link NavigableSet} containing the values (if any) sorted
      * using the provided comparator
      */
-    public static <V> NavigableSet<V> asSortedSet(Comparator<? super V> comp, Collection<? extends V> values) {
+    public static <V> NavigableSet<V> asSortedSet(
+            Comparator<? super V> comp, Collection<? extends V> values) {
         NavigableSet<V> set = new TreeSet<>(Objects.requireNonNull(comp, "No comparator"));
         if (size(values) > 0) {
             set.addAll(values);
@@ -595,22 +601,6 @@ public final class GenericUtils {
         return set;
     }
 
-    @SafeVarargs
-    public static <E extends Enum<E>> Set<E> asEnumSet(E... values) {
-        if (isEmpty(values)) {
-            return Collections.emptySet();
-        }
-
-        Set<E> s = EnumSet.of(values[0]);
-        for (int index = 1 /* we used [0] to populate the initial set */; index < values.length; index++) {
-            if (!s.add(values[index])) {
-                continue;   // debug breakpoint
-            }
-        }
-
-        return s;
-    }
-
     /**
      * @param <V> Type of mapped value
      * @return A {@link Supplier} that returns a <U>new</U> {@link NavigableMap}
@@ -668,7 +658,9 @@ public final class GenericUtils {
      * that 2 (or more) values are not mapped to the same key
      */
     public static <K, V, M extends Map<K, V>> M mapValues(
-            Function<? super V, ? extends K> keyMapper, Supplier<? extends M> mapCreator, Collection<? extends V> values) {
+            Function<? super V, ? extends K> keyMapper,
+            Supplier<? extends M> mapCreator,
+            Collection<? extends V> values) {
         M map = mapCreator.get();
         for (V v : values) {
             K k = keyMapper.apply(v);
@@ -683,10 +675,12 @@ public final class GenericUtils {
 
     @SafeVarargs
     public static <T> T findFirstMatchingMember(Predicate<? super T> acceptor, T... values) {
-        return findFirstMatchingMember(acceptor, isEmpty(values) ? Collections.emptyList() : Arrays.asList(values));
+        return findFirstMatchingMember(acceptor,
+            isEmpty(values) ? Collections.emptyList() : Arrays.asList(values));
     }
 
-    public static <T> T findFirstMatchingMember(Predicate<? super T> acceptor, Collection<? extends T> values) {
+    public static <T> T findFirstMatchingMember(
+            Predicate<? super T> acceptor, Collection<? extends T> values) {
         List<T> matches = selectMatchingMembers(acceptor, values);
         return GenericUtils.isEmpty(matches) ? null : matches.get(0);
     }
@@ -701,7 +695,8 @@ public final class GenericUtils {
      */
     @SafeVarargs
     public static <T> List<T> selectMatchingMembers(Predicate<? super T> acceptor, T... values) {
-        return selectMatchingMembers(acceptor, isEmpty(values) ? Collections.emptyList() : Arrays.asList(values));
+        return selectMatchingMembers(acceptor,
+            isEmpty(values) ? Collections.emptyList() : Arrays.asList(values));
     }
 
     /**
@@ -712,7 +707,8 @@ public final class GenericUtils {
      * @param values The values to be scanned
      * @return A {@link List} of all the values that were accepted by the predicate
      */
-    public static <T> List<T> selectMatchingMembers(Predicate<? super T> acceptor, Collection<? extends T> values) {
+    public static <T> List<T> selectMatchingMembers(
+            Predicate<? super T> acceptor, Collection<? extends T> values) {
         return GenericUtils.stream(values)
             .filter(acceptor)
             .collect(Collectors.toList());
@@ -954,16 +950,19 @@ public final class GenericUtils {
         return (iter == null) ? Collections.emptyIterator() : iter;
     }
 
-    public static <U, V> Iterable<V> wrapIterable(Iterable<? extends U> iter, Function<? super U, ? extends V> mapper) {
+    public static <U, V> Iterable<V> wrapIterable(
+            Iterable<? extends U> iter, Function<? super U, ? extends V> mapper) {
         return () -> wrapIterator(iter, mapper);
     }
 
     @SuppressWarnings({ "unchecked", "rawtypes" })
-    public static <U, V> Iterator<V> wrapIterator(Iterable<? extends U> iter, Function<? super U, ? extends V> mapper) {
+    public static <U, V> Iterator<V> wrapIterator(
+            Iterable<? extends U> iter, Function<? super U, ? extends V> mapper) {
         return (Iterator) stream(iter).map(mapper).iterator();
     }
 
-    public static <U, V> Iterator<V> wrapIterator(Iterator<? extends U> iter, Function<? super U, ? extends V> mapper) {
+    public static <U, V> Iterator<V> wrapIterator(
+            Iterator<? extends U> iter, Function<? super U, ? extends V> mapper) {
         Iterator<? extends U> iterator = iteratorOf(iter);
         return new Iterator<V>() {
             @Override
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/Environment.java b/sshd-core/src/main/java/org/apache/sshd/server/Environment.java
index ea3d769..6513a58 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/Environment.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/Environment.java
@@ -77,7 +77,7 @@ public interface Environment {
      * @param signals The (never {@code null}/empty) {@link Signal}s the listener is interested in
      */
     default void addSignalListener(SignalListener listener, Signal... signals) {
-        addSignalListener(listener, GenericUtils.asEnumSet(signals));
+        addSignalListener(listener, GenericUtils.of(signals));
     }
 
     /**