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