Ensure listening sockets are closed to work around OSX breaking
authorMatt Corallo <git@bluematt.me>
Tue, 28 Sep 2021 04:46:02 +0000 (04:46 +0000)
committerMatt Corallo <git@bluematt.me>
Tue, 28 Sep 2021 04:46:58 +0000 (04:46 +0000)
src/main/java/org/ldk/batteries/NioPeerHandler.java

index faca477f599d284539385af23c0d09bde2987b0f..b722d96d8c1408568659466d87433821bf29bd18 100644 (file)
@@ -3,6 +3,7 @@ package org.ldk.batteries;
 import org.ldk.structs.*;
 
 import java.io.IOException;
+import java.util.LinkedList;
 import java.net.SocketAddress;
 import java.net.StandardSocketOptions;
 import java.nio.Buffer;
@@ -239,6 +240,11 @@ public class NioPeerHandler {
         this.peer_manager.disconnect_by_node_id(their_node_id, false);
     }
 
+    /**
+     * Before shutdown, we have to ensure all of our listening sockets are closed manually, as they appear
+     * to otherwise remain open and lying around on OSX (though no other platform).
+     */
+    private LinkedList<ServerSocketChannel> listening_sockets = new LinkedList();
     /**
      * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
      * thread.
@@ -248,9 +254,13 @@ public class NioPeerHandler {
      */
     public void bind_listener(SocketAddress socket_address) throws IOException {
         ServerSocketChannel listen_channel = ServerSocketChannel.open();
+        listen_channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
         listen_channel.bind(socket_address);
         listen_channel.configureBlocking(false);
         do_selector_action(() -> listen_channel.register(this.selector, SelectionKey.OP_ACCEPT));
+        synchronized(listening_sockets) {
+            listening_sockets.add(listen_channel);
+        }
     }
 
     /**
@@ -263,6 +273,14 @@ public class NioPeerHandler {
         try {
             io_thread.join();
         } catch (InterruptedException ignored) { }
+        synchronized(listening_sockets) {
+            try {
+                selector.close();
+                for (ServerSocketChannel chan : listening_sockets) {
+                    chan.close();
+                }
+            } catch (IOException ignored) {}
+        }
     }
 
     /**