Avoid use of covariant return type change fns fixing backwards compat
[ldk-java] / src / main / java / org / ldk / batteries / NioPeerHandler.java
1 package org.ldk.batteries;
2
3 import org.ldk.structs.*;
4
5 import java.io.IOException;
6 import java.net.SocketAddress;
7 import java.net.StandardSocketOptions;
8 import java.nio.Buffer;
9 import java.nio.ByteBuffer;
10 import java.nio.channels.*;
11
12 /**
13  * A NioPeerHandler maps LDK's PeerHandler to Java's NIO I/O interface. It spawns a single background thread which
14  * processes socket events and provides the data to LDK for decryption and processing.
15  */
16 public class NioPeerHandler {
17     private static class Peer {
18         SocketDescriptor descriptor;
19         // When we are told by LDK to disconnect, we can't return to LDK until we are sure
20         // won't call any more read/write PeerManager functions with the same connection.
21         // This is set to true if we're in such a condition (with disconnect checked
22         // before with the Peer monitor lock held) and false when we can return.
23         boolean block_disconnect_socket = false;
24         // Indicates LDK told us to disconnect this peer, and thus we should not call socket_disconnected.
25         boolean disconnect_requested = false;
26         SelectionKey key;
27     }
28
29     // Android's java.nio implementation has a big lock inside the selector, preventing any concurrent access to it.
30     // This appears to largely defeat the entire purpose of java.nio, but we work around it here by explicitly checking
31     // for an Android environment and passing any selector access on any thread other than our internal one through
32     // do_selector_action, which wakes up the selector before accessing it.
33     private static boolean IS_ANDROID;
34     static {
35         IS_ANDROID = System.getProperty("java.vendor").toLowerCase().contains("android");
36     }
37     private boolean wakeup_selector = false;
38     private interface SelectorCall {
39         void meth() throws IOException;
40     }
41     private void do_selector_action(SelectorCall meth) throws IOException {
42         if (IS_ANDROID) {
43             wakeup_selector = true;
44             this.selector.wakeup();
45             synchronized (this.selector) {
46                 meth.meth();
47                 wakeup_selector = false;
48             }
49         } else {
50             meth.meth();
51         }
52     }
53
54     private Peer setup_socket(SocketChannel chan) throws IOException {
55         chan.configureBlocking(false);
56         // Lightning tends to send a number of small messages back and forth between peers quickly, which Nagle is
57         // particularly bad at handling, so we disable it here.
58         chan.setOption(StandardSocketOptions.TCP_NODELAY, true);
59         long our_id;
60         synchronized (this) {
61             this.socket_id = this.socket_id + 1;
62             our_id = this.socket_id;
63         }
64
65         final Peer peer = new Peer();
66         SocketDescriptor descriptor = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
67             @Override
68             public long send_data(byte[] data, boolean resume_read) {
69                 try {
70                     if (resume_read) {
71                         do_selector_action(() -> peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_READ));
72                     }
73                     long written = chan.write(ByteBuffer.wrap(data));
74                     if (written != data.length) {
75                         do_selector_action(() -> peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_WRITE));
76                     }
77                     return written;
78                 } catch (IOException e) {
79                     // Most likely the socket is disconnected, let the background thread handle it.
80                     return 0;
81                 }
82             }
83
84             @Override
85             public void disconnect_socket() {
86                 synchronized (peer) {
87                     peer.disconnect_requested = true;
88                 }
89                 try {
90                     do_selector_action(() -> {
91                         peer.key.cancel();
92                         peer.key.channel().close();
93                     });
94                 } catch (IOException ignored) { }
95                 synchronized (peer) {
96                     while (peer.block_disconnect_socket) {
97                         try {
98                             peer.wait();
99                         } catch (InterruptedException ignored) { }
100                     }
101                 }
102             }
103             @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == our_id; }
104             @Override public long hash() { return our_id; }
105         });
106         peer.descriptor = descriptor;
107         return peer;
108     }
109
110     PeerManager peer_manager;
111     Thread io_thread;
112     final Selector selector;
113     long socket_id;
114     volatile boolean shutdown = false;
115
116     /**
117      * Constructs a new peer handler, spawning a thread to monitor for socket events.
118      * The background thread will call the PeerManager's timer_tick_occured() function for you on an appropriate schedule.
119      *
120      * @param manager The LDK PeerManager which connection data will be provided to.
121      * @throws IOException If an internal java.nio error occurs.
122      */
123     public NioPeerHandler(PeerManager manager) throws IOException {
124         this.peer_manager = manager;
125         this.selector = Selector.open();
126         io_thread = new Thread(() -> {
127             ByteBuffer buf = ByteBuffer.allocate(8192);
128             long lastTimerTick = System.currentTimeMillis();
129             while (true) {
130                 try {
131                     if (IS_ANDROID) {
132                         while (true) {
133                             synchronized (this.selector) {
134                                 if (!wakeup_selector) {
135                                     this.selector.select(1000);
136                                     break;
137                                 }
138                             }
139                         }
140                     } else {
141                         this.selector.select(1000);
142                     }
143                 } catch (IOException ignored) {
144                     System.err.println("java.nio threw an unexpected IOException. Stopping PeerHandler thread!");
145                     return;
146                 }
147                 if (shutdown) return;
148                 if (Thread.interrupted()) return;
149                 for (SelectionKey key : this.selector.selectedKeys()) {
150                     try {
151                         if ((key.interestOps() & SelectionKey.OP_ACCEPT) != 0) {
152                             if (key.isAcceptable()) {
153                                 SocketChannel chan;
154                                 try {
155                                     chan = ((ServerSocketChannel) key.channel()).accept();
156                                 } catch (IOException ignored) {
157                                     key.cancel();
158                                     continue;
159                                 }
160                                 if (chan == null) continue;
161                                 try {
162                                     Peer peer = setup_socket(chan);
163                                     Result_NonePeerHandleErrorZ res = this.peer_manager.new_inbound_connection(peer.descriptor);
164                                     if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_OK) {
165                                         peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer);
166                                     }
167                                 } catch (IOException ignored) { }
168                             }
169                             continue; // There is no attachment so the rest of the loop is useless
170                         }
171                         Peer peer = (Peer) key.attachment();
172                         synchronized (peer) {
173                             if (peer.disconnect_requested)
174                                 continue;
175                             peer.block_disconnect_socket = true;
176                         }
177                         try {
178                             if (key.isValid() && (key.interestOps() & SelectionKey.OP_WRITE) != 0 && key.isWritable()) {
179                                 Result_NonePeerHandleErrorZ res = this.peer_manager.write_buffer_space_avail(peer.descriptor);
180                                 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_Err) {
181                                     key.channel().close();
182                                     key.cancel();
183                                 }
184                             }
185                             if (key.isValid() && (key.interestOps() & SelectionKey.OP_READ) != 0 && key.isReadable()) {
186                                 ((Buffer)buf).clear();
187                                 int read = ((SocketChannel) key.channel()).read(buf);
188                                 if (read == -1) {
189                                     this.peer_manager.socket_disconnected(peer.descriptor);
190                                     key.cancel();
191                                 } else if (read > 0) {
192                                     ((Buffer)buf).flip();
193                                     byte[] read_bytes = new byte[read];
194                                     buf.get(read_bytes, 0, read);
195                                     Result_boolPeerHandleErrorZ res = this.peer_manager.read_event(peer.descriptor, read_bytes);
196                                     if (res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) {
197                                         if (((Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) res).res) {
198                                             key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
199                                         }
200                                     } else {
201                                         key.channel().close();
202                                         key.cancel();
203                                     }
204                                 }
205                             }
206                         } catch (IOException ignored) {
207                             try { key.channel().close(); } catch (IOException ignored2) { }
208                             key.cancel();
209                             peer_manager.socket_disconnected(peer.descriptor);
210                         }
211                         synchronized (peer) {
212                             peer.block_disconnect_socket = false;
213                             peer.notifyAll();
214                         }
215                     } catch (CancelledKeyException e) {
216                         try { key.channel().close(); } catch (IOException ignored) { }
217                         // The key is only cancelled when we have notified the PeerManager that the socket is closed, so
218                         // no need to do anything here with the PeerManager.
219                     }
220                 }
221                 if (lastTimerTick < System.currentTimeMillis() - 30 * 1000) {
222                     peer_manager.timer_tick_occurred();
223                     lastTimerTick = System.currentTimeMillis();
224                 }
225                 peer_manager.process_events();
226             }
227         }, "NioPeerHandler NIO Thread");
228         io_thread.start();
229     }
230
231     /**
232      * Connect to a peer given their node id and socket address. Blocks until a connection is established (or returns
233      * IOException) and then the connection handling runs in the background.
234      *
235      * @param their_node_id A valid 33-byte public key representing the peer's Lightning Node ID. If this is invalid,
236      *                      undefined behavior (read: Segfault, etc) may occur.
237      * @param remote The socket address to connect to.
238      * @param timeout_ms The amount of time, in milliseconds, up to which we will wait for connection to complete.
239      * @throws IOException If connecting to the remote endpoint fails or internal java.nio errors occur.
240      */
241     public void connect(byte[] their_node_id, SocketAddress remote, int timeout_ms) throws IOException {
242         SocketChannel chan = SocketChannel.open();
243         chan.configureBlocking(false);
244         Selector open_selector = Selector.open();
245         chan.register(open_selector, SelectionKey.OP_CONNECT);
246         if (!chan.connect(remote)) {
247             open_selector.select(timeout_ms);
248         }
249         if (!chan.finishConnect()) { // Note that this may throw its own IOException if we failed for another reason
250             throw new IOException("Timed out");
251         }
252         Peer peer = setup_socket(chan);
253         Result_CVec_u8ZPeerHandleErrorZ res = this.peer_manager.new_outbound_connection(their_node_id, peer.descriptor);
254         if (res instanceof  Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) {
255             byte[] initial_bytes = ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) res).res;
256             if (chan.write(ByteBuffer.wrap(initial_bytes)) != initial_bytes.length) {
257                 throw new IOException("We assume TCP socket buffer is at least a single packet in length");
258             }
259             do_selector_action(() -> peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer));
260         } else {
261             throw new IOException("LDK rejected outbound connection. This likely shouldn't ever happen.");
262         }
263     }
264
265     /**
266      * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
267      * thread.
268      *
269      * @param socket_address The address to bind the listening socket to.
270      * @throws IOException if binding the listening socket fail.
271      */
272     public void bind_listener(SocketAddress socket_address) throws IOException {
273         ServerSocketChannel listen_channel = ServerSocketChannel.open();
274         listen_channel.bind(socket_address);
275         listen_channel.configureBlocking(false);
276         do_selector_action(() -> listen_channel.register(this.selector, SelectionKey.OP_ACCEPT));
277     }
278
279     /**
280      * Interrupt the background thread, stopping all peer handling. Disconnection events to the PeerHandler are not made,
281      * potentially leaving the PeerHandler in an inconsistent state.
282      */
283     public void interrupt() {
284         shutdown = true;
285         selector.wakeup();
286         try {
287             io_thread.join();
288         } catch (InterruptedException ignored) { }
289     }
290
291     /**
292      * Calls process_events on the PeerManager immediately. Normally process_events is polled regularly to check for new
293      * messages which need to be sent, but you can interrupt the poll and check immediately by calling this function.
294      */
295     public void check_events() {
296         selector.wakeup();
297     }
298 }