Merge pull request #46 from TheBlueMatt/main
[ldk-c-bindings] / ldk-net / ldk_net.c
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 /**
11  * This file implements what you need to get networking up with LDK using
12  * standard POSIX APIs. Its not particularly effecient (in fact quite the
13  * opposite) but should be more than sufficient for most use-cases.
14  */
15
16 #include "ldk_net.h"
17
18 #include <lightning.h>
19
20 #include <sys/socket.h>
21 #include <sys/time.h>
22 #include <netinet/in.h>
23 #include <netinet/tcp.h>
24 #include <pthread.h>
25 #include <poll.h>
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <errno.h>
29 #include <assert.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stddef.h>
33
34 #ifndef MSG_NOSIGNAL
35 #define MSG_NOSIGNAL 0
36 #define IS_BSD
37 #endif
38
39 #define MAX_CONNS 1024
40 struct SocketHandler {
41         struct LDKPeerManager ldk_peer_manager;
42         pthread_t socket_thread;
43         bool should_exit;
44         int pipefds[2];
45         // pollfds ands sockcount may only be written to with a lock on
46         // sockets_mutex.
47         // sockcount mut always be the number of sockets in pollfds
48         // Items in pollfds may only be removed in the socket_thread, other threads
49         // may only append new file descriptors at the end (via register_socket).
50         pthread_mutex_t sockets_mutex;
51         struct pollfd pollfds[MAX_CONNS];
52         nfds_t sockcount;
53 };
54
55 int register_socket(struct SocketHandler* handler, int fd, int is_listen_sock) {
56         int fd_flags = fcntl(fd, F_GETFL, 0);
57         if (fd_flags < 0) return -1;
58         if (fcntl(fd, F_SETFL, fd_flags | O_NONBLOCK) == -1) return -1;
59
60         if (!is_listen_sock) {
61                 int opt = 1;
62                 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void*)&opt, sizeof(opt))) return -1;
63 #ifdef IS_BSD
64                 if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&opt, sizeof(opt))) return -1;
65 #endif
66         }
67
68         int lockres = pthread_mutex_lock(&handler->sockets_mutex);
69         assert(lockres == 0);
70
71         handler->pollfds[handler->sockcount].fd = fd;
72         handler->pollfds[handler->sockcount].events = POLLIN;
73         handler->pollfds[handler->sockcount].revents = 0;
74         handler->sockcount++;
75         assert(handler->sockcount <= MAX_CONNS);
76
77         lockres = pthread_mutex_unlock(&handler->sockets_mutex);
78         assert(lockres == 0);
79
80         uint8_t dummy = 0;
81         write(handler->pipefds[1], &dummy, 1);
82
83         return 0;
84 }
85
86 struct Descriptor {
87         struct SocketHandler *handler;
88         int fd;
89 };
90
91 static uintptr_t sock_send_data(void* desc, struct LDKu8slice data, bool resume_read) {
92         struct Descriptor *descriptor = (struct Descriptor*)desc;
93         ssize_t write_count = send(descriptor->fd, data.data, data.datalen, MSG_NOSIGNAL);
94         bool pause_read = false;
95         if (write_count <= 0) {
96                 if (errno == EAGAIN || errno == EWOULDBLOCK) {
97                         pause_read = true;
98                         write_count = 0;
99                 } else {
100                         shutdown(descriptor->fd, SHUT_RDWR);
101                         uint8_t dummy = 0;
102                         write(descriptor->handler->pipefds[1], &dummy, 1);
103                         return 0;
104                 }
105         } else if (write_count < data.datalen) {
106                 pause_read = true;
107         }
108         if (pause_read || resume_read) {
109                 int lockres = pthread_mutex_lock(&descriptor->handler->sockets_mutex);
110                 assert(lockres == 0);
111                 for (int i = 0; i < descriptor->handler->sockcount; i++) {
112                         if (descriptor->handler->pollfds[i].fd == descriptor->fd) {
113                                 if (pause_read) {
114                                         descriptor->handler->pollfds[i].events = POLLOUT;
115                                 } else {
116                                         descriptor->handler->pollfds[i].events = POLLIN;
117                                 }
118                                 break;
119                         }
120                 }
121                 lockres = pthread_mutex_unlock(&descriptor->handler->sockets_mutex);
122                 assert(lockres == 0);
123                 uint8_t dummy = 0;
124                 write(descriptor->handler->pipefds[1], &dummy, 1);
125         }
126
127         return write_count;
128 }
129 static void sock_disconnect(void* desc) {
130         struct Descriptor *descriptor = (struct Descriptor*)desc;
131         shutdown(descriptor->fd, SHUT_RDWR);
132         uint8_t dummy = 0;
133         write(descriptor->handler->pipefds[1], &dummy, 1);
134 }
135 static bool sock_eq(const void* desc, const struct LDKSocketDescriptor *other_arg) {
136         const struct Descriptor *descriptor = (const struct Descriptor*)desc;
137         const struct Descriptor *other_descriptor = (const struct Descriptor*)other_arg->this_arg;
138         return descriptor->fd == other_descriptor->fd;
139 }
140 static uint64_t sock_hash(const void* desc) {
141         const struct Descriptor *descriptor = (const struct Descriptor*)desc;
142         return (uint64_t)descriptor->fd;
143 }
144 static void sock_cloned(LDKSocketDescriptor *NONNULL_PTR ldk_desc) {
145         const struct Descriptor *descriptor = (const struct Descriptor*)ldk_desc->this_arg;
146         struct Descriptor *new_desc = malloc(sizeof(struct Descriptor));
147         new_desc->handler = descriptor->handler;
148         new_desc->fd = descriptor->fd;
149         ldk_desc->this_arg = (void*) new_desc;
150 }
151 static void sock_free(void* desc) {
152         free(desc);
153 }
154
155 static inline LDKSocketDescriptor get_descriptor(struct SocketHandler *handler, int fd) {
156         struct Descriptor *desc = malloc(sizeof(struct Descriptor));
157         desc->handler = handler;
158         desc->fd = fd;
159         LDKSocketDescriptor ret = {
160                 .this_arg = (void*)desc,
161                 .send_data = sock_send_data,
162                 .disconnect_socket = sock_disconnect,
163                 .eq = sock_eq,
164                 .hash = sock_hash,
165                 .cloned = sock_cloned,
166                 .free = sock_free,
167         };
168         return ret;
169 }
170
171 static void *sock_thread_fn(void* arg) {
172         struct SocketHandler *handler = (struct SocketHandler*) arg;
173
174         int lockres;
175         struct pollfd pollfds[MAX_CONNS + 1];
176         int fd_count;
177
178         int close_socks[MAX_CONNS];
179         int close_socks_count = 0;
180
181         uint8_t readbuf[8192];
182
183         while (!handler->should_exit) {
184                 {
185                         lockres = pthread_mutex_lock(&handler->sockets_mutex);
186                         assert(lockres == 0);
187                         memcpy(pollfds, handler->pollfds, sizeof(struct pollfd) * handler->sockcount);
188                         fd_count = handler->sockcount;
189                         lockres = pthread_mutex_unlock(&handler->sockets_mutex);
190                         assert(lockres == 0);
191                 }
192                 pollfds[fd_count].fd = handler->pipefds[0];
193                 pollfds[fd_count].events = POLLIN;
194                 fd_count++;
195
196                 int pollres = poll(pollfds, fd_count, 10000);
197                 assert(pollres != -1);
198                 close_socks_count = 0;
199
200                 read(pollfds[fd_count-1].fd, readbuf, sizeof(readbuf)); // Empty out the pipe
201
202                 if (pollres > 0) {
203                         for (int i = 0; i < fd_count - 1; i++) {
204                                 if (pollfds[i].revents) {
205                                         LDKSocketDescriptor descriptor = get_descriptor(handler, pollfds[i].fd);
206                                         if (pollfds[i].revents & POLLIN) {
207                                                 int readlen = read(pollfds[i].fd, readbuf, sizeof(readbuf));
208                                                 if (readlen < 0) {
209                                                         if (errno == EAGAIN || errno == EWOULDBLOCK) {
210                                                                 // Spurious wake.
211                                                         } else if (errno == EINVAL || errno == ENOTCONN) {
212                                                                 // Assume we're a listening socket!
213                                                                 int newfd = accept(pollfds[i].fd, NULL, NULL);
214                                                                 if (newfd >= 0) {
215                                                                         // Received a new connection, register it!
216                                                                         LDKSocketDescriptor new_descriptor = get_descriptor(handler, newfd);
217                                                                         LDKCResult_NonePeerHandleErrorZ con_res = PeerManager_new_inbound_connection(&handler->ldk_peer_manager, new_descriptor);
218                                                                         if (con_res.result_ok) {
219                                                                                 if (register_socket(handler, newfd, 0))
220                                                                                         shutdown(newfd, SHUT_RDWR);
221                                                                         } else
222                                                                                 close(newfd);
223                                                                         CResult_NonePeerHandleErrorZ_free(con_res);
224                                                                 } else {
225                                                                         // Maybe it wasn't a listening socket, disconnect!
226                                                                         close_socks[close_socks_count++] = i;
227                                                                 }
228                                                         } else {
229                                                                 close_socks[close_socks_count++] = i;
230                                                         }
231                                                 } else if (readlen == 0) {
232                                                         // EOF
233                                                         close_socks[close_socks_count++] = i;
234                                                 } else {
235                                                         LDKu8slice data = {
236                                                                 .data = readbuf,
237                                                                 .datalen = readlen,
238                                                         };
239                                                         LDKCResult_boolPeerHandleErrorZ res = PeerManager_read_event(&handler->ldk_peer_manager, &descriptor, data);
240                                                         if (res.result_ok) {
241                                                                 if (*res.contents.result) {
242                                                                         lockres = pthread_mutex_lock(&handler->sockets_mutex);
243                                                                         assert(lockres == 0);
244                                                                         assert(handler->pollfds[i - 1].fd == pollfds[i].fd); // Only we change fd order!
245                                                                         handler->pollfds[i - 1].events = POLLOUT;
246                                                                         lockres = pthread_mutex_unlock(&handler->sockets_mutex);
247                                                                         assert(lockres == 0);
248                                                                 }
249                                                         } else {
250                                                                 close_socks[close_socks_count++] = i;
251                                                         }
252                                                         CResult_boolPeerHandleErrorZ_free(res);
253                                                 }
254                                         }
255                                         if (pollfds[i].revents & POLLOUT) {
256                                                 LDKCResult_NonePeerHandleErrorZ res = PeerManager_write_buffer_space_avail(&handler->ldk_peer_manager, &descriptor);
257                                                 if (!res.result_ok) {
258                                                         close_socks[close_socks_count++] = i;
259                                                 }
260                                                 CResult_NonePeerHandleErrorZ_free(res);
261                                         }
262                                         SocketDescriptor_free(descriptor);
263                                 }
264                         }
265                 }
266
267                 // We only do the actual socket disconnect handling in this thread,
268                 // other threads may append to pollfds and call shutdown().
269                 // Thus, in this thread, we first call socket_disconnected for each
270                 // socket we're gonna remove, then we walk the sockets and close() each
271                 // which should be disconnecting, shifting the remaining sockets down
272                 // as we walk.
273                 for (int i = 0; i < close_socks_count; i++) {
274                         LDKSocketDescriptor descriptor = get_descriptor(handler, handler->pollfds[close_socks[i]].fd);
275                         PeerManager_socket_disconnected(&handler->ldk_peer_manager, &descriptor);
276                         SocketDescriptor_free(descriptor);
277                 }
278
279                 lockres = pthread_mutex_lock(&handler->sockets_mutex);
280                 assert(lockres == 0);
281                 int close_idx = 0;
282                 for (int i = 0; close_socks_count != 0 && i < handler->sockcount; i++) {
283                         if (close_idx < close_socks_count && close_socks[close_idx] == i) {
284                                 close(handler->pollfds[i].fd);
285                                 close_idx++;
286                         } else {
287                                 handler->pollfds[i-close_idx] = handler->pollfds[i];
288                         }
289                 }
290                 assert(close_idx == close_socks_count);
291                 handler->sockcount -= close_socks_count;
292                 lockres = pthread_mutex_unlock(&handler->sockets_mutex);
293                 assert(lockres == 0);
294
295                 PeerManager_process_events(&handler->ldk_peer_manager);
296         }
297
298         lockres = pthread_mutex_lock(&handler->sockets_mutex);
299         assert(lockres == 0);
300         for (int i = 0; i < handler->sockcount; i++) {
301                 LDKSocketDescriptor descriptor = get_descriptor(handler, handler->pollfds[i].fd);
302                 PeerManager_socket_disconnected(&handler->ldk_peer_manager, &descriptor);
303                 SocketDescriptor_free(descriptor);
304         }
305
306         for (int i = 0; i < handler->sockcount; i++) {
307                 close(handler->pollfds[i].fd);
308         }
309         close(handler->pipefds[0]);
310         close(handler->pipefds[1]);
311         handler->sockcount = 0;
312         lockres = pthread_mutex_unlock(&handler->sockets_mutex);
313         assert(lockres == 0);
314
315         return NULL;
316 }
317
318
319 void* init_socket_handling(const struct LDKPeerManager *NONNULL_PTR ldk_peer_manager) {
320         struct SocketHandler *handler = NULL;
321
322         handler = (struct SocketHandler*) calloc(1, sizeof(struct SocketHandler));
323         if (!handler) goto err;
324         handler->pipefds[0] = -1;
325         handler->pipefds[1] = -1;
326
327         handler->ldk_peer_manager = *ldk_peer_manager;
328         handler->should_exit = false;
329
330         if (pipe(handler->pipefds) != 0) goto err;
331
332         int fd_flags = fcntl(handler->pipefds[0], F_GETFL, 0);
333         if (fd_flags < 0) goto err;
334         if (fcntl(handler->pipefds[0], F_SETFL, fd_flags | O_NONBLOCK) == -1) goto err;
335
336         if (pthread_mutex_init(&handler->sockets_mutex, NULL) != 0) goto err;
337         if (pthread_create(&handler->socket_thread, NULL, sock_thread_fn, handler) != 0) {
338                 pthread_mutex_destroy(&handler->sockets_mutex);
339                 goto err;
340         }
341
342         return handler;
343
344 err:
345         if (handler) {
346                 if (handler->pipefds[0] != -1) close(handler->pipefds[0]);
347                 if (handler->pipefds[1] != -1) close(handler->pipefds[1]);
348                 free(handler);
349         }
350         return NULL;
351 }
352
353 void interrupt_socket_handling(void* arg) {
354         struct SocketHandler *handler = (struct SocketHandler*) arg;
355         handler->should_exit = true;
356         uint8_t dummy = 0;
357         write(handler->pipefds[1], &dummy, 1);
358         void *retval;
359         int ret = pthread_join(handler->socket_thread, &retval);
360         assert(ret == 0);
361         free(handler);
362 }
363
364 int socket_connect(void* arg, LDKPublicKey pubkey, struct sockaddr *addr, size_t addrlen) {
365         struct SocketHandler *handler = (struct SocketHandler*) arg;
366
367         int fd = socket(addr->sa_family, SOCK_STREAM, 0);
368         if (fd < 0) return -1;
369
370         struct timeval timeout;
371         timeout.tv_sec = 1;
372         timeout.tv_usec = 0;
373         if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout))) return -2;
374         if (connect(fd, addr, addrlen)) return -3;
375         timeout.tv_sec = 120;
376         if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout))) return -3;
377
378         if (register_socket(handler, fd, 0)) return -4;
379
380         LDKSocketDescriptor descriptor = get_descriptor(handler, fd);
381         LDKCResult_CVec_u8ZPeerHandleErrorZ con_res = PeerManager_new_outbound_connection(&handler->ldk_peer_manager, pubkey, descriptor);
382         if (con_res.result_ok) {
383                 ssize_t write_count = send(fd, con_res.contents.result->data, con_res.contents.result->datalen, MSG_NOSIGNAL);
384                 if (write_count != con_res.contents.result->datalen)
385                         shutdown(fd, SHUT_RDWR);
386         } else {
387                 shutdown(fd, SHUT_RDWR);
388         }
389         CResult_CVec_u8ZPeerHandleErrorZ_free(con_res);
390
391         return 0;
392 }
393
394 int socket_bind(void* arg, struct sockaddr *addr, socklen_t addrlen) {
395         struct SocketHandler *handler = (struct SocketHandler*) arg;
396         int fd = socket(addr->sa_family, SOCK_STREAM, 0);
397         if (fd < 0) return -1;
398
399         int reuseon = 1;
400         if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseon, sizeof(reuseon))) return -2;
401
402         if (bind(fd, addr, addrlen)) return -3;
403         if (listen(fd, 32)) return -4;
404
405         if (register_socket(handler, fd, 1)) return -5;
406
407         return 0;
408 }