[Java] Print error stack trace when tests fail
[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.lang.reflect.InvocationTargetException;
10 import java.lang.reflect.Method;
11 import java.net.*;
12 import java.util.LinkedList;
13 import java.nio.Buffer;
14 import java.nio.ByteBuffer;
15 import java.nio.channels.*;
16
17 /**
18  * A NioPeerHandler maps LDK's PeerHandler to Java's NIO I/O interface. It spawns a single background thread which
19  * processes socket events and provides the data to LDK for decryption and processing.
20  */
21 public class NioPeerHandler {
22     private static class Peer {
23         SocketDescriptor descriptor;
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 Method ResultBoolPeerHandleError_Free;
53     static {
54         try {
55             Class c = Result_boolPeerHandleErrorZ.class;
56             ResultBoolPeerHandleError_Free = c.getDeclaredMethod("force_free");
57             ResultBoolPeerHandleError_Free.setAccessible(true);
58         } catch (NoSuchMethodException 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|CancelledKeyException ignored) {
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                         try { peer.key.cancel(); } catch (CancelledKeyException ignored) {}
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         return peer;
109     }
110
111     PeerManager peer_manager;
112     Thread io_thread;
113     final Selector selector;
114     long socket_id;
115     volatile boolean shutdown = false;
116
117     private static Option_SocketAddressZ get_netaddr_from_sockaddr(java.net.SocketAddress sockaddr) {
118         if (sockaddr instanceof InetSocketAddress) {
119             InetAddress addr = ((InetSocketAddress) sockaddr).getAddress();
120             short port = (short) ((InetSocketAddress) sockaddr).getPort();
121             if (addr instanceof Inet4Address) {
122                 return Option_SocketAddressZ.some(org.ldk.structs.SocketAddress.tcp_ip_v4(addr.getAddress(), port));
123             } else if (addr instanceof Inet6Address) {
124                 return Option_SocketAddressZ.some(org.ldk.structs.SocketAddress.tcp_ip_v6(addr.getAddress(), port));
125             }
126         }
127         return Option_SocketAddressZ.none();
128     }
129
130     /**
131      * Constructs a new peer handler, spawning a thread to monitor for socket events.
132      *
133      * @param manager The LDK PeerManager which connection data will be provided to.
134      * @throws IOException If an internal java.nio error occurs.
135      */
136     public NioPeerHandler(PeerManager manager) throws IOException {
137         this.peer_manager = manager;
138         this.selector = Selector.open();
139         io_thread = new Thread(() -> {
140             int BUF_SZ = 16 * 1024;
141             byte[] max_buf_byte_object = new byte[BUF_SZ];
142             ByteBuffer buf = ByteBuffer.allocate(BUF_SZ);
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                                     Option_SocketAddressZ netaddr = get_netaddr_from_sockaddr(chan.getRemoteAddress());
180                                     Result_NonePeerHandleErrorZ res = this.peer_manager.new_inbound_connection(peer.descriptor, netaddr);
181                                     if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_Err) {
182                                                                                 peer.descriptor.disconnect_socket();
183                                                                         }
184                                 } catch (IOException ignored) { }
185                             }
186                             continue; // There is no attachment so the rest of the loop is useless
187                         }
188                         Peer peer = (Peer) key.attachment();
189                         try {
190                             if (key.isValid() && (key.interestOps() & SelectionKey.OP_WRITE) != 0 && key.isWritable()) {
191                                 Result_NonePeerHandleErrorZ res = this.peer_manager.write_buffer_space_avail(peer.descriptor);
192                                 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_Err) {
193                                     key.cancel();
194                                     key.channel().close();
195                                 }
196                             }
197                             if (key.isValid() && (key.interestOps() & SelectionKey.OP_READ) != 0 && key.isReadable()) {
198                                 ((Buffer)buf).clear();
199                                 int read = ((SocketChannel) key.channel()).read(buf);
200                                 if (read == -1) {
201                                     this.peer_manager.socket_disconnected(peer.descriptor);
202                                     key.cancel();
203                                     key.channel().close(); // This may throw, we read -1 so the channel should already be closed, but do this to be safe
204                                 } else if (read > 0) {
205                                     ((Buffer)buf).flip();
206                                     byte[] read_bytes;
207                                     if (read == BUF_SZ) {
208                                         read_bytes = max_buf_byte_object;
209                                     } else {
210                                         read_bytes = new byte[read];
211                                     }
212                                     buf.get(read_bytes, 0, read);
213                                     Result_boolPeerHandleErrorZ read_res = this.peer_manager.read_event(peer.descriptor, read_bytes);
214                                     if (read_res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) {
215                                         if (((Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) read_res).res) {
216                                             key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
217                                         }
218                                         // Force the read_res to drop its native memory early (before finalize()) as this is
219                                         // pretty hot and we don't want to bloat native memory too long.
220                                         // Note that we only do this in the Ok case as its more trivially safe, the Err
221                                         // case has nested structs which will also free and may be confused if their pointer
222                                         // is dropped out from under them.
223                                         try { ResultBoolPeerHandleError_Free.invoke(read_res); } catch (Exception ignored) {}
224                                     } else {
225                                         key.cancel();
226                                         key.channel().close();
227                                     }
228                                 }
229                             }
230                         } catch (IOException ignored) {
231                             key.cancel();
232                             try { key.channel().close(); } catch (IOException ignored2) { }
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     /**
248      * Connect to a peer given their node id and socket address. Blocks until a connection is established (or returns
249      * IOException) and then the connection handling runs in the background.
250      *
251      * @param their_node_id A valid 33-byte public key representing the peer's Lightning Node ID. If this is invalid,
252      *                      undefined behavior (read: Segfault, etc) may occur.
253      * @param remote The socket address to connect to.
254      * @param timeout_ms The amount of time, in milliseconds, up to which we will wait for connection to complete.
255      * @throws IOException If connecting to the remote endpoint fails or internal java.nio errors occur.
256      */
257     public void connect(byte[] their_node_id, java.net.SocketAddress remote, int timeout_ms) throws IOException {
258         SocketChannel chan = SocketChannel.open();
259         boolean connected;
260         try {
261             chan.configureBlocking(false);
262             Selector open_selector = Selector.open();
263             chan.register(open_selector, SelectionKey.OP_CONNECT);
264             if (!chan.connect(remote)) {
265                 open_selector.select(timeout_ms);
266             }
267             connected = chan.finishConnect();
268         } catch (IOException e) {
269             try { chan.close(); } catch (IOException _e) { }
270             throw e;
271         }
272         if (!connected) {
273             try { chan.close(); } catch (IOException _e) { }
274             throw new IOException("Timed out");
275         }
276         Peer peer = setup_socket(chan);
277         do_selector_action(() -> peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer));
278         Result_CVec_u8ZPeerHandleErrorZ res = this.peer_manager.new_outbound_connection(their_node_id, peer.descriptor, get_netaddr_from_sockaddr(remote));
279         if (res instanceof  Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) {
280             byte[] initial_bytes = ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) res).res;
281             if (chan.write(ByteBuffer.wrap(initial_bytes)) != initial_bytes.length) {
282                 peer.descriptor.disconnect_socket();
283                 this.peer_manager.socket_disconnected(peer.descriptor);
284                 throw new IOException("We assume TCP socket buffer is at least a single packet in length");
285             }
286         } else {
287             peer.descriptor.disconnect_socket();
288             throw new IOException("LDK rejected outbound connection. This likely shouldn't ever happen.");
289         }
290     }
291
292     /**
293      * Disconnects any connections currently open with the peer with the given node id.
294      *
295      * @param their_node_id must be a valid 33-byte public key
296      */
297     public void disconnect(byte[] their_node_id) {
298         this.peer_manager.disconnect_by_node_id(their_node_id);
299     }
300
301     /**
302      * Before shutdown, we have to ensure all of our listening sockets are closed manually, as they appear
303      * to otherwise remain open and lying around on OSX (though no other platform).
304      */
305     private LinkedList<ServerSocketChannel> listening_sockets = new LinkedList();
306     /**
307      * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
308      * thread.
309      *
310      * @param socket_address The address to bind the listening socket to.
311      * @throws IOException if binding the listening socket fail.
312      */
313     public void bind_listener(java.net.SocketAddress socket_address) throws IOException {
314         ServerSocketChannel listen_channel = ServerSocketChannel.open();
315         listen_channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
316         listen_channel.bind(socket_address);
317         listen_channel.configureBlocking(false);
318         do_selector_action(() -> listen_channel.register(this.selector, SelectionKey.OP_ACCEPT));
319         synchronized(listening_sockets) {
320             listening_sockets.add(listen_channel);
321         }
322     }
323
324     /**
325      * Interrupt the background thread, stopping all peer handling.
326      *
327      * After this method is called, the behavior of future calls to methods on this NioPeerHandler are undefined.
328      */
329     public void interrupt() {
330         this.peer_manager.disconnect_all_peers();
331         shutdown = true;
332         selector.wakeup();
333         try {
334             io_thread.join();
335         } catch (InterruptedException ignored) { }
336         synchronized(listening_sockets) {
337             try {
338                 selector.close();
339                 for (ServerSocketChannel chan : listening_sockets) {
340                     chan.close();
341                 }
342                 listening_sockets.clear();
343             } catch (IOException ignored) {}
344         }
345         Reference.reachabilityFence(this.peer_manager); // Almost certainly overkill, but no harm in it
346     }
347
348     /**
349      * Calls process_events on the PeerManager immediately. Normally process_events is polled regularly to check for new
350      * messages which need to be sent, but you can interrupt the poll and check immediately by calling this function.
351      */
352     public void check_events() {
353         selector.wakeup();
354     }
355 }