]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/socket-proxy/socket-proxyd.c
Merge pull request #10407 from yuwata/netlink-slot
[thirdparty/systemd.git] / src / socket-proxy / socket-proxyd.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <getopt.h>
6 #include <netdb.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/socket.h>
11 #include <sys/un.h>
12 #include <unistd.h>
13
14 #include "sd-daemon.h"
15 #include "sd-event.h"
16 #include "sd-resolve.h"
17
18 #include "alloc-util.h"
19 #include "fd-util.h"
20 #include "log.h"
21 #include "parse-util.h"
22 #include "path-util.h"
23 #include "set.h"
24 #include "socket-util.h"
25 #include "string-util.h"
26 #include "terminal-util.h"
27 #include "util.h"
28
29 #define BUFFER_SIZE (256 * 1024)
30 static unsigned arg_connections_max = 256;
31
32 static const char *arg_remote_host = NULL;
33
34 typedef struct Context {
35 sd_event *event;
36 sd_resolve *resolve;
37
38 Set *listen;
39 Set *connections;
40 } Context;
41
42 typedef struct Connection {
43 Context *context;
44
45 int server_fd, client_fd;
46 int server_to_client_buffer[2]; /* a pipe */
47 int client_to_server_buffer[2]; /* a pipe */
48
49 size_t server_to_client_buffer_full, client_to_server_buffer_full;
50 size_t server_to_client_buffer_size, client_to_server_buffer_size;
51
52 sd_event_source *server_event_source, *client_event_source;
53
54 sd_resolve_query *resolve_query;
55 } Connection;
56
57 static void connection_free(Connection *c) {
58 assert(c);
59
60 if (c->context)
61 set_remove(c->context->connections, c);
62
63 sd_event_source_unref(c->server_event_source);
64 sd_event_source_unref(c->client_event_source);
65
66 safe_close(c->server_fd);
67 safe_close(c->client_fd);
68
69 safe_close_pair(c->server_to_client_buffer);
70 safe_close_pair(c->client_to_server_buffer);
71
72 sd_resolve_query_unref(c->resolve_query);
73
74 free(c);
75 }
76
77 static void context_free(Context *context) {
78 assert(context);
79
80 set_free_with_destructor(context->listen, sd_event_source_unref);
81 set_free_with_destructor(context->connections, connection_free);
82
83 sd_event_unref(context->event);
84 sd_resolve_unref(context->resolve);
85 }
86
87 static int connection_create_pipes(Connection *c, int buffer[2], size_t *sz) {
88 int r;
89
90 assert(c);
91 assert(buffer);
92 assert(sz);
93
94 if (buffer[0] >= 0)
95 return 0;
96
97 r = pipe2(buffer, O_CLOEXEC|O_NONBLOCK);
98 if (r < 0)
99 return log_error_errno(errno, "Failed to allocate pipe buffer: %m");
100
101 (void) fcntl(buffer[0], F_SETPIPE_SZ, BUFFER_SIZE);
102
103 r = fcntl(buffer[0], F_GETPIPE_SZ);
104 if (r < 0)
105 return log_error_errno(errno, "Failed to get pipe buffer size: %m");
106
107 assert(r > 0);
108 *sz = r;
109
110 return 0;
111 }
112
113 static int connection_shovel(
114 Connection *c,
115 int *from, int buffer[2], int *to,
116 size_t *full, size_t *sz,
117 sd_event_source **from_source, sd_event_source **to_source) {
118
119 bool shoveled;
120
121 assert(c);
122 assert(from);
123 assert(buffer);
124 assert(buffer[0] >= 0);
125 assert(buffer[1] >= 0);
126 assert(to);
127 assert(full);
128 assert(sz);
129 assert(from_source);
130 assert(to_source);
131
132 do {
133 ssize_t z;
134
135 shoveled = false;
136
137 if (*full < *sz && *from >= 0 && *to >= 0) {
138 z = splice(*from, NULL, buffer[1], NULL, *sz - *full, SPLICE_F_MOVE|SPLICE_F_NONBLOCK);
139 if (z > 0) {
140 *full += z;
141 shoveled = true;
142 } else if (z == 0 || IN_SET(errno, EPIPE, ECONNRESET)) {
143 *from_source = sd_event_source_unref(*from_source);
144 *from = safe_close(*from);
145 } else if (!IN_SET(errno, EAGAIN, EINTR))
146 return log_error_errno(errno, "Failed to splice: %m");
147 }
148
149 if (*full > 0 && *to >= 0) {
150 z = splice(buffer[0], NULL, *to, NULL, *full, SPLICE_F_MOVE|SPLICE_F_NONBLOCK);
151 if (z > 0) {
152 *full -= z;
153 shoveled = true;
154 } else if (z == 0 || IN_SET(errno, EPIPE, ECONNRESET)) {
155 *to_source = sd_event_source_unref(*to_source);
156 *to = safe_close(*to);
157 } else if (!IN_SET(errno, EAGAIN, EINTR))
158 return log_error_errno(errno, "Failed to splice: %m");
159 }
160 } while (shoveled);
161
162 return 0;
163 }
164
165 static int connection_enable_event_sources(Connection *c);
166
167 static int traffic_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
168 Connection *c = userdata;
169 int r;
170
171 assert(s);
172 assert(fd >= 0);
173 assert(c);
174
175 r = connection_shovel(c,
176 &c->server_fd, c->server_to_client_buffer, &c->client_fd,
177 &c->server_to_client_buffer_full, &c->server_to_client_buffer_size,
178 &c->server_event_source, &c->client_event_source);
179 if (r < 0)
180 goto quit;
181
182 r = connection_shovel(c,
183 &c->client_fd, c->client_to_server_buffer, &c->server_fd,
184 &c->client_to_server_buffer_full, &c->client_to_server_buffer_size,
185 &c->client_event_source, &c->server_event_source);
186 if (r < 0)
187 goto quit;
188
189 /* EOF on both sides? */
190 if (c->server_fd == -1 && c->client_fd == -1)
191 goto quit;
192
193 /* Server closed, and all data written to client? */
194 if (c->server_fd == -1 && c->server_to_client_buffer_full <= 0)
195 goto quit;
196
197 /* Client closed, and all data written to server? */
198 if (c->client_fd == -1 && c->client_to_server_buffer_full <= 0)
199 goto quit;
200
201 r = connection_enable_event_sources(c);
202 if (r < 0)
203 goto quit;
204
205 return 1;
206
207 quit:
208 connection_free(c);
209 return 0; /* ignore errors, continue serving */
210 }
211
212 static int connection_enable_event_sources(Connection *c) {
213 uint32_t a = 0, b = 0;
214 int r;
215
216 assert(c);
217
218 if (c->server_to_client_buffer_full > 0)
219 b |= EPOLLOUT;
220 if (c->server_to_client_buffer_full < c->server_to_client_buffer_size)
221 a |= EPOLLIN;
222
223 if (c->client_to_server_buffer_full > 0)
224 a |= EPOLLOUT;
225 if (c->client_to_server_buffer_full < c->client_to_server_buffer_size)
226 b |= EPOLLIN;
227
228 if (c->server_event_source)
229 r = sd_event_source_set_io_events(c->server_event_source, a);
230 else if (c->server_fd >= 0)
231 r = sd_event_add_io(c->context->event, &c->server_event_source, c->server_fd, a, traffic_cb, c);
232 else
233 r = 0;
234
235 if (r < 0)
236 return log_error_errno(r, "Failed to set up server event source: %m");
237
238 if (c->client_event_source)
239 r = sd_event_source_set_io_events(c->client_event_source, b);
240 else if (c->client_fd >= 0)
241 r = sd_event_add_io(c->context->event, &c->client_event_source, c->client_fd, b, traffic_cb, c);
242 else
243 r = 0;
244
245 if (r < 0)
246 return log_error_errno(r, "Failed to set up client event source: %m");
247
248 return 0;
249 }
250
251 static int connection_complete(Connection *c) {
252 int r;
253
254 assert(c);
255
256 r = connection_create_pipes(c, c->server_to_client_buffer, &c->server_to_client_buffer_size);
257 if (r < 0)
258 goto fail;
259
260 r = connection_create_pipes(c, c->client_to_server_buffer, &c->client_to_server_buffer_size);
261 if (r < 0)
262 goto fail;
263
264 r = connection_enable_event_sources(c);
265 if (r < 0)
266 goto fail;
267
268 return 0;
269
270 fail:
271 connection_free(c);
272 return 0; /* ignore errors, continue serving */
273 }
274
275 static int connect_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
276 Connection *c = userdata;
277 socklen_t solen;
278 int error, r;
279
280 assert(s);
281 assert(fd >= 0);
282 assert(c);
283
284 solen = sizeof(error);
285 r = getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &solen);
286 if (r < 0) {
287 log_error_errno(errno, "Failed to issue SO_ERROR: %m");
288 goto fail;
289 }
290
291 if (error != 0) {
292 log_error_errno(error, "Failed to connect to remote host: %m");
293 goto fail;
294 }
295
296 c->client_event_source = sd_event_source_unref(c->client_event_source);
297
298 return connection_complete(c);
299
300 fail:
301 connection_free(c);
302 return 0; /* ignore errors, continue serving */
303 }
304
305 static int connection_start(Connection *c, struct sockaddr *sa, socklen_t salen) {
306 int r;
307
308 assert(c);
309 assert(sa);
310 assert(salen);
311
312 c->client_fd = socket(sa->sa_family, SOCK_STREAM|SOCK_NONBLOCK|SOCK_CLOEXEC, 0);
313 if (c->client_fd < 0) {
314 log_error_errno(errno, "Failed to get remote socket: %m");
315 goto fail;
316 }
317
318 r = connect(c->client_fd, sa, salen);
319 if (r < 0) {
320 if (errno == EINPROGRESS) {
321 r = sd_event_add_io(c->context->event, &c->client_event_source, c->client_fd, EPOLLOUT, connect_cb, c);
322 if (r < 0) {
323 log_error_errno(r, "Failed to add connection socket: %m");
324 goto fail;
325 }
326
327 r = sd_event_source_set_enabled(c->client_event_source, SD_EVENT_ONESHOT);
328 if (r < 0) {
329 log_error_errno(r, "Failed to enable oneshot event source: %m");
330 goto fail;
331 }
332 } else {
333 log_error_errno(errno, "Failed to connect to remote host: %m");
334 goto fail;
335 }
336 } else {
337 r = connection_complete(c);
338 if (r < 0)
339 goto fail;
340 }
341
342 return 0;
343
344 fail:
345 connection_free(c);
346 return 0; /* ignore errors, continue serving */
347 }
348
349 static int resolve_cb(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) {
350 Connection *c = userdata;
351
352 assert(q);
353 assert(c);
354
355 if (ret != 0) {
356 log_error("Failed to resolve host: %s", gai_strerror(ret));
357 goto fail;
358 }
359
360 c->resolve_query = sd_resolve_query_unref(c->resolve_query);
361
362 return connection_start(c, ai->ai_addr, ai->ai_addrlen);
363
364 fail:
365 connection_free(c);
366 return 0; /* ignore errors, continue serving */
367 }
368
369 static int resolve_remote(Connection *c) {
370
371 static const struct addrinfo hints = {
372 .ai_family = AF_UNSPEC,
373 .ai_socktype = SOCK_STREAM,
374 .ai_flags = AI_ADDRCONFIG
375 };
376
377 union sockaddr_union sa = {};
378 const char *node, *service;
379 int r;
380
381 if (IN_SET(arg_remote_host[0], '/', '@')) {
382 int salen;
383
384 salen = sockaddr_un_set_path(&sa.un, arg_remote_host);
385 if (salen < 0) {
386 log_error_errno(salen, "Specified address doesn't fit in an AF_UNIX address, refusing: %m");
387 goto fail;
388 }
389
390 return connection_start(c, &sa.sa, salen);
391 }
392
393 service = strrchr(arg_remote_host, ':');
394 if (service) {
395 node = strndupa(arg_remote_host, service - arg_remote_host);
396 service++;
397 } else {
398 node = arg_remote_host;
399 service = "80";
400 }
401
402 log_debug("Looking up address info for %s:%s", node, service);
403 r = sd_resolve_getaddrinfo(c->context->resolve, &c->resolve_query, node, service, &hints, resolve_cb, c);
404 if (r < 0) {
405 log_error_errno(r, "Failed to resolve remote host: %m");
406 goto fail;
407 }
408
409 return 0;
410
411 fail:
412 connection_free(c);
413 return 0; /* ignore errors, continue serving */
414 }
415
416 static int add_connection_socket(Context *context, int fd) {
417 Connection *c;
418 int r;
419
420 assert(context);
421 assert(fd >= 0);
422
423 if (set_size(context->connections) > arg_connections_max) {
424 log_warning("Hit connection limit, refusing connection.");
425 safe_close(fd);
426 return 0;
427 }
428
429 r = set_ensure_allocated(&context->connections, NULL);
430 if (r < 0) {
431 log_oom();
432 return 0;
433 }
434
435 c = new0(Connection, 1);
436 if (!c) {
437 log_oom();
438 return 0;
439 }
440
441 c->context = context;
442 c->server_fd = fd;
443 c->client_fd = -1;
444 c->server_to_client_buffer[0] = c->server_to_client_buffer[1] = -1;
445 c->client_to_server_buffer[0] = c->client_to_server_buffer[1] = -1;
446
447 r = set_put(context->connections, c);
448 if (r < 0) {
449 free(c);
450 log_oom();
451 return 0;
452 }
453
454 return resolve_remote(c);
455 }
456
457 static int accept_cb(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
458 _cleanup_free_ char *peer = NULL;
459 Context *context = userdata;
460 int nfd = -1, r;
461
462 assert(s);
463 assert(fd >= 0);
464 assert(revents & EPOLLIN);
465 assert(context);
466
467 nfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
468 if (nfd < 0) {
469 if (errno != -EAGAIN)
470 log_warning_errno(errno, "Failed to accept() socket: %m");
471 } else {
472 getpeername_pretty(nfd, true, &peer);
473 log_debug("New connection from %s", strna(peer));
474
475 r = add_connection_socket(context, nfd);
476 if (r < 0) {
477 log_error_errno(r, "Failed to accept connection, ignoring: %m");
478 safe_close(fd);
479 }
480 }
481
482 r = sd_event_source_set_enabled(s, SD_EVENT_ONESHOT);
483 if (r < 0) {
484 log_error_errno(r, "Error while re-enabling listener with ONESHOT: %m");
485 sd_event_exit(context->event, r);
486 return r;
487 }
488
489 return 1;
490 }
491
492 static int add_listen_socket(Context *context, int fd) {
493 sd_event_source *source;
494 int r;
495
496 assert(context);
497 assert(fd >= 0);
498
499 r = set_ensure_allocated(&context->listen, NULL);
500 if (r < 0) {
501 log_oom();
502 return r;
503 }
504
505 r = sd_is_socket(fd, 0, SOCK_STREAM, 1);
506 if (r < 0)
507 return log_error_errno(r, "Failed to determine socket type: %m");
508 if (r == 0) {
509 log_error("Passed in socket is not a stream socket.");
510 return -EINVAL;
511 }
512
513 r = fd_nonblock(fd, true);
514 if (r < 0)
515 return log_error_errno(r, "Failed to mark file descriptor non-blocking: %m");
516
517 r = sd_event_add_io(context->event, &source, fd, EPOLLIN, accept_cb, context);
518 if (r < 0)
519 return log_error_errno(r, "Failed to add event source: %m");
520
521 r = set_put(context->listen, source);
522 if (r < 0) {
523 log_error_errno(r, "Failed to add source to set: %m");
524 sd_event_source_unref(source);
525 return r;
526 }
527
528 /* Set the watcher to oneshot in case other processes are also
529 * watching to accept(). */
530 r = sd_event_source_set_enabled(source, SD_EVENT_ONESHOT);
531 if (r < 0)
532 return log_error_errno(r, "Failed to enable oneshot mode: %m");
533
534 return 0;
535 }
536
537 static int help(void) {
538 _cleanup_free_ char *link = NULL;
539 int r;
540
541 r = terminal_urlify_man("systemd-socket-proxyd", "8", &link);
542 if (r < 0)
543 return log_oom();
544
545 printf("%1$s [HOST:PORT]\n"
546 "%1$s [SOCKET]\n\n"
547 "Bidirectionally proxy local sockets to another (possibly remote) socket.\n\n"
548 " -c --connections-max= Set the maximum number of connections to be accepted\n"
549 " -h --help Show this help\n"
550 " --version Show package version\n"
551 "\nSee the %2$s for details.\n"
552 , program_invocation_short_name
553 , link
554 );
555
556 return 0;
557 }
558
559 static int parse_argv(int argc, char *argv[]) {
560
561 enum {
562 ARG_VERSION = 0x100,
563 ARG_IGNORE_ENV
564 };
565
566 static const struct option options[] = {
567 { "connections-max", required_argument, NULL, 'c' },
568 { "help", no_argument, NULL, 'h' },
569 { "version", no_argument, NULL, ARG_VERSION },
570 {}
571 };
572
573 int c, r;
574
575 assert(argc >= 0);
576 assert(argv);
577
578 while ((c = getopt_long(argc, argv, "c:h", options, NULL)) >= 0)
579
580 switch (c) {
581
582 case 'h':
583 return help();
584
585 case ARG_VERSION:
586 return version();
587
588 case 'c':
589 r = safe_atou(optarg, &arg_connections_max);
590 if (r < 0) {
591 log_error("Failed to parse --connections-max= argument: %s", optarg);
592 return r;
593 }
594
595 if (arg_connections_max < 1) {
596 log_error("Connection limit is too low.");
597 return -EINVAL;
598 }
599
600 break;
601
602 case '?':
603 return -EINVAL;
604
605 default:
606 assert_not_reached("Unhandled option");
607 }
608
609 if (optind >= argc) {
610 log_error("Not enough parameters.");
611 return -EINVAL;
612 }
613
614 if (argc != optind+1) {
615 log_error("Too many parameters.");
616 return -EINVAL;
617 }
618
619 arg_remote_host = argv[optind];
620 return 1;
621 }
622
623 int main(int argc, char *argv[]) {
624 Context context = {};
625 int r, n, fd;
626
627 log_parse_environment();
628 log_open();
629
630 r = parse_argv(argc, argv);
631 if (r <= 0)
632 goto finish;
633
634 r = sd_event_default(&context.event);
635 if (r < 0) {
636 log_error_errno(r, "Failed to allocate event loop: %m");
637 goto finish;
638 }
639
640 r = sd_resolve_default(&context.resolve);
641 if (r < 0) {
642 log_error_errno(r, "Failed to allocate resolver: %m");
643 goto finish;
644 }
645
646 r = sd_resolve_attach_event(context.resolve, context.event, 0);
647 if (r < 0) {
648 log_error_errno(r, "Failed to attach resolver: %m");
649 goto finish;
650 }
651
652 sd_event_set_watchdog(context.event, true);
653
654 n = sd_listen_fds(1);
655 if (n < 0) {
656 log_error("Failed to receive sockets from parent.");
657 r = n;
658 goto finish;
659 } else if (n == 0) {
660 log_error("Didn't get any sockets passed in.");
661 r = -EINVAL;
662 goto finish;
663 }
664
665 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
666 r = add_listen_socket(&context, fd);
667 if (r < 0)
668 goto finish;
669 }
670
671 r = sd_event_loop(context.event);
672 if (r < 0) {
673 log_error_errno(r, "Failed to run event loop: %m");
674 goto finish;
675 }
676
677 finish:
678 context_free(&context);
679
680 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
681 }