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 f92106b165c763fbbd7f5cc2853683cfeae90b3d
Author: Lyor Goldstein <[email protected]>
AuthorDate: Tue Apr 16 10:24:19 2019 +0300

    [SSHD-902] Implemented 'handleEof' method for MINA and Netty sessions
---
 .../apache/sshd/common/io/mina/MinaSession.java    | 60 ++++++++++++++++++
 .../sshd/common/io/mina/MinaSessionTest.java       | 43 +++++++++++++
 .../java/org/apache/sshd/netty/NettyIoSession.java | 72 +++++++++++++++++++++-
 .../org/apache/sshd/netty/NettyIoSessionTest.java  | 43 +++++++++++++
 4 files changed, 216 insertions(+), 2 deletions(-)

diff --git 
a/sshd-mina/src/main/java/org/apache/sshd/common/io/mina/MinaSession.java 
b/sshd-mina/src/main/java/org/apache/sshd/common/io/mina/MinaSession.java
index 1b231ff..c32f677 100644
--- a/sshd-mina/src/main/java/org/apache/sshd/common/io/mina/MinaSession.java
+++ b/sshd-mina/src/main/java/org/apache/sshd/common/io/mina/MinaSession.java
@@ -18,12 +18,19 @@
  */
 package org.apache.sshd.common.io.mina;
 
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.net.Socket;
 import java.net.SocketAddress;
+import java.nio.channels.Channel;
+import java.nio.channels.SocketChannel;
 import java.util.Objects;
+import java.util.stream.Stream;
 
 import org.apache.mina.core.buffer.IoBuffer;
 import org.apache.mina.core.future.IoFutureListener;
 import org.apache.mina.core.future.WriteFuture;
+import org.apache.mina.transport.socket.nio.NioSession;
 import org.apache.sshd.common.Closeable;
 import org.apache.sshd.common.future.CloseFuture;
 import org.apache.sshd.common.future.DefaultCloseFuture;
@@ -32,6 +39,7 @@ import org.apache.sshd.common.io.AbstractIoWriteFuture;
 import org.apache.sshd.common.io.IoService;
 import org.apache.sshd.common.io.IoSession;
 import org.apache.sshd.common.io.IoWriteFuture;
