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