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 = POLLOUT;
116 descriptor->handler->pollfds[i].events = POLLIN;
121 lockres = pthread_mutex_unlock(&descriptor->handler->sockets_mutex);
122 assert(lockres == 0);
124 write(descriptor->handler->pipefds[1], &dummy, 1);
129 static void sock_disconnect(void* desc) {
130 struct Descriptor *descriptor = (struct Descriptor*)desc;
131 shutdown(descriptor->fd, SHUT_RDWR);
133 write(descriptor->handler->pipefds[1], &dummy, 1);
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;
140 static uint64_t sock_hash(const void* desc) {
141 const struct Descriptor *descriptor = (const struct Descriptor*)desc;
142 return (uint64_t)descriptor->fd;
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;
151 static void sock_free(void* desc) {
155 static inline LDKSocketDescriptor get_descriptor(struct SocketHandler *handler, int fd) {
156 struct Descriptor *desc = malloc(sizeof(struct Descriptor));
157 desc->handler = handler;
159 LDKSocketDescriptor ret = {
160 .this_arg = (void*)desc,
161 .send_data = sock_send_data,
162 .disconnect_socket = sock_disconnect,
165 .cloned = sock_cloned,
171 static void *sock_thread_fn(void* arg) {
172 struct SocketHandler *handler = (struct SocketHandler*) arg;
175 struct pollfd pollfds[MAX_CONNS + 1];
178 int close_socks[MAX_CONNS];
179 int close_socks_count = 0;
181 uint8_t readbuf[8192];
183 while (!handler->should_exit) {
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);
192 pollfds[fd_count].fd = handler->pipefds[0];
193 pollfds[fd_count].events = POLLIN;
196 int pollres = poll(pollfds, fd_count, 10000);
197 assert(pollres != -1);
198 close_socks_count = 0;
200 read(pollfds[fd_count-1].fd, readbuf, sizeof(readbuf)); // Empty out the pipe
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));
209 if (errno == EAGAIN || errno == EWOULDBLOCK) {
211 } else if (errno == EINVAL || errno == ENOTCONN) {
212 // Assume we're a listening socket!
213 int newfd = accept(pollfds[i].fd, NULL, NULL);
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);
223 CResult_NonePeerHandleErrorZ_free(con_res);
225 // Maybe it wasn't a listening socket, disconnect!
226 close_socks[close_socks_count++] = i;
229 close_socks[close_socks_count++] = i;
231 } else if (readlen == 0) {
233 close_socks[close_socks_count++] = i;
239 LDKCResult_boolPeerHandleErrorZ res = PeerManager_read_event(&handler->ldk_peer_manager, &descriptor, data);
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);
250 close_socks[close_socks_count++] = i;
252 CResult_boolPeerHandleErrorZ_free(res);
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;
260 CResult_NonePeerHandleErrorZ_free(res);
262 SocketDescriptor_free(descriptor);
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
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);
279 lockres = pthread_mutex_lock(&handler->sockets_mutex);
280 assert(lockres == 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);
287 handler->pollfds[i-close_idx] = handler->pollfds[i];
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);
295 PeerManager_process_events(&handler->ldk_peer_manager);
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);
306 for (int i = 0; i < handler->sockcount; i++) {
307 close(handler->pollfds[i].fd);
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);
319 void* init_socket_handling(const struct LDKPeerManager *NONNULL_PTR ldk_peer_manager) {
320 struct SocketHandler *handler = NULL;
322 handler = (struct SocketHandler*) calloc(1, sizeof(struct SocketHandler));
323 if (!handler) goto err;
324 handler->pipefds[0] = -1;
325 handler->pipefds[1] = -1;
327 handler->ldk_peer_manager = *ldk_peer_manager;
328 handler->should_exit = false;
330 if (pipe(handler->pipefds) != 0) goto err;
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;
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);
346 if (handler->pipefds[0] != -1) close(handler->pipefds[0]);
347 if (handler->pipefds[1] != -1) close(handler->pipefds[1]);
353 void interrupt_socket_handling(void* arg) {
354 struct SocketHandler *handler = (struct SocketHandler*) arg;
355 handler->should_exit = true;
357 write(handler->pipefds[1], &dummy, 1);
359 int ret = pthread_join(handler->socket_thread, &retval);
364 int socket_connect(void* arg, LDKPublicKey pubkey, struct sockaddr *addr, size_t addrlen) {
365 struct SocketHandler *handler = (struct SocketHandler*) arg;
367 int fd = socket(addr->sa_family, SOCK_STREAM, 0);
368 if (fd < 0) return -1;
370 struct timeval timeout;
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;
378 if (register_socket(handler, fd, 0)) return -4;
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);
387 shutdown(fd, SHUT_RDWR);
389 CResult_CVec_u8ZPeerHandleErrorZ_free(con_res);
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;
400 if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuseon, sizeof(reuseon))) return -2;
402 if (bind(fd, addr, addrlen)) return -3;
403 if (listen(fd, 32)) return -4;
405 if (register_socket(handler, fd, 1)) return -5;