Prevent exceptions being thrown during normal shutdown of NIO connections. This enables TLS connections to close cleanly.

git-svn-id: https://svn.apache.org/repos/asf/tomcat/tc8.0.x/trunk@1804561 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/java/org/apache/tomcat/util/net/NioEndpoint.java b/java/org/apache/tomcat/util/net/NioEndpoint.java
index ef71952..723a1eb 100644
--- a/java/org/apache/tomcat/util/net/NioEndpoint.java
+++ b/java/org/apache/tomcat/util/net/NioEndpoint.java
@@ -970,6 +970,22 @@
                 if (ka!=null) handler.release(ka);
                 else handler.release((SocketChannel)key.channel());
                 if (key.isValid()) key.cancel();
+                // If it is available, close the NioChannel first which should
+                // in turn close the underlying SocketChannel. The NioChannel
+                // needs to be closed first, if available, to ensure that TLS
+                // connections are shut down cleanly.
+                if (ka != null) {
+                    try {
+                        ka.getSocket().close(true);
+                    } catch (Exception e){
+                        if (log.isDebugEnabled()) {
+                            log.debug(sm.getString(
+                                    "endpoint.debug.socketCloseFail"), e);
+                        }
+                    }
+                }
+                // The SocketChannel is also available via the SelectionKey. If
+                // it hasn't been closed in the block above, close it now.
                 if (key.channel().isOpen()) {
                     try {
                         key.channel().close();
@@ -981,16 +997,6 @@
                     }
                 }
                 try {
-                    if (ka!=null) {
-                        ka.getSocket().close(true);
-                    }
-                } catch (Exception e){
-                    if (log.isDebugEnabled()) {
-                        log.debug(sm.getString(
-                                "endpoint.debug.socketCloseFail"), e);
-                    }
-                }
-                try {
                     if (ka != null && ka.getSendfileData() != null
                             && ka.getSendfileData().fchannel != null
                             && ka.getSendfileData().fchannel.isOpen()) {
diff --git a/webapps/docs/changelog.xml b/webapps/docs/changelog.xml
index f79e074..ada9b71 100644
--- a/webapps/docs/changelog.xml
+++ b/webapps/docs/changelog.xml
@@ -105,6 +105,10 @@
         <code>maxThreads</code> from the Executor when calculating the point at
         which to disable keep-alive. (markt)
       </fix>
+      <fix>
+        Prevent exceptions being thrown during normal shutdown of NIO
+        connections. This enables TLS connections to close cleanly. (markt)
+      </fix>
     </changelog>
   </subsection>
   <subsection name="Jasper">