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