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 6855c0889c9b5d46fda6a663b124fa2ee2893cd7
Author: Lyor Goldstein <[email protected]>
AuthorDate: Wed Jun 5 16:19:43 2019 +0300

    [SSHD-921] Proceed with session disconnect if the relevant handler throws 
an exception when invoked
---
 docs/event-listeners.md                            |  19 +-
 .../common/session/SessionDisconnectHandler.java   |   4 +-
 .../common/session/helpers/AbstractSession.java    |  17 +-
 .../sshd/common/session/helpers/SessionHelper.java |  16 +-
 .../sshd/server/session/AbstractServerSession.java |  39 ++-
 .../sshd/server/session/ServerUserAuthService.java | 275 +++++++++++++--------
 6 files changed, 239 insertions(+), 131 deletions(-)

diff --git a/docs/event-listeners.md b/docs/event-listeners.md
index 7a2457a..22b3dcc 100644
--- a/docs/event-listeners.md
+++ b/docs/event-listeners.md
@@ -174,18 +174,23 @@ protocol requirements - e.g., unknown service, idle 
timeout, etc.. In many cases
 cancel the disconnect by handling the problem somehow and then signaling to 
the code that there is no longer any need
 to disconnect. The handler can be registered globally at the 
`SshClient/Server` instance or per-session (via a `SessionListener`).
 
-**NOTE:** this handler is non-cumulative - i.e., setting it replaces any 
existing previous handler instance.
+**NOTE(s):**
+
+* This handler is non-cumulative - i.e., setting it replaces any existing 
previous handler instance.
+
+* If any exception is thrown from one of the invoked callback methods then 
session disconnect proceeds as if
+the handler decided not to intervene.
 
 ### `SignalListener`
 
