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