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/02/28 03:05:50 UTC

[mina-sshd] 04/04: [SSHD-901] Provided hook for user customized session heartbeat mechanism

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

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

commit e83a26a0272c15e4510195c0f369a5c4a29e8b9b
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Feb 28 05:12:39 2019 +0200

    [SSHD-901] Provided hook for user customized session heartbeat mechanism
---
 CHANGES.md                                         |  8 ++++-
 docs/client-setup.md                               |  9 +++++-
 docs/event-listeners.md                            |  3 ++
 docs/server-setup.md                               |  6 ++++
 .../common/session/SessionHeartbeatController.java |  9 ++++--
 .../session/ReservedSessionMessagesHandler.java    | 17 ++++++++++
 .../session/helpers/AbstractConnectionService.java | 36 ++++++++++++++++------
 7 files changed, 74 insertions(+), 14 deletions(-)

diff --git a/CHANGES.md b/CHANGES.md
index 206c5ed..d458670 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -38,7 +38,13 @@ then the internal `DefaultClientKexExtensionHandler` is used.
 
 ## Behavioral changes and enhancements
 
-* [SSHD-782](https://issues.apache.org/jira/browse/SSHD-882) - Added session level heartbeat mechanism via `SSH_MSG_IGNORE`.
+* [SSHD-782](https://issues.apache.org/jira/browse/SSHD-882) - Added session level heartbeat mechanism via `SSH_MSG_IGNORE`
+or customized user provided code.
+
+In order to support customized user code for this feature, the `ReservedSessionMessagesHandler` can be used to
+implement any kind of user-defined heartbeat. *Note:* if the user configured such a mechanism, then the
+`sendReservedHeartbeat` method **must** be implemented since the default throws `UnsupportedOperationException`
+which will cause the session to be terminated the 1st time the method is invoked.
 
 * [SSHD-882](https://issues.apache.org/jira/browse/SSHD-882) - Provide hooks to allow users to register a consumer
 for STDERR data sent via the `ChannelSession` - especially for the SFTP subsystem.
diff --git a/docs/client-setup.md b/docs/client-setup.md
index ce0fffc..797d7b6 100644
--- a/docs/client-setup.md
+++ b/docs/client-setup.md
@@ -182,6 +182,13 @@ regardless of the user's own traffic:
     willing to wait for the server's reply to the global request.
 
 
+* Customized user code
+
+    In order to support customized user code for this feature, the `ReservedSessionMessagesHandler` can be used to
+    implement any kind of user-defined heartbeat. *Note:* if the user configured such a mechanism, then the
+    `sendReservedHeartbeat` method **must** be implemented since the default throws `UnsupportedOperationException`
+    which will cause the session to be terminated the 1st time the method is invoked.
+
 **Note(s):**
 
 * Both options are disabled by default - they need to be activated explicitly.
@@ -189,7 +196,7 @@ regardless of the user's own traffic:
 * Both options can be activated either on the `SshClient` (for **global** setup) and/or
 the `ClientSession` (for specific session configuration).
 
-* The `keepalive@,,,,` mechanism **supersedes** the `SSH_MSG_IGNORE` one if both activated.
+* The `keepalive@,,,,` mechanism **supersedes** the the other mechanisms if activated.
 
     * If specified timeout expires for the `wantReply` option then session will be **closed**.
 
diff --git a/docs/event-listeners.md b/docs/event-listeners.md
index 2557a69..eda2d27 100644
--- a/docs/event-listeners.md
+++ b/docs/event-listeners.md
@@ -94,6 +94,9 @@ Can be used to handle the following cases:
 * [SSH_MSG_IGNORE](https://tools.ietf.org/html/rfc4253#section-11.2)
 * [SSH_MSG_DEBUG](https://tools.ietf.org/html/rfc4253#section-11.3)
 * [SSH_MSG_UNIMPLEMENTED](https://tools.ietf.org/html/rfc4253#section-11.4)
+* Implementing a custom session heartbeat mechanism - for **both**
+[client](./client-setup.md#keeping-the-session-alive-while-no-traffic)
+or [server](./server-setup.md#providing-server-side-heartbeat).
 * Any other unrecognized message received in the session.
 
 **Note:** The `handleUnimplementedMessage` method serves both for handling `SSH_MSG_UNIMPLEMENTED` and any other unrecognized
diff --git a/docs/server-setup.md b/docs/server-setup.md
index 3992c63..3e6b2db 100644
--- a/docs/server-setup.md
+++ b/docs/server-setup.md
@@ -150,3 +150,9 @@ it is highly recommended to use the API - unless one needs to control these prop
 
 If one is using the SSHD CLI code, then these options are controlled via `-o ServerAliveInterval=NNNN` where the value is
 the requested **global** interval in **seconds**. *Note*: any non-positive value is treated as if the feature is disabled.
+
+In order to support customized user code for this feature, the `ReservedSessionMessagesHandler` can be used to
+implement any kind of user-defined heartbeat. *Note:* if the user configured such a mechanism, then the
+`sendReservedHeartbeat` method **must** be implemented since the default throws `UnsupportedOperationException`
+which will cause the session to be terminated the 1st time the method is invoked.
+
diff --git a/sshd-common/src/main/java/org/apache/sshd/common/session/SessionHeartbeatController.java b/sshd-common/src/main/java/org/apache/sshd/common/session/SessionHeartbeatController.java
index ce02b80..be1f75d 100644
--- a/sshd-common/src/main/java/org/apache/sshd/common/session/SessionHeartbeatController.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/session/SessionHeartbeatController.java
@@ -36,7 +36,9 @@ public interface SessionHeartbeatController extends PropertyResolver {
         /** No heartbeat */
         NONE,
         /** Use {@code SSH_MSG_IGNORE} packets */
-        IGNORE;
+        IGNORE,
+        /** Custom mechanism via {@code ReservedSessionMessagesHandler} */
+        RESERVED;
 
         public static final Set<HeartbeatType> VALUES = EnumSet.allOf(HeartbeatType.class);
 
@@ -60,13 +62,16 @@ public interface SessionHeartbeatController extends PropertyResolver {
     /** Property used to register the interval for the heartbeat - if not set or non-positive then disabled */
     String SESSION_HEARTBEAT_INTERVAL = "session-connection-heartbeat-interval";
 
+    /** Default value for {@value #SESSION_HEARTBEAT_INTERVAL} if none set */
+    long DEFAULT_CONNECTION_HEARTBEAT_INTERVAL = 0L;
+
     default HeartbeatType getSessionHeartbeatType() {
         Object value = getObject(SESSION_HEARTBEAT_TYPE);
         return PropertyResolverUtils.toEnum(HeartbeatType.class, value, false, HeartbeatType.VALUES);
     }
 
     default long getSessionHeartbeatInterval() {
-        return getLongProperty(SESSION_HEARTBEAT_INTERVAL, 0L);
+        return getLongProperty(SESSION_HEARTBEAT_INTERVAL, DEFAULT_CONNECTION_HEARTBEAT_INTERVAL);
     }
 
     /**
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/ReservedSessionMessagesHandler.java b/sshd-core/src/main/java/org/apache/sshd/common/session/ReservedSessionMessagesHandler.java
index e229eb0..3eea967 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/ReservedSessionMessagesHandler.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/ReservedSessionMessagesHandler.java
@@ -69,4 +69,21 @@ public interface ReservedSessionMessagesHandler extends SshdEventListener {
     default boolean handleUnimplementedMessage(Session session, int cmd, Buffer buffer) throws Exception {
         return false;
     }
+
+    /**
+     * Invoked if the user configured usage of a proprietary heartbeat mechanism.
+     * <B>Note:</B> by default throws {@code UnsupportedOperationException} so
+     * users who configure a proprietary heartbeat mechanism option must provide
+     * an implementation for this method.
+     *
+     * @param service The {@link ConnectionService} through which the heartbeat
+     * is being executed.
+     * @return {@code true} whether heartbeat actually sent - <B>Note:</B> used
+     * mainly for debugging purposes.
+     * @throws Exception If failed to send the heartbeat - <B>Note:</B> causes
+     * associated session termination.
+     */
+    default boolean sendReservedHeartbeat(ConnectionService service) throws Exception {
+        throw new UnsupportedOperationException("Reserved heartbeat not implemented for " + service);
+    }
 }
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 9ac6077..4b40ff1 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
@@ -56,6 +56,7 @@ import org.apache.sshd.common.forward.PortForwardingEventListenerManager;
 import org.apache.sshd.common.io.AbstractIoWriteFuture;
 import org.apache.sshd.common.io.IoWriteFuture;
 import org.apache.sshd.common.session.ConnectionService;
+import org.apache.sshd.common.session.ReservedSessionMessagesHandler;
 import org.apache.sshd.common.session.Session;
 import org.apache.sshd.common.session.UnknownChannelReferenceHandler;
 import org.apache.sshd.common.util.EventListenerUtils;
@@ -226,20 +227,35 @@ public abstract class AbstractConnectionService
                 session, heartbeatType, interval);
         }
 
-        if ((heartbeatType == null) || (heartbeatType == HeartbeatType.NONE)
-                || (interval <= 0L) || (heartBeat == null)) {
+        if ((heartbeatType == null) || (interval <= 0L) || (heartBeat == null)) {
             return false;
         }
 
         try {
-            Buffer buffer = session.createBuffer(
-                SshConstants.SSH_MSG_IGNORE, DEFAULT_SESSION_IGNORE_HEARTBEAT_STRING.length() + Byte.SIZE);
-            buffer.putString(DEFAULT_SESSION_IGNORE_HEARTBEAT_STRING);
-
-            IoWriteFuture future = session.writePacket(buffer);
-            future.addListener(this::futureDone);
-            return true;
-        } catch (IOException | RuntimeException | Error e) {
+            switch (heartbeatType) {
+                case NONE:
+                    return false;
+                case IGNORE: {
+                    Buffer buffer = session.createBuffer(
+                        SshConstants.SSH_MSG_IGNORE, DEFAULT_SESSION_IGNORE_HEARTBEAT_STRING.length() + Byte.SIZE);
+                    buffer.putString(DEFAULT_SESSION_IGNORE_HEARTBEAT_STRING);
+
+                    IoWriteFuture future = session.writePacket(buffer);
+                    future.addListener(this::futureDone);
+                    return true;
+                }
+                case RESERVED: {
+                    ReservedSessionMessagesHandler handler =
+                        Objects.requireNonNull(
+                            session.getReservedSessionMessagesHandler(),
+                            "No customized heartbeat handler registered");
+                    return handler.sendReservedHeartbeat(this);
+                }
+                default:
+                    throw new UnsupportedOperationException("Unsupported heartbeat type: " + heartbeatType);
+            }
+
+        } catch (Throwable e) {
             session.exceptionCaught(e);
             if (log.isDebugEnabled()) {
                 log.debug("sendHeartBeat({}) failed ({}) to send heartbeat #{} request={}: {}",