-Informs about signal requests as described in [RFC 4254 - section 
6.9](https://tools.ietf.org/html/rfc4254#section-6.9), break requests
+Informs about signal requests as described in [RFC 4254 - section 
6.9](https://tools.ietf.org/html/rfc4254#section-6.9), "break" requests
 (sent as SIGINT) as described in [RFC 
4335](https://tools.ietf.org/html/rfc4335) and "window-change" (sent as 
SIGWINCH) requests as described
 in [RFC 4254 - section 6.7](https://tools.ietf.org/html/rfc4254#section-6.7)
 
 
 ### `SftpEventListener`
 
-Provides information about major SFTP protocol events. The provided 
`File/DirectoryHandle` to the various callbacks an also be used to
+Provides information about major SFTP protocol events. The provided 
`File/DirectoryHandle` to the various callbacks can also be used to
 store user-defined attributes via its `AttributeStore` implementation. The 
listener is registered at the `SftpSubsystemFactory`:
 
 
@@ -216,7 +221,7 @@ store user-defined attributes via its `AttributeStore` 
implementation. The liste
 
 ```
 
-**Note:** the attached attributed are automatically removed once handle has 
been closed - regardless of
+**Note:** the attached attributes are automatically removed once handle has 
been closed - regardless of
 whether the close attempt was successful or not. In other words, after 
`SftpEventListener#closed` has been
 called, all attributes associated with the handle are cleared.
 
@@ -236,16 +241,16 @@ The accessor is registered/overwritten in via the 
`SftpSubSystemFactory`:
 
 ```
 
-*Note:*
+**Note:**
 
 * Closing of file channel/directory streams created by the accessor are also 
closed
 via callbacks to the same accessor
-    
+
 * When closing a file channel that may have been potentially modified, the 
default implementation
 forces a synchronization of the data with the file-system. This behavior can 
be modified
 by setting the `sftp-auto-fsync-on-close` property to *false* (or by providing 
a customized implementation
 that involves other considerations as well).
-    
+
 ### `PortForwardingEventListener`
 
 Informs and allows tracking of port forwarding events as described in [RFC 
4254 - section 7](https://tools.ietf.org/html/rfc4254#section-7)
diff --git 
a/sshd-core/src/main/java/org/apache/sshd/common/session/SessionDisconnectHandler.java
 
b/sshd-core/src/main/java/org/apache/sshd/common/session/SessionDisconnectHandler.java
index 5f0d063..6cf4558 100644
--- 
a/sshd-core/src/main/java/org/apache/sshd/common/session/SessionDisconnectHandler.java
+++ 
b/sshd-core/src/main/java/org/apache/sshd/common/session/SessionDisconnectHandler.java
@@ -144,10 +144,12 @@ public interface SessionDisconnectHandler {
      * @param option The violating {@link KexProposalOption}
      * @return {@code true} if disregard the violation - if {@code false} then
      * session will disconnect
+     * @throws IOException if attempted to exchange some packets to fix the 
situation
      */
     default boolean handleKexDisconnectReason(
             Session session, Map<KexProposalOption, String> c2sOptions, 
Map<KexProposalOption, String> s2cOptions,
-            Map<KexProposalOption, String> negotiatedGuess, KexProposalOption 
option) {
+            Map<KexProposalOption, String> negotiatedGuess, KexProposalOption 
option)
+                throws IOException {
         if (KexProposalOption.S2CLANG.equals(option) || 
KexProposalOption.C2SLANG.equals(option)) {
             return true;    // OK if cannot agree on a language
         }
diff --git 
a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
 
b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
index 827c20f..074488e 100644
--- 
a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
+++ 
b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
@@ -1568,13 +1568,22 @@ public abstract class AbstractSession extends 
SessionHelper {
                     continue;
                 }
 
-                if ((discHandler != null)
-                        && discHandler.handleKexDisconnectReason(
+                try {
+                    if ((discHandler != null)
+                            && discHandler.handleKexDisconnectReason(
                                 this, c2sOptions, s2cOptions, negotiatedGuess, 
paramType)) {
+                        if (debugEnabled) {
+                            log.debug("negotiate({}) ignore missing value for 
KEX option={}", this, paramType);
+                        }
+                        continue;
+                    }
+                } catch (IOException | RuntimeException e) {
+                    // If disconnect handler throws an exception continue with 
the disconnect
+                    log.warn("negotiate({}) failed ({}) to invoke disconnect 
handler due to mismatched KEX option={}: {}",
+                        this, e.getClass().getSimpleName(), paramType, 
e.getMessage());
                     if (debugEnabled) {
-                        log.debug("negotiate({}) ignore missing value for KEX 
option={}", this, paramType);
+                        log.debug("negotiate(" + this + ") handler invocation 
exception details", e);
                     }
-                    continue;
                 }
 
                 String message = "Unable to negotiate key exchange for " + 
paramType.getDescription()
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 5e91e32..95ea0ae 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
@@ -255,8 +255,20 @@ public abstract class SessionHelper extends 
AbstractKexFactoryManager implements
             return TimeoutIndicator.NONE;
         }
 
-        SessionDisconnectHandler handler = getSessionDisconnectHandler();
-        if ((handler != null) && handler.handleTimeoutDisconnectReason(this, 
result)) {
+        boolean resetTimeout = false;
+        try {
+            SessionDisconnectHandler handler = getSessionDisconnectHandler();
+            resetTimeout = (handler != null) && 
handler.handleTimeoutDisconnectReason(this, result);
+        } catch (RuntimeException | IOException e) {
+            // If disconnect handler throws an exception continue with the 
disconnect
+            log.warn("checkForTimeouts({}) failed ({}) to invoke disconnect 
handler to handle {}: {}",
+                this, e.getClass().getSimpleName(), result, e.getMessage());
+            if (log.isDebugEnabled()) {
+                log.debug("checkForTimeouts(" + this + ") disconnect handler 
exception details", e);
+            }
+        }
+
+        if (resetTimeout) {
             if (log.isDebugEnabled()) {
                 log.debug("checkForTimeouts({}) cancel {} due to handler 
intervention", this, result);
             }
diff --git 
a/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java
 
b/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java
index a882f78..5c6dfd3 100644
--- 
a/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java
+++ 
b/sshd-core/src/main/java/org/apache/sshd/server/session/AbstractServerSession.java
@@ -246,14 +246,22 @@ public abstract class AbstractServerSession extends 
AbstractSession implements S
          *      appropriate SSH_MSG_DISCONNECT message and MUST disconnect.
          */
         if (currentService == null) {
-            SessionDisconnectHandler handler = getSessionDisconnectHandler();
-            if ((handler != null)
-                    && handler.handleUnsupportedServiceDisconnectReason(
+            try {
+                SessionDisconnectHandler handler = 
getSessionDisconnectHandler();
+                if ((handler != null)
+                        && handler.handleUnsupportedServiceDisconnectReason(
                             this, SshConstants.SSH_MSG_SERVICE_REQUEST, name, 
buffer)) {
+                    if (log.isDebugEnabled()) {
+                        log.debug("startService({}) ignore unknown service={} 
by handler", this, name);
+                    }
+                    return;
+                }
+            } catch (IOException | RuntimeException e) {
+                log.warn("startService({})[{}] failed ({}) to invoke 
disconnect handler: {}",
+                    this, name, e.getClass().getSimpleName(), e.getMessage());
                 if (log.isDebugEnabled()) {
-                    log.debug("startService({}) ignore unknown service={} by 
handler", this, name);
+                    log.debug("startService(" + this + ")[" + name + "] 
disconnect handler invocation exception details", e);
                 }
-                return;
             }
 
             throw new 
SshException(SshConstants.SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE, "Unknown 
service: " + name);
@@ -309,18 +317,27 @@ public abstract class AbstractServerSession extends 
AbstractSession implements S
     protected void handleServiceAccept(String serviceName, Buffer buffer) 
throws Exception {
         super.handleServiceAccept(serviceName, buffer);
 
-        SessionDisconnectHandler handler = getSessionDisconnectHandler();
-        if ((handler != null)
-                && handler.handleUnsupportedServiceDisconnectReason(
+        try {
+            SessionDisconnectHandler handler = getSessionDisconnectHandler();
+            if ((handler != null)
+                    && handler.handleUnsupportedServiceDisconnectReason(
                         this, SshConstants.SSH_MSG_SERVICE_ACCEPT, 
serviceName, buffer)) {
+                if (log.isDebugEnabled()) {
+                    log.debug("handleServiceAccept({}) ignore unknown 
service={} by handler", this, serviceName);
+                }
+                return;
+            }
+        } catch (IOException | RuntimeException e) {
+            log.warn("handleServiceAccept({}) failed ({}) to invoke disconnect 
handler of unknown service={}: {}",
+                this, e.getClass().getSimpleName(), serviceName, 
e.getMessage());
             if (log.isDebugEnabled()) {
-                log.debug("handleServiceAccept({}) ignore unknown service={} 
by handler", this, serviceName);
+                log.debug("handleServiceAccept(" + this + ")[" + serviceName + 
"] handler invocation exception details", e);
             }
-            return;
         }
 
         // TODO: can services be initiated by the server-side ?
-        disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR, "Unsupported 
packet: SSH_MSG_SERVICE_ACCEPT for " + serviceName);
+        disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR,
+            "Unsupported packet: SSH_MSG_SERVICE_ACCEPT for " + serviceName);
     }
 
     @Override
diff --git 
a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
 
b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
index b6a1e55..e3e046b 100644
--- 
a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
+++ 
b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
@@ -37,6 +37,7 @@ import java.util.Map;
 import java.util.Objects;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.stream.Collectors;
 
 import org.apache.sshd.common.Factory;
@@ -162,108 +163,14 @@ public class ServerUserAuthService extends 
AbstractCloseable implements Service,
         Boolean authed = Boolean.FALSE;
         ServerSession session = getServerSession();
         boolean debugEnabled = log.isDebugEnabled();
-        if (cmd == SshConstants.SSH_MSG_USERAUTH_REQUEST) {
-            /*
-             * According to RFC4252 section 5.1:
-             *
-             *
-             *      When SSH_MSG_USERAUTH_SUCCESS has been sent, any
-             *      further authentication requests received after that
-             *      SHOULD be silently ignored.
-             */
-            if (session.isAuthenticated()) {
-                String username = buffer.getString();
-                String service = buffer.getString();
-                String method = buffer.getString();
-
-                if (debugEnabled) {
-                    log.debug("process({}) ignore user={}, service={}, 
method={} auth. request since session already authenticated",
-                        session, username, service, method);
-                }
-                return;
-            }
-
-            if (WelcomeBannerPhase.FIRST_REQUEST.equals(getWelcomePhase())) {
-                sendWelcomeBanner(session);
-            }
-
-            if (currentAuth != null) {
-                try {
-                    currentAuth.destroy();
-                } finally {
-                    currentAuth = null;
-                }
-            }
-
-            String username = buffer.getString();
-            String service = buffer.getString();
-            String method = buffer.getString();
-            if (debugEnabled) {
-                log.debug("process({}) Received SSH_MSG_USERAUTH_REQUEST 
user={}, service={}, method={}",
-                      session, username, service, method);
-            }
 
-            if ((this.authUserName == null) || (this.authService == null)) {
-                this.authUserName = username;
-                this.authService = service;
-            } else if (this.authUserName.equals(username) && 
this.authService.equals(service)) {
-                nbAuthRequests++;
-                if (nbAuthRequests > maxAuthRequests) {
-                    SessionDisconnectHandler handler = 
session.getSessionDisconnectHandler();
-                    if ((handler == null)
-                            || (!handler.handleAuthCountDisconnectReason(
-                                    session, this, service, method, username, 
nbAuthRequests, maxAuthRequests))) {
-                        
session.disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR,
-                            "Too many authentication failures: " + 
nbAuthRequests);
-                        return;
-                    }
-                }
-            } else {
-                SessionDisconnectHandler handler = 
session.getSessionDisconnectHandler();
-                if ((handler != null)
-                        && handler.handleAuthParamsDisconnectReason(
-                            session, this, this.authUserName, username, 
this.authService, service)) {
-                    if (debugEnabled) {
-                        log.debug("process({}) ignore mismatched 
authentication parameters: user={}/{}, service={}/{}",
-                                session, this.authUserName, username, 
this.authService, service);
-                    }
-                } else {
-                    
session.disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR,
-                        "Change of username or service is not allowed (" + 
this.authUserName + ", " + this.authService + ") -> ("
-                            + username + ", " + service + ")");
-                }
+        if (cmd == SshConstants.SSH_MSG_USERAUTH_REQUEST) {
+            AtomicReference<Boolean> authHolder = new 
AtomicReference<>(authed);
+            if (!handleUserAuthRequestMessage(session, buffer, authHolder)) {
                 return;
             }
 
-            // TODO: verify that the service is supported
-            this.authMethod = method;
-            if (debugEnabled) {
-                log.debug("process({}) Authenticating user '{}' with service 
'{}' and method '{}' (attempt {} / {})",
-                      session, username, service, method, nbAuthRequests, 
maxAuthRequests);
-            }
-
-            Factory<UserAuth> factory = NamedResource.findByName(method, 
String.CASE_INSENSITIVE_ORDER, userAuthFactories);
-            if (factory != null) {
-                currentAuth = ValidateUtils.checkNotNull(factory.create(), "No 
authenticator created for method=%s", method);
-                try {
-                    authed = currentAuth.auth(session, username, service, 
buffer);
-                } catch (AsyncAuthException async) {
-                    async.addListener(authenticated -> asyncAuth(cmd, buffer, 
authenticated));
-                    return;
-                } catch (Exception e) {
-                    if (debugEnabled) {
-                        log.debug("process({}) Failed ({}) to authenticate 
using factory method={}: {}",
-                              session, e.getClass().getSimpleName(), method, 
e.getMessage());
-                    }
-                    if (log.isTraceEnabled()) {
-                        log.trace("process(" + session + ") factory 
authentication=" + method + " failure details", e);
-                    }
-                }
-            } else {
-                if (debugEnabled) {
-                    log.debug("process({}) no authentication factory for 
method={}", session, method);
-                }
-            }
+            authed = authHolder.get();
         } else {
             if (WelcomeBannerPhase.FIRST_AUTHCMD.equals(getWelcomePhase())) {
                 sendWelcomeBanner(session);
@@ -306,6 +213,151 @@ public class ServerUserAuthService extends 
AbstractCloseable implements Service,
         }
     }
 
+    protected boolean handleUserAuthRequestMessage(
+            ServerSession session, Buffer buffer, AtomicReference<Boolean> 
authHolder)
+                throws Exception {
+        boolean debugEnabled = log.isDebugEnabled();
+        /*
+         * According to RFC4252 section 5.1:
+         *
+         *
+         *      When SSH_MSG_USERAUTH_SUCCESS has been sent, any
+         *      further authentication requests received after that
+         *      SHOULD be silently ignored.
+         */
+        if (session.isAuthenticated()) {
+            String username = buffer.getString();
+            String service = buffer.getString();
+            String method = buffer.getString();
+
+            if (debugEnabled) {
+                log.debug("handleUserAuthRequestMessage({}) ignore user={}, 
service={}, method={}"
+                    + " auth. request since session already authenticated",
+                    session, username, service, method);
+            }
+            return false;
+        }
+
+        if (WelcomeBannerPhase.FIRST_REQUEST.equals(getWelcomePhase())) {
+            sendWelcomeBanner(session);
+        }
+
+        if (currentAuth != null) {
+            try {
+                currentAuth.destroy();
+            } finally {
+                currentAuth = null;
+            }
+        }
+
+        String username = buffer.getString();
+        String service = buffer.getString();
+        String method = buffer.getString();
+        if (debugEnabled) {
+            log.debug("handleUserAuthRequestMessage({}) Received 
SSH_MSG_USERAUTH_REQUEST user={}, service={}, method={}",
+                  session, username, service, method);
+        }
+
+        if ((this.authUserName == null) || (this.authService == null)) {
+            this.authUserName = username;
+            this.authService = service;
+        } else if (this.authUserName.equals(username) && 
this.authService.equals(service)) {
+            nbAuthRequests++;
+            if (nbAuthRequests > maxAuthRequests) {
+                boolean disconnectSession = true;
+                try {
+                    SessionDisconnectHandler handler = 
session.getSessionDisconnectHandler();
+                    disconnectSession = (handler == null)
+                        || (!handler.handleAuthCountDisconnectReason(
+                                session, this, service, method, username, 
nbAuthRequests, maxAuthRequests));
+                } catch (IOException | RuntimeException e) {
+                    log.warn("handleUserAuthRequestMessage({}) failed ({}) to 
invoke disconnect handler due to"
+                        + " user={}/{}, service={}/{} - {}/{} auth requests: 
{}",
+                        session, e.getClass().getSimpleName(),
+                        this.authUserName, username, this.authService, service,
+                        nbAuthRequests, maxAuthRequests, e.getMessage());
+                    if (debugEnabled) {
+                        log.debug("process(" + session + ") disconnect handler 
auth requests count invocation exception", e);
+                    }
+                }
+
+                if (disconnectSession) {
+                    
session.disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR,
+                        "Too many authentication failures: " + nbAuthRequests);
+                    return false;
+                }
+
+                if (debugEnabled) {
+                    log.debug("handleUserAuthRequestMessage({}) ignore 
mismatched authentication counts: user={}/{}, service={}/{}: {}/{}",
+                        session, this.authUserName, username, 
this.authService, service, nbAuthRequests, maxAuthRequests);
+                }
+            }
+        } else {
+            boolean disconnectSession = true;
+            try {
+                SessionDisconnectHandler handler = 
session.getSessionDisconnectHandler();
+                disconnectSession = (handler == null)
+                    || (!handler.handleAuthParamsDisconnectReason(
+                            session, this, this.authUserName, username, 
this.authService, service));
+            } catch (IOException | RuntimeException e) {
+                log.warn("handleUserAuthRequestMessage({}) failed ({}) to 
invoke disconnect handler due to"
+                    + " user={}/{}, service={}/{} mismatched parameters: {}",
+                    session, e.getClass().getSimpleName(),
+                    this.authUserName, username, this.authService, service, 
e.getMessage());
+                if (debugEnabled) {
+                    log.debug("handleUserAuthRequestMessage(" + session + ") 
disconnect handler auth mismatched parameters invocation exception", e);
+                }
+            }
+
+            if (disconnectSession) {
+                session.disconnect(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR,
+                    "Change of username or service is not allowed (" + 
this.authUserName + ", " + this.authService + ")"
+                    + " -> (" + username + ", " + service + ")");
+            } else {
+                if (debugEnabled) {
+                    log.debug("handleUserAuthRequestMessage({}) ignore 
mismatched authentication parameters: user={}/{}, service={}/{}",
+                        session, this.authUserName, username, 
this.authService, service);
+                }
+            }
+            return false;
+        }
+
+        // TODO: verify that the service is supported
+        this.authMethod = method;
+        if (debugEnabled) {
+            log.debug("handleUserAuthRequestMessage({}) Authenticating user 
'{}' with service '{}' and method '{}' (attempt {} / {})",
+                  session, username, service, method, nbAuthRequests, 
maxAuthRequests);
+        }
+
+        Factory<UserAuth> factory = NamedResource.findByName(method, 
String.CASE_INSENSITIVE_ORDER, userAuthFactories);
+        if (factory == null) {
+            if (debugEnabled) {
+                log.debug("handleUserAuthRequestMessage({}) no authentication 
factory for method={}", session, method);
+            }
+
+            return true;
+        }
+
+        currentAuth = ValidateUtils.checkNotNull(factory.create(), "No 
authenticator created for method=%s", method);
+        try {
+            Boolean authed = currentAuth.auth(session, username, service, 
buffer);
+            authHolder.set(authed);
+        } catch (AsyncAuthException async) {
+            async.addListener(authenticated -> 
asyncAuth(SshConstants.SSH_MSG_USERAUTH_REQUEST, buffer, authenticated));
+            return false;
+        } catch (Exception e) {
+            if (debugEnabled) {
+                log.debug("handleUserAuthRequestMessage({}) Failed ({}) to 
authenticate using factory method={}: {}",
+                      session, e.getClass().getSimpleName(), method, 
e.getMessage());
+            }
+            if (log.isTraceEnabled()) {
+                log.trace("handleUserAuthRequestMessage(" + session + ") 
factory authentication=" + method + " failure details", e);
+            }
+        }
+
+        return true;
+    }
+
     protected synchronized void asyncAuth(int cmd, Buffer buffer, boolean 
authed) {
         try {
             if (authed) {
@@ -348,18 +400,29 @@ public class ServerUserAuthService extends 
AbstractCloseable implements Service,
             if (maxSessionCount != null) {
                 int currentSessionCount = 
session.getActiveSessionCountForUser(username);
                 if (currentSessionCount >= maxSessionCount) {
-                    SessionDisconnectHandler handler = 
session.getSessionDisconnectHandler();
-                    if ((handler == null)
+                    boolean disconnectSession = true;
+                    try {
+                        SessionDisconnectHandler handler = 
session.getSessionDisconnectHandler();
+                        disconnectSession = (handler == null)
                             || (!handler.handleSessionsCountDisconnectReason(
-                                    session, this, username, 
currentSessionCount, maxSessionCount))) {
+                                    session, this, username, 
currentSessionCount, maxSessionCount));
+                    } catch (IOException | RuntimeException e) {
+                        log.warn("handleAuthenticationSuccess({}@{}) failed 
({}) to invoke disconnect handler due to {}/{} sessions count: {}",
+                            username, session, e.getClass().getSimpleName(), 
currentSessionCount, maxSessionCount, e.getMessage());
+                        if (debugEnabled) {
+                            log.debug("handleAuthenticationSuccess(" + 
username + "@" + session + ") invocation handler exception details", e);
+                        }
+                    }
+
+                    if (disconnectSession) {
                         
session.disconnect(SshConstants.SSH2_DISCONNECT_TOO_MANY_CONNECTIONS,
                             "Too many concurrent connections (" + 
currentSessionCount + ") - max. allowed: " + maxSessionCount);
                         return;
-                    } else {
-                        if (debugEnabled) {
-                            log.debug("handleAuthenticationSuccess({}@{}) 
ignore {}/{} sessions count due to handler intervention",
-                                username, session, currentSessionCount, 
maxSessionCount);
-                        }
+                    }
+
+                    if (debugEnabled) {
+                        log.debug("handleAuthenticationSuccess({}@{}) ignore 
{}/{} sessions count due to handler intervention",
+                            username, session, currentSessionCount, 
maxSessionCount);
                     }
                 }
             }

Reply via email to