+import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.NumberUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.closeable.AbstractInnerCloseable;
@@ -41,6 +49,15 @@ import org.apache.sshd.common.util.closeable.IoBaseCloseable;
  * @author <a href="mailto:[email protected]";>Apache MINA SSHD Project</a>
  */
 public class MinaSession extends AbstractInnerCloseable implements IoSession {
+    public static final Field NIO_SESSION_CHANNEL_FIELD =
+        Stream.of(NioSession.class.getDeclaredFields())
+            .filter(f -> "channel".equals(f.getName()))
+            .map(f -> {
+                f.setAccessible(true);
+                return f;
+            }).findFirst()
+            .orElse(null);
+
     private final MinaService service;
     private final org.apache.mina.core.session.IoSession session;
     private final Object sessionWriteId;
@@ -191,6 +208,49 @@ public class MinaSession extends AbstractInnerCloseable 
implements IoSession {
         return service;
     }
 
+    @Override   // see SSHD-902
+    public void handleEof() throws IOException {
+        boolean debugEnabled = log.isDebugEnabled();
+        if (!(session instanceof NioSession)) {
+            if (debugEnabled) {
+                log.debug("handleEof({}) not a NioSession: {}",
+                    session, (session == null) ? null : 
session.getClass().getSimpleName());
+            }
+            return;
+        }
+
+        if (NIO_SESSION_CHANNEL_FIELD == null) {
+            if (debugEnabled) {
+                log.debug("handleEof({}) missing channel field",
+                    session, (session == null) ? null : 
session.getClass().getSimpleName());
+            }
+            return;
+        }
+
+        Channel channel;
+        try {
+            channel = (Channel) NIO_SESSION_CHANNEL_FIELD.get(session);
+        } catch (Exception t) {
+            Throwable e = GenericUtils.peelException(t);
+            log.warn("handleEof({}) failed ({}) to retrieve embedded channel: 
{}",
+                session, e.getClass().getSimpleName(), e.getMessage());
+            return;
+        }
+
+        if (!(channel instanceof SocketChannel)) {
+            if (debugEnabled) {
+                log.debug("handleEof({}) not a SocketChannel: {}",
+                    session, (channel == null) ? null : 
channel.getClass().getSimpleName());
+            }
+            return;
+        }
+
+        Socket socket = ((SocketChannel) channel).socket();
+        if (socket.isConnected() && (!socket.isClosed())) {
+            socket.shutdownOutput();
+        }
+    }
+
     @Override
     public String toString() {
         return getClass().getSimpleName()
diff --git 
a/sshd-mina/src/test/java/org/apache/sshd/common/io/mina/MinaSessionTest.java 
b/sshd-mina/src/test/java/org/apache/sshd/common/io/mina/MinaSessionTest.java
new file mode 100644
index 0000000..929b295
--- /dev/null
+++ 
b/sshd-mina/src/test/java/org/apache/sshd/common/io/mina/MinaSessionTest.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sshd.common.io.mina;
+
+import org.apache.sshd.util.test.JUnitTestSupport;
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runners.MethodSorters;
+
+/**
+ * TODO Add javadoc
+ *
+ * @author <a href="mailto:[email protected]";>Apache MINA SSHD Project</a>
+ */
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class MinaSessionTest extends JUnitTestSupport {
+    public MinaSessionTest() {
+        super();
+    }
+
+    @Test   // SSHD-902
+    public void testNioSessionChannelFieldExistsAndAccessible() {
+        assertNotNull("Field has not been detected", 
MinaSession.NIO_SESSION_CHANNEL_FIELD);
+        assertTrue("Field is inaccessible", 
MinaSession.NIO_SESSION_CHANNEL_FIELD.isAccessible());
+    }
+}
diff --git a/sshd-netty/src/main/java/org/apache/sshd/netty/NettyIoSession.java 
b/sshd-netty/src/main/java/org/apache/sshd/netty/NettyIoSession.java
index 580765d..0a3365e 100644
--- a/sshd-netty/src/main/java/org/apache/sshd/netty/NettyIoSession.java
+++ b/sshd-netty/src/main/java/org/apache/sshd/netty/NettyIoSession.java
@@ -19,10 +19,16 @@
 
 package org.apache.sshd.netty;
 
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.net.Socket;
 import java.net.SocketAddress;
+import java.nio.channels.SelectableChannel;
+import java.nio.channels.SocketChannel;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Objects;
+import java.util.stream.Stream;
 
 import org.apache.sshd.common.future.CloseFuture;
 import org.apache.sshd.common.io.AbstractIoWriteFuture;
@@ -31,6 +37,7 @@ import org.apache.sshd.common.io.IoHandler;
 import org.apache.sshd.common.io.IoService;
 import org.apache.sshd.common.io.IoSession;
 import org.apache.sshd.common.io.IoWriteFuture;
+import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.closeable.AbstractCloseable;
 
@@ -42,6 +49,7 @@ import io.netty.channel.ChannelFutureListener;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelInboundHandlerAdapter;
 import io.netty.channel.ChannelPromise;
+import io.netty.channel.nio.AbstractNioChannel;
 import io.netty.util.Attribute;
 
 /**
@@ -51,6 +59,15 @@ import io.netty.util.Attribute;
  * @author <a href="mailto:[email protected]";>Apache MINA SSHD Project</a>
  */
 public class NettyIoSession extends AbstractCloseable implements IoSession {
+    public static final Method NIO_JAVA_CHANNEL_METHOD =
+        Stream.of(AbstractNioChannel.class.getDeclaredMethods())
+            .filter(m -> "javaChannel".equals(m.getName()) && 
(m.getParameterCount() == 0))
+            .map(m -> {
+                m.setAccessible(true);
+                return m;
+            }).findFirst()
+            .orElse(null);
+
     protected final Map<Object, Object> attributes = new HashMap<>();
     protected final NettyIoService service;
     protected final IoHandler handler;
@@ -111,8 +128,8 @@ public class NettyIoSession extends AbstractCloseable 
implements IoSession {
 
     @Override
     public SocketAddress getLocalAddress() {
-        Channel channel = context.channel();
-        return channel.localAddress();
+        Channel channel = (context == null) ? null : context.channel();
+        return (channel == null) ? null : channel.localAddress();
     }
 
     @Override
@@ -148,6 +165,49 @@ public class NettyIoSession extends AbstractCloseable 
implements IoSession {
         return service;
     }
 
+    @Override   // see SSHD-902
+    public void handleEof() throws IOException {
+        Channel ch = context.channel();
+        boolean debugEnabled = log.isDebugEnabled();
+        if (!(ch instanceof AbstractNioChannel)) {
+            if (debugEnabled) {
+                log.debug("handleEof({}) channel is not AbstractNioChannel: 
{}",
+                    this, (ch == null) ? null : ch.getClass().getSimpleName());
+            }
+            return;
+        }
+
+        if (NIO_JAVA_CHANNEL_METHOD == null) {
+            if (debugEnabled) {
+                log.debug("handleEof({}) missing channel access method", this);
+            }
+            return;
+        }
+
+        SelectableChannel channel;
+        try {
+            channel = (SelectableChannel) NIO_JAVA_CHANNEL_METHOD.invoke(ch, 
GenericUtils.EMPTY_OBJECT_ARRAY);
+        } catch (Exception t) {
+            Throwable e = GenericUtils.peelException(t);
+            log.warn("handleEof({}) failed ({}) to retrieve embedded channel: 
{}",
+                this, e.getClass().getSimpleName(), e.getMessage());
+            return;
+        }
+
+        if (!(channel instanceof SocketChannel)) {
+            if (debugEnabled) {
+                log.debug("handleEof({}) not a SocketChannel: {}",
+                    this, (channel == null) ? null : 
channel.getClass().getSimpleName());
+            }
+            return;
+        }
+
+        Socket socket = ((SocketChannel) channel).socket();
+        if (socket.isConnected() && (!socket.isClosed())) {
+            socket.shutdownOutput();
+        }
+    }
+
     @Override
     protected CloseFuture doCloseGracefully() {
         context.writeAndFlush(Unpooled.EMPTY_BUFFER)
@@ -198,6 +258,14 @@ public class NettyIoSession extends AbstractCloseable 
implements IoSession {
         handler.exceptionCaught(NettyIoSession.this, cause);
     }
 
+    @Override
+    public String toString() {
+        return getClass().getSimpleName()
+            + "[local=" + getLocalAddress()
+            + ", remote=" + getRemoteAddress()
+            + "]";
+    }
+
     protected static class DefaultIoWriteFuture extends AbstractIoWriteFuture {
         public DefaultIoWriteFuture(Object id, Object lock) {
             super(id, lock);
diff --git 
a/sshd-netty/src/test/java/org/apache/sshd/netty/NettyIoSessionTest.java 
b/sshd-netty/src/test/java/org/apache/sshd/netty/NettyIoSessionTest.java
new file mode 100644
index 0000000..158e04c
--- /dev/null
+++ b/sshd-netty/src/test/java/org/apache/sshd/netty/NettyIoSessionTest.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sshd.netty;
+
+import org.apache.sshd.util.test.JUnitTestSupport;
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runners.MethodSorters;
+
+/**
+ * TODO Add javadoc
+ *
+ * @author <a href="mailto:[email protected]";>Apache MINA SSHD Project</a>
+ */
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class NettyIoSessionTest extends JUnitTestSupport {
+    public NettyIoSessionTest() {
+        super();
+    }
+
+    @Test
+    public void testJavaChannelMethodExistsAndAccessible() {
+        assertNotNull("Missing channel extraction method", 
NettyIoSession.NIO_JAVA_CHANNEL_METHOD);
+        assertTrue("Channel extraction method is inaccessible", 
NettyIoSession.NIO_JAVA_CHANNEL_METHOD.isAccessible());
+    }
+}

Reply via email to