2ab48d627a67c0405d985cd6fdaf78969b276ff1
[ldk-java] / src / main / java / org / ldk / batteries / NioPeerHandler.java
1 package org.ldk.batteries;
2
3 import org.ldk.impl.bindings;
4 import org.ldk.structs.*;
5
6 import java.io.IOException;
7 import java.lang.reflect.Field;
8 import java.lang.ref.Reference;
9 import java.util.LinkedList;
10 import java.net.SocketAddress;
11 import java.net.StandardSocketOptions;
12 import java.nio.Buffer;
13 import java.nio.ByteBuffer;
14 import java.nio.channels.*;
15
16 /**
17  * A NioPeerHandler maps LDK's PeerHandler to Java's NIO I/O interface. It spawns a single background thread which
18  * processes socket events and provides the data to LDK for decryption and processing.
19  */
20 public class NioPeerHandler {
21     private static class Peer {
22         SocketDescriptor descriptor;
23         long descriptor_raw_pointer;
24         SelectionKey key;
25     }
26
27     // Android's java.nio implementation has a big lock inside the selector, preventing any concurrent access to it.
28     // This appears to largely defeat the entire purpose of java.nio, but we work around it here by explicitly checking
29     // for an Android environment and passing any selector access on any thread other than our internal one through
30     // do_selector_action, which wakes up the selector before accessing it.
31     private static boolean IS_ANDROID;
32     static {
33         IS_ANDROID = System.getProperty("java.vendor").toLowerCase().contains("android");
34     }
35     private boolean wakeup_selector = false;
36     private interface SelectorCall {
37         void meth() throws IOException;
38     }
39     private void do_selector_action(SelectorCall meth) throws IOException {
40         if (IS_ANDROID) {
41             wakeup_selector = true;
42             this.selector.wakeup();
43             synchronized (this.selector) {
44                 meth.meth();
45                 wakeup_selector = false;
46             }
47         } else {
48             meth.meth();
49         }
50     }
51
52     static private Field CommonBasePointer;
53     static {
54         try {
55             Class c = PeerManager.class.getSuperclass();
56             CommonBasePointer = c.getDeclaredField("ptr");
57             CommonBasePointer.setAccessible(true);
58             long _dummy_check = CommonBasePointer.getLong(Ping.of((short)0, (short)0));
59         } catch (NoSuchFieldException | IllegalAccessException e) {
60             throw new IllegalArgumentException(
61                     "We currently use reflection to access protected fields as Java has no reasonable access controls", e);
62         }
63     }
64
65     private Peer setup_socket(SocketChannel chan) throws IOException {
66         chan.configureBlocking(false);
67         // Lightning tends to send a number of small messages back and forth between peers quickly, which Nagle is
68         // particularly bad at handling, so we disable it here.
69         chan.setOption(StandardSocketOptions.TCP_NODELAY, true);
70         long our_id;
71         synchronized (this) {
72             this.socket_id = this.socket_id + 1;
73             our_id = this.socket_id;
74         }
75
76         final Peer peer = new Peer();
77         SocketDescriptor descriptor = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
78             @Override
79             public long send_data(byte[] data, boolean resume_read) {
80                 try {
81                     long written = chan.write(ByteBuffer.wrap(data));
82                     if (written != data.length) {
83                         do_selector_action(() -> peer.key.interestOps(
84                                                         (peer.key.interestOps() | SelectionKey.OP_WRITE) & (~SelectionKey.OP_READ)));
85                     } else if (resume_read) {
86                         do_selector_action(() -> peer.key.interestOps(
87                                                         (peer.key.interestOps() | SelectionKey.OP_READ) & (~SelectionKey.OP_WRITE)));
88                                         }
89                     return written;
90                 } catch (IOException|CancelledKeyException ignored) {
91                     // Most likely the socket is disconnected, let the background thread handle it.
92                     return 0;
93                 }
94             }
95
96             @Override
97             public void disconnect_socket() {
98                 try {
99                     do_selector_action(() -> {
100                         try { peer.key.cancel(); } catch (CancelledKeyException ignored) {}
101                         peer.key.channel().close();
102                     });
103                 } catch (IOException ignored) { }
104             }
105             @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == our_id; }
106             @Override public long hash() { return our_id; }
107         });
108         peer.descriptor = descriptor;
109         try {
110             peer.descriptor_raw_pointer = CommonBasePointer.getLong(descriptor);
111         } catch (IllegalAccessException e) {
112             throw new IllegalArgumentException(
113                     "We currently use reflection to access protected fields as Java has no reasonable access controls", e);
114         }
115         return peer;
116     }
117
118     PeerManager peer_manager;
119     Thread io_thread;
120     final Selector selector;
121     long socket_id;
122     volatile boolean shutdown = false;
123
124     /**
125      * Constructs a new peer handler, spawning a thread to monitor for socket events.
126      *
127      * @param manager The LDK PeerManager which connection data will be provided to.
128      * @throws IOException If an internal java.nio error occurs.
129      */
130     public NioPeerHandler(PeerManager manager) throws IOException {
131         this.peer_manager = manager;
132         this.selector = Selector.open();
133         io_thread = new Thread(() -> {
134             int BUF_SZ = 16 * 1024;
135             byte[] max_buf_byte_object = new byte[BUF_SZ];
136             ByteBuffer buf = ByteBuffer.allocate(BUF_SZ);
137
138             long peer_manager_raw_pointer;
139             try {
140                 peer_manager_raw_pointer = CommonBasePointer.getLong(this.peer_manager);
141             } catch (IllegalAccessException e) {
142                 throw new RuntimeException(e);
143             }
144             while (true) {
145                 try {
146                     if (IS_ANDROID) {
147                         while (true) {
148                             synchronized (this.selector) {
149                                 if (!wakeup_selector) {
150                                     this.selector.select(1000);
151                                     break;
152                                 }
153                             }
154                         }
155                     } else {
156                         this.selector.select(1000);
157                     }
158                 } catch (IOException ignored) {
159                     System.err.println("java.nio threw an unexpected IOException. Stopping PeerHandler thread!");
160                     return;
161                 }
162                 if (shutdown) return;
163                 if (Thread.interrupted()) return;
164                 for (SelectionKey key : this.selector.selectedKeys()) {
165                     try {
166                         if ((key.interestOps() & SelectionKey.OP_ACCEPT) != 0) {
167                             if (key.isAcceptable()) {
168                                 SocketChannel chan;
169                                 try {
170                                     chan = ((ServerSocketChannel) key.channel()).accept();
171                                 } catch (IOException ignored) {
172                                     key.cancel();
173                                     continue;
174                                 }
175                                 if (chan == null) continue;
176                                 try {
177                                     Peer peer = setup_socket(chan);
178                                     peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer);
179                                     Result_NonePeerHandleErrorZ res = this.peer_manager.new_inbound_connection(peer.descriptor);
180                                     if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_Err) {
181                                                                                 peer.descriptor.disconnect_socket();
182                                                                         }
183                                 } catch (IOException ignored) { }
184                             }
185                             continue; // There is no attachment so the rest of the loop is useless
186                         }
187                         Peer peer = (Peer) key.attachment();
188                         try {
189                             if (key.isValid() && (key.interestOps() & SelectionKey.OP_WRITE) != 0 && key.isWritable()) {
190                                 Result_NonePeerHandleErrorZ res = this.peer_manager.write_buffer_space_avail(peer.descriptor);
191                                 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_Err) {
192                                     key.cancel();
193                                     key.channel().close();
194                                 }
195                             }
196                             if (key.isValid() && (key.interestOps() & SelectionKey.OP_READ) != 0 && key.isReadable()) {
197                                 ((Buffer)buf).clear();
198                                 int read = ((SocketChannel) key.channel()).read(buf);
199                                 if (read == -1) {
200                                     this.peer_manager.socket_disconnected(peer.descriptor);
201                                     key.cancel();
202                                     key.channel().close(); // This may throw, we read -1 so the channel should already be closed, but do this to be safe
203                                 } else if (read > 0) {
204                                     ((Buffer)buf).flip();
205                                     // This code is quite hot during initial network graph sync, so we go a ways out of
206                                     // our way to avoid object allocations that'll make the GC sweat later -
207                                     // * when we're hot, we'll likely often be reading the full buffer, so we keep
208                                     //   around a full-buffer-sized byte array to reuse across reads,
209                                     // * We use the manual memory management call logic directly in bindings instead of
210                                     //   the nice "human-readable" wrappers. This puts us at risk of memory issues,
211                                     //   so we indirectly ensure compile fails if the types change by writing the
212                                     //   "human-readable" form of the same code in the dummy function below.
213                                     byte[] read_bytes;
214                                     if (read == BUF_SZ) {
215                                         read_bytes = max_buf_byte_object;
216                                     } else {
217                                         read_bytes = new byte[read];
218                                     }
219                                     buf.get(read_bytes, 0, read);
220                                     long read_result_pointer = bindings.PeerManager_read_event(
221                                             peer_manager_raw_pointer, peer.descriptor_raw_pointer, read_bytes);
222                                     if (bindings.CResult_boolPeerHandleErrorZ_is_ok(read_result_pointer)) {
223                                         if (bindings.CResult_boolPeerHandleErrorZ_get_ok(read_result_pointer)) {
224                                             key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
225                                         }
226                                     } else {
227                                         key.cancel();
228                                         key.channel().close();
229                                     }
230                                     bindings.CResult_boolPeerHandleErrorZ_free(read_result_pointer);
231                                 }
232                             }
233                         } catch (IOException ignored) {
234                             key.cancel();
235                             try { key.channel().close(); } catch (IOException ignored2) { }
236                             peer_manager.socket_disconnected(peer.descriptor);
237                         }
238                     } catch (CancelledKeyException e) {
239                         try { key.channel().close(); } catch (IOException ignored) { }
240                         // The key is only cancelled when we have notified the PeerManager that the socket is closed, so
241                         // no need to do anything here with the PeerManager.
242                     }
243                 }
244                 peer_manager.process_events();
245             }
246         }, "NioPeerHandler NIO Thread");
247         io_thread.start();
248     }
249
250     // Ensure the types used in the above manual code match what they were when the code was written.
251     // Ensure the above manual bindings.* code changes if this fails to compile.
252     private void dummy_check_return_type_matches_manual_memory_code_above(Peer peer) {
253         byte[] read_bytes = new byte[32];
254         Result_boolPeerHandleErrorZ res = this.peer_manager.read_event(peer.descriptor, read_bytes);
255     }
256
257     /**
258      * Connect to a peer given their node id and socket address. Blocks until a connection is established (or returns
259      * IOException) and then the connection handling runs in the background.
260      *
261      * @param their_node_id A valid 33-byte public key representing the peer's Lightning Node ID. If this is invalid,
262      *                      undefined behavior (read: Segfault, etc) may occur.
263      * @param remote The socket address to connect to.
264      * @param timeout_ms The amount of time, in milliseconds, up to which we will wait for connection to complete.
265      * @throws IOException If connecting to the remote endpoint fails or internal java.nio errors occur.
266      */
267     public void connect(byte[] their_node_id, SocketAddress remote, int timeout_ms) throws IOException {
268         SocketChannel chan = SocketChannel.open();
269         boolean connected;
270         try {
271             chan.configureBlocking(false);
272             Selector open_selector = Selector.open();
273             chan.register(open_selector, SelectionKey.OP_CONNECT);
274             if (!chan.connect(remote)) {
275                 open_selector.select(timeout_ms);
276             }
277             connected = chan.finishConnect();
278         } catch (IOException e) {
279             try { chan.close(); } catch (IOException _e) { }
280             throw e;
281         }
282         if (!connected) {
283             try { chan.close(); } catch (IOException _e) { }
284             throw new IOException("Timed out");
285         }
286         Peer peer = setup_socket(chan);
287         do_selector_action(() -> peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer));
288         Result_CVec_u8ZPeerHandleErrorZ res = this.peer_manager.new_outbound_connection(their_node_id, peer.descriptor);
289         if (res instanceof  Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) {
290             byte[] initial_bytes = ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) res).res;
291             if (chan.write(ByteBuffer.wrap(initial_bytes)) != initial_bytes.length) {
292                 peer.descriptor.disconnect_socket();
293                 this.peer_manager.socket_disconnected(peer.descriptor);
294                 throw new IOException("We assume TCP socket buffer is at least a single packet in length");
295             }
296         } else {
297             peer.descriptor.disconnect_socket();
298             throw new IOException("LDK rejected outbound connection. This likely shouldn't ever happen.");
299         }
300     }
301
302     /**
303      * Disconnects any connections currently open with the peer with the given node id.
304      *
305      * @param their_node_id must be a valid 33-byte public key
306      */
307     public void disconnect(byte[] their_node_id) {
308         this.peer_manager.disconnect_by_node_id(their_node_id, false);
309     }
310
311     /**
312      * Before shutdown, we have to ensure all of our listening sockets are closed manually, as they appear
313      * to otherwise remain open and lying around on OSX (though no other platform).
314      */
315     private LinkedList<ServerSocketChannel> listening_sockets = new LinkedList();
316     /**
317      * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
318      * thread.
319      *
320      * @param socket_address The address to bind the listening socket to.
321      * @throws IOException if binding the listening socket fail.
322      */
323     public void bind_listener(SocketAddress socket_address) throws IOException {
324         ServerSocketChannel listen_channel = ServerSocketChannel.open();
325         listen_channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
326         listen_channel.bind(socket_address);
327         listen_channel.configureBlocking(false);
328         do_selector_action(() -> listen_channel.register(this.selector, SelectionKey.OP_ACCEPT));
329         synchronized(listening_sockets) {
330             listening_sockets.add(listen_channel);
331         }
332     }
333
334     /**
335      * Interrupt the background thread, stopping all peer handling. Disconnection events to the PeerHandler are not made,
336      * potentially leaving the PeerHandler in an inconsistent state.
337      */
338     public void interrupt() {
339         shutdown = true;
340         selector.wakeup();
341         try {
342             io_thread.join();
343         } catch (InterruptedException ignored) { }
344         synchronized(listening_sockets) {
345             try {
346                 selector.close();
347                 for (ServerSocketChannel chan : listening_sockets) {
348                     chan.close();
349                 }
350             } catch (IOException ignored) {}
351         }
352         Reference.reachabilityFence(this.peer_manager); // Almost certainly overkill, but no harm in it
353     }
354
355     /**
356      * Calls process_events on the PeerManager immediately. Normally process_events is polled regularly to check for new
357      * messages which need to be sent, but you can interrupt the poll and check immediately by calling this function.
358      */
359     public void check_events() {
360         selector.wakeup();
361     }
362 }