1 // This file is Copyright its original authors, visible in version control
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
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.
18 #include <lightning.h>
20 #include <sys/socket.h>
22 #include <netinet/in.h>
23 #include <netinet/tcp.h>
35 #define MSG_NOSIGNAL 0
39 #define MAX_CONNS 1024
40 struct SocketHandler {
41 struct LDKPeerManager ldk_peer_manager;
42 pthread_t socket_thread;
45 // pollfds ands sockcount may only be written to with a lock on
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];
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;
60 if (!is_listen_sock) {
62 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (void*)&opt, sizeof(opt))) return -1;
64 if (setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void*)&opt, sizeof(opt))) return -1;
68 int lockres = pthread_mutex_lock(&handler->sockets_mutex);
71 handler->pollfds[handler->sockcount].fd = fd;
72 handler->pollfds[handler->sockcount].events = POLLIN;
73 handler->pollfds[handler->sockcount].revents = 0;
75 assert(handler->sockcount <= MAX_CONNS);
77 lockres = pthread_mutex_unlock(&handler->sockets_mutex);
81 write(handler->pipefds[1], &dummy, 1);
87 struct SocketHandler *handler;
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) {
100 shutdown(descriptor->fd, SHUT_RDWR);
102 write(descriptor->handler->pipefds[1], &dummy, 1);
105 } else if (write_count < data.datalen) {
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) {
114 descriptor->handler->pollfds[i].events &= POLLIN;
115 descriptor->handler->pollfds[i].events |= POLLOUT;
117 descriptor->handler->pollfds[i].events |= POLLIN;
122 lockres = pthread_mutex_unlock(&descriptor->handler->sockets_mutex);
123 assert(lockres == 0);
125 write(descriptor->handler->pipefds[1], &dummy, 1);
130 static void sock_disconnect(void* desc) {
131 struct Descriptor *descriptor = (struct Descriptor*)desc;
132 shutdown(descriptor->fd, SHUT_RDWR);
134 write(descriptor->handler->pipefds[1], &dummy, 1);
136 static bool sock_eq(const void* desc, const struct LDKSocketDescriptor *other_arg) {
137 const struct Descriptor *descriptor = (const struct Descriptor*)desc;
138 const struct Descriptor *other_descriptor = (const struct Descriptor*)other_arg->this_arg;
139 return descriptor->fd == other_descriptor->fd;
141 static uint64_t sock_hash(const void* desc) {
142 const struct Descriptor *descriptor = (const struct Descriptor*)desc;
143 return (uint64_t)descriptor->fd;
145 static void sock_cloned(LDKSocketDescriptor *NONNULL_PTR ldk_desc) {
146 const struct Descriptor *descriptor = (const struct Descriptor*)ldk_desc->this_arg;
147 struct Descriptor *new_desc = malloc(sizeof(struct Descriptor));
148 new_desc->handler = descriptor->handler;
149 new_desc->fd = descriptor->fd;
150 ldk_desc->this_arg = (void*) new_desc;
152 static void sock_free(void* desc) {
156 static inline LDKSocketDescriptor get_descriptor(struct SocketHandler *handler, int fd) {
157 struct Descriptor *desc = malloc(sizeof(struct Descriptor));
158 desc->handler = handler;
160 LDKSocketDescriptor ret = {
161 .this_arg = (void*)desc,
162 .send_data = sock_send_data,
163 .disconnect_socket = sock_disconnect,
166 .cloned = sock_cloned,
172 static void *sock_thread_fn(void* arg) {
173 struct SocketHandler *handler = (struct SocketHandler*) arg;
176 struct pollfd pollfds[MAX_CONNS + 1];
179 int close_socks[MAX_CONNS];
180 int close_socks_count = 0;
182 uint8_t readbuf[8192];
184 while (!handler->should_exit) {
186 lockres = pthread_mutex_lock(&handler->sockets_mutex);
187 assert(lockres == 0);
188 memcpy(pollfds, handler->pollfds, sizeof(struct pollfd) * handler->sockcount);
189 fd_count = handler->sockcount;
190 lockres = pthread_mutex_unlock(&handler->sockets_mutex);
191 assert(lockres == 0);
193 pollfds[fd_count].fd = handler->pipefds[0];
194 pollfds[fd_count].events = POLLIN;
197 int pollres = poll(pollfds, fd_count, 10000);
198 assert(pollres != -1);
199 close_socks_count = 0;
201 read(pollfds[fd_count-1].fd, readbuf, sizeof(readbuf)); // Empty out the pipe
204 for (int i = 0; i < fd_count - 1; i++) {
205 if (pollfds[i].revents) {
206 LDKSocketDescriptor descriptor = get_descriptor(handler, pollfds[i].fd);
207 if (pollfds[i].revents & POLLIN) {
208 int readlen = read(pollfds[i].fd, readbuf, sizeof(readbuf));
210 if (errno == EAGAIN || errno == EWOULDBLOCK) {
212 } else if (errno == EINVAL || errno == ENOTCONN) {
213 // Assume we're a listening socket!
214 int newfd = accept(pollfds[i].fd, NULL, NULL);
216 // Received a new connection, register it!
217 LDKSocketDescriptor new_descriptor = get_descriptor(handler, newfd);
218 LDKCResult_NonePeerHandleErrorZ con_res = PeerManager_new_inbound_connection(&handler->ldk_peer_manager, new_descriptor);
219 if (con_res.result_ok) {
220 if (register_socket(handler, newfd, 0))
221 shutdown(newfd, SHUT_RDWR);
224 CResult_NonePeerHandleErrorZ_free(con_res);
226 // Maybe it wasn't a listening socket, disconnect!
227 close_socks[close_socks_count++] = i;
230 close_socks[close_socks_count++] = i;
232 } else if (readlen == 0) {
234 close_socks[close_socks_count++] = i;
240 LDKCResult_boolPeerHandleErrorZ res = PeerManager_read_event(&handler->ldk_peer_manager, &descriptor, data);
242 if (*res.contents.result) {
243 lockres = pthread_mutex_lock(&handler->sockets_mutex);
244 assert(lockres == 0);
245 assert(handler->pollfds[i - 1].fd == pollfds[i].fd); // Only we change fd order!
246 handler->pollfds[i - 1].events &= POLLIN;
247 handler->pollfds[i - 1].events |= POLLOUT;
248 lockres = pthread_mutex_unlock(&handler->sockets_mutex);
249 assert(lockres == 0);
252 close_socks[close_socks_count++] = i;
254 CResult_boolPeerHandleErrorZ_free(res);
257 if (pollfds[i].revents & POLLOUT) {
258 LDKCResult_NonePeerHandleErrorZ res = PeerManager_write_buffer_space_avail(&handler->ldk_peer_manager, &descriptor);
259 if (!res.result_ok) {
260 close_socks[close_socks_count++] = i;
262 CResult_NonePeerHandleErrorZ_free(res);
264 SocketDescriptor_free(descriptor);
269 // We only do the actual socket disconnect handling in this thread,
270 // other threads may append to pollfds and call shutdown().
271 // Thus, in this thread, we first call socket_disconnected for each
272 // socket we're gonna remove, then we walk the sockets and close() each
273 // which should be disconnecting, shifting the remaining sockets down
275 for (int i = 0; i < close_socks_count; i++) {
276 LDKSocketDescriptor descriptor = get_descriptor(handler, handler->pollfds[close_socks[i]].fd);
277 PeerManager_socket_disconnected(&handler->ldk_peer_manager, &descriptor);
278 SocketDescriptor_free(descriptor);
281 lockres = pthread_mutex_lock(&handler->sockets_mutex);
282 assert(lockres == 0);
284 for (int i = 0; close_socks_count != 0 && i < handler->sockcount; i++) {
285 if (close_idx < close_socks_count && close_socks[close_idx] == i) {
286 close(handler->pollfds[i].fd);
289 handler->pollfds[i-close_idx] = handler->pollfds[i];
292 assert(close_idx == close_socks_count);
293 handler->sockcount -= close_socks_count;
294 lockres = pthread_mutex_unlock(&handler->sockets_mutex);
295 assert(lockres == 0);
297 PeerManager_process_events(&handler->ldk_peer_manager);
300 lockres = pthread_mutex_lock(&handler->sockets_mutex);
301 assert(lockres == 0);
302 for (int i = 0; i < handler->sockcount; i++) {
303 LDKSocketDescriptor descriptor = get_descriptor(handler, handler->pollfds[i].fd);
304 PeerManager_socket_disconnected(&handler->ldk_peer_manager, &descriptor);
305 SocketDescriptor_free(descriptor);
308 for (int i = 0; i < handler->sockcount; i++) {
309 close(handler->pollfds[i].fd);
311 close(handler->pipefds[0]);
312 close(handler->pipefds[1]);
313 handler->sockcount = 0;
314 lockres = pthread_mutex_unlock(&handler->sockets_mutex);
315 assert(lockres == 0);
321 void* init_socket_handling(const struct LDKPeerManager *NONNULL_PTR ldk_peer_manager) {
322 struct SocketHandler *handler = NULL;
324 handler = (struct SocketHandler*) calloc(1, sizeof(struct SocketHandler));
325 if (!handler) goto err;
326 handler->pipefds[0] = -1;
327 handler->pipefds[1] = -1;
329 handler->ldk_peer_manager = *ldk_peer_manager;
330 handler->should_exit = false;
332 if (pipe(handler->pipefds) != 0) goto err;
334 int fd_flags = fcntl(handler->pipefds[0], F_GETFL, 0);
335 if (fd_flags < 0) goto err;
336 if (fcntl(handler->pipefds[0], F_SETFL, fd_flags | O_NONBLOCK) == -1) goto err;
338 if (pthread_mutex_init(&handler->sockets_mutex, NULL) != 0) goto err;
339 if (pthread_create(&handler->socket_thread, NULL, sock_thread_fn, handler) != 0) {
340 pthread_mutex_destroy(&handler->sockets_mutex);
348 if (handler->pipefds[0] != -1) close(handler->pipefds[0]);
349 if (handler->pipefds[1] != -1) close(handler->pipefds[1]);
355 void interrupt_socket_handling(void* arg) {
356 struct SocketHandler *handler = (struct SocketHandler*) arg;
357 handler->should_exit = true;
359 write(handler->pipefds[1], &dummy, 1);
361 int ret = pthread_join(handler->socket_thread, &retval);
366 int socket_connect(void* arg, LDKPublicKey pubkey, struct sockaddr *addr, size_t addrlen) {
367 struct SocketHandler *handler = (struct SocketHandler*) arg;
369 int fd = socket(addr->sa_family, SOCK_STREAM, 0);
370 if (fd < 0) return -1;
372 struct timeval timeout;
375 if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout))) return -2;
376 if (connect(fd, addr, addrlen)) return -3;
377 timeout.tv_sec = 120;
378 if (setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout))) return -3;
380 if (register_socket(handler, fd, 0)) return -4;
382 LDKSocketDescriptor descriptor = get_descriptor(handler, fd);
383 LDKCResult_CVec_u8ZPeerHandleErrorZ con_res = PeerManager_new_outbound_connection(&handler->ldk_peer_manager, pubkey, descriptor);
384 if (con_res.result_ok) {
385 ssize_t write_count = send(fd, con_res.contents.result->data, con_res.contents.result->datalen, MSG_NOSIGNAL);
386 if (write_count != con_res.contents.result->datalen)
387 shutdown(fd, SHUT_RDWR);
389 shutdown(fd, SHUT_RDWR);
391 CResult_CVec_u8ZPeerHandleErrorZ_free(con_res);
396 int socket_bind(void* arg, struct sockaddr *addr, socklen_t addrlen) {
397 struct SocketHandler *handler = (struct SocketHandler*) arg;
398 int fd = socket(addr->sa_family, SOCK_STREAM, 0);
399 if (fd < 0) return -1;
402 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseon, sizeof(reuseon))) return -2;
404 if (bind(fd, addr, addrlen)) return -3;
405 if (listen(fd, 32)) return -4;
407 if (register_socket(handler, fd, 1)) return -5;